(function(){window.MLD={};MLD.mylifeApiUrl='https://api-stage.mylife.com';MLD.WebWidget=function(name,options,selector)
{var id='MLD-'+name+'-'+Date.UTC()+'-'+Math.floor(Math.random()*10001);if(selector==null)
{document.write('<div id="'+id+'"> </div>');}
else
{jQuery(selector).html('<div id="'+id+'"> </div>');}
jQuery('#'+id)[name](options);};

jQuery.extend({createUploadIframe:function(id,uri)
{var frameId='jUploadFrame'+id;if(window.ActiveXObject){var io=document.createElement('<iframe id="'+frameId+'" name="'+frameId+'" />');if(typeof uri=='boolean'){io.src='javascript:false';}
else if(typeof uri=='string'){io.src=uri;}}
else{var io=document.createElement('iframe');io.id=frameId;io.name=frameId;}
io.style.position='absolute';io.style.top='-1000px';io.style.left='-1000px';document.body.appendChild(io);return io},createUploadForm:function(id,fileElementId)
{var formId='jUploadForm'+id;var fileId='jUploadFile'+id;var form=$('<form  action="" method="POST" name="'+formId+'" id="'+formId+'" enctype="multipart/form-data"></form>');var oldElement=$('#'+fileElementId);var newElement=$(oldElement).clone();$(oldElement).attr('id',fileId);$(oldElement).before(newElement);$(oldElement).appendTo(form);$(form).css('position','absolute');$(form).css('top','-1200px');$(form).css('left','-1200px');$(form).appendTo('body');return form;},ajaxFileUpload:function(s){s=jQuery.extend({},jQuery.ajaxSettings,s);var id=new Date().getTime()
var form=jQuery.createUploadForm(id,s.fileElementId);var io=jQuery.createUploadIframe(id,s.secureuri);var frameId='jUploadFrame'+id;var formId='jUploadForm'+id;if(s.global&&!jQuery.active++)
{jQuery.event.trigger("ajaxStart");}
var requestDone=false;var xml={}
if(s.global)
jQuery.event.trigger("ajaxSend",[xml,s]);var uploadCallback=function(isTimeout)
{var io=document.getElementById(frameId);try
{if(io.contentWindow)
{xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}else if(io.contentDocument)
{xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;}}catch(e)
{jQuery.handleError(s,xml,null,e);}
if(xml||isTimeout=="timeout")
{requestDone=true;var status;try{status=isTimeout!="timeout"?"success":"error";if(status!="error")
{var data=jQuery.uploadHttpData(xml,s.dataType);if(s.success)
s.success(data,status);if(s.global)
jQuery.event.trigger("ajaxSuccess",[xml,s]);}else
jQuery.handleError(s,xml,status);}catch(e)
{status="error";jQuery.handleError(s,xml,status,e);}
if(s.global)
jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)
jQuery.event.trigger("ajaxStop");if(s.complete)
s.complete(xml,status);jQuery(io).unbind()
setTimeout(function()
{try
{$(io).remove();$(form).remove();}catch(e)
{jQuery.handleError(s,xml,null,e);}},100)
xml=null}}
if(s.timeout>0)
{setTimeout(function(){if(!requestDone)uploadCallback("timeout");},s.timeout);}
try
{var form=$('#'+formId);$(form).attr('action',s.url);$(form).attr('method','POST');$(form).attr('target',frameId);if(form.encoding)
{form.encoding='multipart/form-data';}
else
{form.enctype='multipart/form-data';}
$(form).submit();}catch(e)
{jQuery.handleError(s,xml,null,e);}
if(window.attachEvent){document.getElementById(frameId).attachEvent('onload',uploadCallback);}
else{document.getElementById(frameId).addEventListener('load',uploadCallback,false);}
return{abort:function(){}};},uploadHttpData:function(r,type){var data=!type;data=type=="xml"||data?r.responseXML:r.responseText;if(type=="script")
jQuery.globalEval(data);if(type=="json")
eval("data = "+data);if(type=="html")
jQuery("<div>").html(data).evalScripts();return data;}});

(function($){var ColorPicker=function(){var
ids={},inAction,charMin=65,visible,tpl='<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',defaults={eventName:'click',onShow:function(){},onBeforeShow:function(){},onHide:function(){},onChange:function(){},onSubmit:function(){},color:'ff0000',livePreview:true,flat:false},fillRGBFields=function(hsb,cal){var rgb=HSBToRGB(hsb);$(cal).data('colorpicker').fields.eq(1).val(rgb.r).end().eq(2).val(rgb.g).end().eq(3).val(rgb.b).end();},fillHSBFields=function(hsb,cal){$(cal).data('colorpicker').fields.eq(4).val(hsb.h).end().eq(5).val(hsb.s).end().eq(6).val(hsb.b).end();},fillHexFields=function(hsb,cal){$(cal).data('colorpicker').fields.eq(0).val(HSBToHex(hsb)).end();},setSelector=function(hsb,cal){$(cal).data('colorpicker').selector.css('backgroundColor','#'+HSBToHex({h:hsb.h,s:100,b:100}));$(cal).data('colorpicker').selectorIndic.css({left:parseInt(150*hsb.s/100,10),top:parseInt(150*(100-hsb.b)/100,10)});},setHue=function(hsb,cal){$(cal).data('colorpicker').hue.css('top',parseInt(150-150*hsb.h/360,10));},setCurrentColor=function(hsb,cal){$(cal).data('colorpicker').currentColor.css('backgroundColor','#'+HSBToHex(hsb));},setNewColor=function(hsb,cal){$(cal).data('colorpicker').newColor.css('backgroundColor','#'+HSBToHex(hsb));},keyDown=function(ev){var pressedKey=ev.charCode||ev.keyCode||-1;if((pressedKey>charMin&&pressedKey<=90)||pressedKey==32){return false;}
var cal=$(this).parent().parent();if(cal.data('colorpicker').livePreview===true){change.apply(this);}},change=function(ev){var cal=$(this).parent().parent(),col;if(this.parentNode.className.indexOf('_hex')>0){cal.data('colorpicker').color=col=HexToHSB(fixHex(this.value));}else if(this.parentNode.className.indexOf('_hsb')>0){cal.data('colorpicker').color=col=fixHSB({h:parseInt(cal.data('colorpicker').fields.eq(4).val(),10),s:parseInt(cal.data('colorpicker').fields.eq(5).val(),10),b:parseInt(cal.data('colorpicker').fields.eq(6).val(),10)});}else{cal.data('colorpicker').color=col=RGBToHSB(fixRGB({r:parseInt(cal.data('colorpicker').fields.eq(1).val(),10),g:parseInt(cal.data('colorpicker').fields.eq(2).val(),10),b:parseInt(cal.data('colorpicker').fields.eq(3).val(),10)}));}
if(ev){fillRGBFields(col,cal.get(0));fillHexFields(col,cal.get(0));fillHSBFields(col,cal.get(0));}
setSelector(col,cal.get(0));setHue(col,cal.get(0));setNewColor(col,cal.get(0));cal.data('colorpicker').onChange.apply(cal,[col,HSBToHex(col),HSBToRGB(col)]);},blur=function(ev){var cal=$(this).parent().parent();cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');},focus=function(){charMin=this.parentNode.className.indexOf('_hex')>0?70:65;$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');$(this).parent().addClass('colorpicker_focus');},downIncrement=function(ev){var field=$(this).parent().find('input').focus();var current={el:$(this).parent().addClass('colorpicker_slider'),max:this.parentNode.className.indexOf('_hsb_h')>0?360:(this.parentNode.className.indexOf('_hsb')>0?100:255),y:ev.pageY,field:field,val:parseInt(field.val(),10),preview:$(this).parent().parent().data('colorpicker').livePreview};$(document).bind('mouseup',current,upIncrement);$(document).bind('mousemove',current,moveIncrement);},moveIncrement=function(ev){ev.data.field.val(Math.max(0,Math.min(ev.data.max,parseInt(ev.data.val+ev.pageY-ev.data.y,10))));if(ev.data.preview){change.apply(ev.data.field.get(0),[true]);}
return false;},upIncrement=function(ev){change.apply(ev.data.field.get(0),[true]);ev.data.el.removeClass('colorpicker_slider').find('input').focus();$(document).unbind('mouseup',upIncrement);$(document).unbind('mousemove',moveIncrement);return false;},downHue=function(ev){var current={cal:$(this).parent(),y:$(this).offset().top};current.preview=current.cal.data('colorpicker').livePreview;$(document).bind('mouseup',current,upHue);$(document).bind('mousemove',current,moveHue);},moveHue=function(ev){change.apply(ev.data.cal.data('colorpicker').fields.eq(4).val(parseInt(360*(150-Math.max(0,Math.min(150,(ev.pageY-ev.data.y))))/150,10)).get(0),[ev.data.preview]);return false;},upHue=function(ev){fillRGBFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));fillHexFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));$(document).unbind('mouseup',upHue);$(document).unbind('mousemove',moveHue);return false;},downSelector=function(ev){var current={cal:$(this).parent(),pos:$(this).offset()};current.preview=current.cal.data('colorpicker').livePreview;$(document).bind('mouseup',current,upSelector);$(document).bind('mousemove',current,moveSelector);},moveSelector=function(ev){change.apply(ev.data.cal.data('colorpicker').fields.eq(6).val(parseInt(100*(150-Math.max(0,Math.min(150,(ev.pageY-ev.data.pos.top))))/150,10)).end().eq(5).val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX-ev.data.pos.left))))/150,10)).get(0),[ev.data.preview]);return false;},upSelector=function(ev){fillRGBFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));fillHexFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));$(document).unbind('mouseup',upSelector);$(document).unbind('mousemove',moveSelector);return false;},enterSubmit=function(ev){$(this).addClass('colorpicker_focus');},leaveSubmit=function(ev){$(this).removeClass('colorpicker_focus');},clickSubmit=function(ev){var cal=$(this).parent();var col=cal.data('colorpicker').color;cal.data('colorpicker').origColor=col;setCurrentColor(col,cal.get(0));cal.data('colorpicker').onSubmit(col,HSBToHex(col),HSBToRGB(col),cal.data('colorpicker').el);},show=function(ev){var cal=$('#'+$(this).data('colorpickerId'));cal.data('colorpicker').onBeforeShow.apply(this,[cal.get(0)]);var pos=$(this).offset();var viewPort=getViewport();var top=pos.top+this.offsetHeight;var left=pos.left;if(top+176>viewPort.t+viewPort.h){top-=this.offsetHeight+176;}
if(left+356>viewPort.l+viewPort.w){left-=356;}
cal.css({left:left+'px',top:top+'px'});if(cal.data('colorpicker').onShow.apply(this,[cal.get(0)])!=false){cal.show();}
$(document).bind('mousedown',{cal:cal},hide);return false;},hide=function(ev){if(!isChildOf(ev.data.cal.get(0),ev.target,ev.data.cal.get(0))){if(ev.data.cal.data('colorpicker').onHide.apply(this,[ev.data.cal.get(0)])!=false){ev.data.cal.hide();}
$(document).unbind('mousedown',hide);}},isChildOf=function(parentEl,el,container){if(parentEl==el){return true;}
if(parentEl.contains){return parentEl.contains(el);}
if(parentEl.compareDocumentPosition){return!!(parentEl.compareDocumentPosition(el)&16);}
var prEl=el.parentNode;while(prEl&&prEl!=container){if(prEl==parentEl)
return true;prEl=prEl.parentNode;}
return false;},getViewport=function(){var m=document.compatMode=='CSS1Compat';return{l:window.pageXOffset||(m?document.documentElement.scrollLeft:document.body.scrollLeft),t:window.pageYOffset||(m?document.documentElement.scrollTop:document.body.scrollTop),w:window.innerWidth||(m?document.documentElement.clientWidth:document.body.clientWidth),h:window.innerHeight||(m?document.documentElement.clientHeight:document.body.clientHeight)};},fixHSB=function(hsb){return{h:Math.min(360,Math.max(0,hsb.h)),s:Math.min(100,Math.max(0,hsb.s)),b:Math.min(100,Math.max(0,hsb.b))};},fixRGB=function(rgb){return{r:Math.min(255,Math.max(0,rgb.r)),g:Math.min(255,Math.max(0,rgb.g)),b:Math.min(255,Math.max(0,rgb.b))};},fixHex=function(hex){var len=6-hex.length;if(len>0){var o=[];for(var i=0;i<len;i++){o.push('0');}
o.push(hex);hex=o.join('');}
return hex;},HexToRGB=function(hex){var hex=parseInt(((hex.indexOf('#')>-1)?hex.substring(1):hex),16);return{r:hex>>16,g:(hex&0x00FF00)>>8,b:(hex&0x0000FF)};},HexToHSB=function(hex){return RGBToHSB(HexToRGB(hex));},RGBToHSB=function(rgb){var hsb={h:0,s:0,b:0};var min=Math.min(rgb.r,rgb.g,rgb.b);var max=Math.max(rgb.r,rgb.g,rgb.b);var delta=max-min;hsb.b=max;if(max!=0){}
hsb.s=max!=0?255*delta/max:0;if(hsb.s!=0){if(rgb.r==max){hsb.h=(rgb.g-rgb.b)/delta;}else if(rgb.g==max){hsb.h=2+(rgb.b-rgb.r)/delta;}else{hsb.h=4+(rgb.r-rgb.g)/delta;}}else{hsb.h=-1;}
hsb.h*=60;if(hsb.h<0){hsb.h+=360;}
hsb.s*=100/255;hsb.b*=100/255;return hsb;},HSBToRGB=function(hsb){var rgb={};var h=Math.round(hsb.h);var s=Math.round(hsb.s*255/100);var v=Math.round(hsb.b*255/100);if(s==0){rgb.r=rgb.g=rgb.b=v;}else{var t1=v;var t2=(255-s)*v/255;var t3=(t1-t2)*(h%60)/60;if(h==360)h=0;if(h<60){rgb.r=t1;rgb.b=t2;rgb.g=t2+t3}
else if(h<120){rgb.g=t1;rgb.b=t2;rgb.r=t1-t3}
else if(h<180){rgb.g=t1;rgb.r=t2;rgb.b=t2+t3}
else if(h<240){rgb.b=t1;rgb.r=t2;rgb.g=t1-t3}
else if(h<300){rgb.b=t1;rgb.g=t2;rgb.r=t2+t3}
else if(h<360){rgb.r=t1;rgb.g=t2;rgb.b=t1-t3}
else{rgb.r=0;rgb.g=0;rgb.b=0}}
return{r:Math.round(rgb.r),g:Math.round(rgb.g),b:Math.round(rgb.b)};},RGBToHex=function(rgb){var hex=[rgb.r.toString(16),rgb.g.toString(16),rgb.b.toString(16)];$.each(hex,function(nr,val){if(val.length==1){hex[nr]='0'+val;}});return hex.join('');},HSBToHex=function(hsb){return RGBToHex(HSBToRGB(hsb));},restoreOriginal=function(){var cal=$(this).parent();var col=cal.data('colorpicker').origColor;cal.data('colorpicker').color=col;fillRGBFields(col,cal.get(0));fillHexFields(col,cal.get(0));fillHSBFields(col,cal.get(0));setSelector(col,cal.get(0));setHue(col,cal.get(0));setNewColor(col,cal.get(0));};return{init:function(opt){opt=$.extend({},defaults,opt||{});if(typeof opt.color=='string'){opt.color=HexToHSB(opt.color);}else if(opt.color.r!=undefined&&opt.color.g!=undefined&&opt.color.b!=undefined){opt.color=RGBToHSB(opt.color);}else if(opt.color.h!=undefined&&opt.color.s!=undefined&&opt.color.b!=undefined){opt.color=fixHSB(opt.color);}else{return this;}
return this.each(function(){if(!$(this).data('colorpickerId')){var options=$.extend({},opt);options.origColor=opt.color;var id='collorpicker_'+parseInt(Math.random()*1000);$(this).data('colorpickerId',id);var cal=$(tpl).attr('id',id);if(options.flat){cal.appendTo(this).show();}else{cal.appendTo(document.body);}
options.fields=cal.find('input').bind('keyup',keyDown).bind('change',change).bind('blur',blur).bind('focus',focus);cal.find('span').bind('mousedown',downIncrement).end().find('>div.colorpicker_current_color').bind('click',restoreOriginal);options.selector=cal.find('div.colorpicker_color').bind('mousedown',downSelector);options.selectorIndic=options.selector.find('div div');options.el=this;options.hue=cal.find('div.colorpicker_hue div');cal.find('div.colorpicker_hue').bind('mousedown',downHue);options.newColor=cal.find('div.colorpicker_new_color');options.currentColor=cal.find('div.colorpicker_current_color');cal.data('colorpicker',options);cal.find('div.colorpicker_submit').bind('mouseenter',enterSubmit).bind('mouseleave',leaveSubmit).bind('click',clickSubmit);fillRGBFields(options.color,cal.get(0));fillHSBFields(options.color,cal.get(0));fillHexFields(options.color,cal.get(0));setHue(options.color,cal.get(0));setSelector(options.color,cal.get(0));setCurrentColor(options.color,cal.get(0));setNewColor(options.color,cal.get(0));if(options.flat){cal.css({position:'relative',display:'block'});}else{$(this).bind(options.eventName,show);}}});},showPicker:function(){return this.each(function(){if($(this).data('colorpickerId')){show.apply(this);}});},hidePicker:function(){return this.each(function(){if($(this).data('colorpickerId')){$('#'+$(this).data('colorpickerId')).hide();}});},setColor:function(col){if(typeof col=='string'){col=HexToHSB(col);}else if(col.r!=undefined&&col.g!=undefined&&col.b!=undefined){col=RGBToHSB(col);}else if(col.h!=undefined&&col.s!=undefined&&col.b!=undefined){col=fixHSB(col);}else{return this;}
return this.each(function(){if($(this).data('colorpickerId')){var cal=$('#'+$(this).data('colorpickerId'));cal.data('colorpicker').color=col;cal.data('colorpicker').origColor=col;fillRGBFields(col,cal.get(0));fillHSBFields(col,cal.get(0));fillHexFields(col,cal.get(0));setHue(col,cal.get(0));setSelector(col,cal.get(0));setCurrentColor(col,cal.get(0));setNewColor(col,cal.get(0));}});}};}();$.fn.extend({ColorPicker:ColorPicker.init,ColorPickerHide:ColorPicker.hidePicker,ColorPickerShow:ColorPicker.showPicker,ColorPickerSetColor:ColorPicker.setColor});})(jQuery);

(function($){var abs=Math.abs,max=Math.max,min=Math.min,round=Math.round;function div(){return $('<div/>')}$.imgAreaSelect=function(img,options){var $img=$(img),imgLoaded,$box=div(),$area=div(),$border=div().add(div()).add(div()).add(div()),$outer=div().add(div()).add(div()).add(div()),$handles=$([]),$areaOpera,left,top,imgOfs={left:0,top:0},imgWidth,imgHeight,$parent,parOfs={left:0,top:0},zIndex=0,position='absolute',startX,startY,scaleX,scaleY,resize,minWidth,minHeight,maxWidth,maxHeight,aspectRatio,shown,x1,y1,x2,y2,selection={x1:0,y1:0,x2:0,y2:0,width:0,height:0},docElem=document.documentElement,$p,d,i,o,w,h,adjusted;function viewX(x){return x+imgOfs.left-parOfs.left}function viewY(y){return y+imgOfs.top-parOfs.top}function selX(x){return x-imgOfs.left+parOfs.left}function selY(y){return y-imgOfs.top+parOfs.top}function evX(event){return event.pageX-parOfs.left}function evY(event){return event.pageY-parOfs.top}function getSelection(noScale){var sx=noScale||scaleX,sy=noScale||scaleY;return{x1:round(selection.x1*sx),y1:round(selection.y1*sy),x2:round(selection.x2*sx),y2:round(selection.y2*sy),width:round(selection.x2*sx)-round(selection.x1*sx),height:round(selection.y2*sy)-round(selection.y1*sy)}}function setSelection(x1,y1,x2,y2,noScale){var sx=noScale||scaleX,sy=noScale||scaleY;selection={x1:round(x1/sx||0),y1:round(y1/sy||0),x2:round(x2/sx||0),y2:round(y2/sy||0)};selection.width=selection.x2-selection.x1;selection.height=selection.y2-selection.y1}function adjust(){if(!$img.width())return;imgOfs={left:round($img.offset().left),top:round($img.offset().top)};imgWidth=$img.innerWidth();imgHeight=$img.innerHeight();imgOfs.top+=($img.outerHeight()-imgHeight)>>1;imgOfs.left+=($img.outerWidth()-imgWidth)>>1;minWidth=round(options.minWidth/scaleX)||0;minHeight=round(options.minHeight/scaleY)||0;maxWidth=round(min(options.maxWidth/scaleX||1<<24,imgWidth));maxHeight=round(min(options.maxHeight/scaleY||1<<24,imgHeight));if($().jquery=='1.3.2'&&position=='fixed'&&!docElem['getBoundingClientRect']){imgOfs.top+=max(document.body.scrollTop,docElem.scrollTop);imgOfs.left+=max(document.body.scrollLeft,docElem.scrollLeft)}parOfs=/absolute|relative/.test($parent.css('position'))?{left:round($parent.offset().left)-$parent.scrollLeft(),top:round($parent.offset().top)-$parent.scrollTop()}:position=='fixed'?{left:$(document).scrollLeft(),top:$(document).scrollTop()}:{left:0,top:0};left=viewX(0);top=viewY(0);if(selection.x2>imgWidth||selection.y2>imgHeight)doResize()}function update(resetKeyPress){if(!shown)return;$box.css({left:viewX(selection.x1),top:viewY(selection.y1)}).add($area).width(w=selection.width).height(h=selection.height);$area.add($border).add($handles).css({left:0,top:0});$border.width(max(w-$border.outerWidth()+$border.innerWidth(),0)).height(max(h-$border.outerHeight()+$border.innerHeight(),0));$($outer[0]).css({left:left,top:top,width:selection.x1,height:imgHeight});$($outer[1]).css({left:left+selection.x1,top:top,width:w,height:selection.y1});$($outer[2]).css({left:left+selection.x2,top:top,width:imgWidth-selection.x2,height:imgHeight});$($outer[3]).css({left:left+selection.x1,top:top+selection.y2,width:w,height:imgHeight-selection.y2});w-=$handles.outerWidth();h-=$handles.outerHeight();switch($handles.length){case 8:$($handles[4]).css({left:w>>1});$($handles[5]).css({left:w,top:h>>1});$($handles[6]).css({left:w>>1,top:h});$($handles[7]).css({top:h>>1});case 4:$handles.slice(1,3).css({left:w});$handles.slice(2,4).css({top:h})}if(resetKeyPress!==false){if($.imgAreaSelect.keyPress!=docKeyPress)$(document).unbind($.imgAreaSelect.keyPress,$.imgAreaSelect.onKeyPress);if(options.keys)$(document)[$.imgAreaSelect.keyPress]($.imgAreaSelect.onKeyPress=docKeyPress)}if($.browser.msie&&$border.outerWidth()-$border.innerWidth()==2){$border.css('margin',0);setTimeout(function(){$border.css('margin','auto')},0)}}function doUpdate(resetKeyPress){adjust();update(resetKeyPress);x1=viewX(selection.x1);y1=viewY(selection.y1);x2=viewX(selection.x2);y2=viewY(selection.y2)}function hide($elem,fn){options.fadeSpeed?$elem.fadeOut(options.fadeSpeed,fn):$elem.hide()}function areaMouseMove(event){var x=selX(evX(event))-selection.x1,y=selY(evY(event))-selection.y1;if(!adjusted){adjust();adjusted=true;$box.one('mouseout',function(){adjusted=false})}resize='';if(options.resizable){if(y<=options.resizeMargin)resize='n';else if(y>=selection.height-options.resizeMargin)resize='s';if(x<=options.resizeMargin)resize+='w';else if(x>=selection.width-options.resizeMargin)resize+='e'}$box.css('cursor',resize?resize+'-resize':options.movable?'move':'');if($areaOpera)$areaOpera.toggle()}function docMouseUp(event){$('body').css('cursor','');if(options.autoHide||selection.width*selection.height==0)hide($box.add($outer),function(){$(this).hide()});$(document).unbind('mousemove',selectingMouseMove);$box.mousemove(areaMouseMove);options.onSelectEnd(img,getSelection())}function areaMouseDown(event){if(event.which!=1)return false;adjust();if(resize){$('body').css('cursor',resize+'-resize');x1=viewX(selection[/w/.test(resize)?'x2':'x1']);y1=viewY(selection[/n/.test(resize)?'y2':'y1']);$(document).mousemove(selectingMouseMove).one('mouseup',docMouseUp);$box.unbind('mousemove',areaMouseMove)}else if(options.movable){startX=left+selection.x1-evX(event);startY=top+selection.y1-evY(event);$box.unbind('mousemove',areaMouseMove);$(document).mousemove(movingMouseMove).one('mouseup',function(){options.onSelectEnd(img,getSelection());$(document).unbind('mousemove',movingMouseMove);$box.mousemove(areaMouseMove)})}else $img.mousedown(event);return false}function fixAspectRatio(xFirst){if(aspectRatio)if(xFirst){x2=max(left,min(left+imgWidth,x1+abs(y2-y1)*aspectRatio*(x2>x1||-1)));y2=round(max(top,min(top+imgHeight,y1+abs(x2-x1)/aspectRatio*(y2>y1||-1))));x2=round(x2)}else{y2=max(top,min(top+imgHeight,y1+abs(x2-x1)/aspectRatio*(y2>y1||-1)));x2=round(max(left,min(left+imgWidth,x1+abs(y2-y1)*aspectRatio*(x2>x1||-1))));y2=round(y2)}}function doResize(){x1=min(x1,left+imgWidth);y1=min(y1,top+imgHeight);if(abs(x2-x1)<minWidth){x2=x1-minWidth*(x2<x1||-1);if(x2<left)x1=left+minWidth;else if(x2>left+imgWidth)x1=left+imgWidth-minWidth}if(abs(y2-y1)<minHeight){y2=y1-minHeight*(y2<y1||-1);if(y2<top)y1=top+minHeight;else if(y2>top+imgHeight)y1=top+imgHeight-minHeight}x2=max(left,min(x2,left+imgWidth));y2=max(top,min(y2,top+imgHeight));fixAspectRatio(abs(x2-x1)<abs(y2-y1)*aspectRatio);if(abs(x2-x1)>maxWidth){x2=x1-maxWidth*(x2<x1||-1);fixAspectRatio()}if(abs(y2-y1)>maxHeight){y2=y1-maxHeight*(y2<y1||-1);fixAspectRatio(true)}selection={x1:selX(min(x1,x2)),x2:selX(max(x1,x2)),y1:selY(min(y1,y2)),y2:selY(max(y1,y2)),width:abs(x2-x1),height:abs(y2-y1)};update();options.onSelectChange(img,getSelection())}function selectingMouseMove(event){x2=/w|e|^$/.test(resize)||aspectRatio?evX(event):viewX(selection.x2);y2=/n|s|^$/.test(resize)||aspectRatio?evY(event):viewY(selection.y2);doResize();return false}function doMove(newX1,newY1){x2=(x1=newX1)+selection.width;y2=(y1=newY1)+selection.height;$.extend(selection,{x1:selX(x1),y1:selY(y1),x2:selX(x2),y2:selY(y2)});update();options.onSelectChange(img,getSelection())}function movingMouseMove(event){x1=max(left,min(startX+evX(event),left+imgWidth-selection.width));y1=max(top,min(startY+evY(event),top+imgHeight-selection.height));doMove(x1,y1);event.preventDefault();return false}function startSelection(){$(document).unbind('mousemove',startSelection);adjust();x2=x1;y2=y1;doResize();resize='';if(!$outer.is(':visible'))$box.add($outer).hide().fadeIn(options.fadeSpeed||0);shown=true;$(document).unbind('mouseup',cancelSelection).mousemove(selectingMouseMove).one('mouseup',docMouseUp);$box.unbind('mousemove',areaMouseMove);options.onSelectStart(img,getSelection())}function cancelSelection(){$(document).unbind('mousemove',startSelection).unbind('mouseup',cancelSelection);hide($box.add($outer));setSelection(selX(x1),selY(y1),selX(x1),selY(y1));if(!this instanceof $.imgAreaSelect){options.onSelectChange(img,getSelection());options.onSelectEnd(img,getSelection())}}function imgMouseDown(event){if(event.which!=1||$outer.is(':animated'))return false;adjust();startX=x1=evX(event);startY=y1=evY(event);$(document).mousemove(startSelection).mouseup(cancelSelection);return false}function windowResize(){doUpdate(false)}function imgLoad(){imgLoaded=true;setOptions(options=$.extend({classPrefix:'imgareaselect',movable:true,parent:'body',resizable:true,resizeMargin:10,onInit:function(){},onSelectStart:function(){},onSelectChange:function(){},onSelectEnd:function(){}},options));$box.add($outer).css({visibility:''});if(options.show){shown=true;adjust();update();$box.add($outer).hide().fadeIn(options.fadeSpeed||0)}setTimeout(function(){options.onInit(img,getSelection())},0)}var docKeyPress=function(event){var k=options.keys,d,t,key=event.keyCode;d=!isNaN(k.alt)&&(event.altKey||event.originalEvent.altKey)?k.alt:!isNaN(k.ctrl)&&event.ctrlKey?k.ctrl:!isNaN(k.shift)&&event.shiftKey?k.shift:!isNaN(k.arrows)?k.arrows:10;if(k.arrows=='resize'||(k.shift=='resize'&&event.shiftKey)||(k.ctrl=='resize'&&event.ctrlKey)||(k.alt=='resize'&&(event.altKey||event.originalEvent.altKey))){switch(key){case 37:d=-d;case 39:t=max(x1,x2);x1=min(x1,x2);x2=max(t+d,x1);fixAspectRatio();break;case 38:d=-d;case 40:t=max(y1,y2);y1=min(y1,y2);y2=max(t+d,y1);fixAspectRatio(true);break;default:return}doResize()}else{x1=min(x1,x2);y1=min(y1,y2);switch(key){case 37:doMove(max(x1-d,left),y1);break;case 38:doMove(x1,max(y1-d,top));break;case 39:doMove(x1+min(d,imgWidth-selX(x2)),y1);break;case 40:doMove(x1,y1+min(d,imgHeight-selY(y2)));break;default:return}}return false};function styleOptions($elem,props){for(option in props)if(options[option]!==undefined)$elem.css(props[option],options[option])}function setOptions(newOptions){if(newOptions.parent)($parent=$(newOptions.parent)).append($box.add($outer));$.extend(options,newOptions);adjust();if(newOptions.handles!=null){$handles.remove();$handles=$([]);i=newOptions.handles?newOptions.handles=='corners'?4:8:0;while(i--)$handles=$handles.add(div());$handles.addClass(options.classPrefix+'-handle').css({position:'absolute',fontSize:0,zIndex:zIndex+1||1});if(!parseInt($handles.css('width'))>=0)$handles.width(5).height(5);if(o=options.borderWidth)$handles.css({borderWidth:o,borderStyle:'solid'});styleOptions($handles,{borderColor1:'border-color',borderColor2:'background-color',borderOpacity:'opacity'})}scaleX=options.imageWidth/imgWidth||1;scaleY=options.imageHeight/imgHeight||1;if(newOptions.x1!=null){setSelection(newOptions.x1,newOptions.y1,newOptions.x2,newOptions.y2);newOptions.show=!newOptions.hide}if(newOptions.keys)options.keys=$.extend({shift:1,ctrl:'resize'},newOptions.keys);$outer.addClass(options.classPrefix+'-outer');$area.addClass(options.classPrefix+'-selection');for(i=0;i++<4;)$($border[i-1]).addClass(options.classPrefix+'-border'+i);styleOptions($area,{selectionColor:'background-color',selectionOpacity:'opacity'});styleOptions($border,{borderOpacity:'opacity',borderWidth:'border-width'});styleOptions($outer,{outerColor:'background-color',outerOpacity:'opacity'});if(o=options.borderColor1)$($border[0]).css({borderStyle:'solid',borderColor:o});if(o=options.borderColor2)$($border[1]).css({borderStyle:'dashed',borderColor:o});$box.append($area.add($border).add($areaOpera).add($handles));if($.browser.msie){if(o=$outer.css('filter').match(/opacity=(\d+)/))$outer.css('opacity',o[1]/100);if(o=$border.css('filter').match(/opacity=(\d+)/))$border.css('opacity',o[1]/100)}if(newOptions.hide)hide($box.add($outer));else if(newOptions.show&&imgLoaded){shown=true;$box.add($outer).fadeIn(options.fadeSpeed||0);doUpdate()}aspectRatio=(d=(options.aspectRatio||'').split(/:/))[0]/d[1];$img.add($outer).unbind('mousedown',imgMouseDown);if(options.disable||options.enable===false){$box.unbind('mousemove',areaMouseMove).unbind('mousedown',areaMouseDown);$(window).unbind('resize',windowResize)}else{if(options.enable||options.disable===false){if(options.resizable||options.movable)$box.mousemove(areaMouseMove).mousedown(areaMouseDown);$(window).resize(windowResize)}if(!options.persistent)$img.add($outer).mousedown(imgMouseDown)}options.enable=options.disable=undefined}this.remove=function(){setOptions({disable:true});$box.add($outer).remove()};this.getOptions=function(){return options};this.setOptions=setOptions;this.getSelection=getSelection;this.setSelection=setSelection;this.cancelSelection=cancelSelection;this.update=doUpdate;$p=$img;while($p.length){zIndex=max(zIndex,!isNaN($p.css('z-index'))?$p.css('z-index'):zIndex);if($p.css('position')=='fixed')position='fixed';$p=$p.parent(':not(body)')}zIndex=options.zIndex||zIndex;if($.browser.msie)$img.attr('unselectable','on');$.imgAreaSelect.keyPress=$.browser.msie||$.browser.safari?'keydown':'keypress';if($.browser.opera)$areaOpera=div().css({width:'100%',height:'100%',position:'absolute',zIndex:zIndex+2||2});$box.add($outer).css({visibility:'hidden',position:position,overflow:'hidden',zIndex:zIndex||'0'});$box.css({zIndex:zIndex+2||2});$area.add($border).css({position:'absolute',fontSize:0});img.complete||img.readyState=='complete'||!$img.is('img')?imgLoad():$img.one('load',imgLoad);if($.browser.msie&&$.browser.version>=7)img.src=img.src};$.fn.imgAreaSelect=function(options){options=options||{};this.each(function(){if($(this).data('imgAreaSelect')){if(options.remove){$(this).data('imgAreaSelect').remove();$(this).removeData('imgAreaSelect')}else $(this).data('imgAreaSelect').setOptions(options)}else if(!options.remove){if(options.enable===undefined&&options.disable===undefined)options.enable=true;$(this).data('imgAreaSelect',new $.imgAreaSelect(this,options))}});if(options.instance)return $(this).data('imgAreaSelect');return this}})(jQuery);

(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}
var validator=$.data(this[0],'validator');if(validator){return validator;}
validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});if(validator.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){validator.submitButton=this;});}
this.submit(function(event){if(validator.settings.debug||options.preventDefaultSubmit)
event.preventDefault();function handle(){if(validator.settings.submitHandler){if(validator.submitButton){var hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);}
validator.settings.submitHandler.call(validator,validator.currentForm);if(validator.submitButton){hidden.remove();}
return false;}
return true;}
if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}
if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}
return handle();}else{validator.focusInvalid();return false;}});}
return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=true;var validator=$(this[0].form).validate();this.each(function(){valid&=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)
settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}
var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}
var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}
return data;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(""+a.value);},filled:function(a){return!!$.trim(""+a.value);},unchecked:function(a){return!a.checked;}});$.validator=function(options,form){this.settings=$.extend(true,{},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length==1)
return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.format.apply(this,args);};if(arguments.length>2&&params.constructor!=Array){params=$.makeArray(arguments).slice(1);}
if(params.constructor!=Array){params=[params];}
$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(element)).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)
this.element(element);else if(element.parentNode.name in this.submitted)
this.element(element.parentNode);},highlight:function(element,errorClass,validClass){if(element.type==='radio'){this.findByName(element.name).addClass(errorClass).removeClass(validClass);}else{$(element).addClass(errorClass).removeClass(validClass);}},unhighlight:function(element,errorClass,validClass){if(element.type==='radio'){this.findByName(element.name).removeClass(errorClass).addClass(validClass);}else{$(element).removeClass(errorClass).addClass(validClass);}}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator"),eventType="on"+event.type.replace(/^validate/,"");validator.settings[eventType]&&validator.settings[eventType].call(validator,this[0]);}
$(this.currentForm).validateDelegate(":text, :password, :file, select, textarea","focusin focusout keyup",delegate).validateDelegate(":radio, :checkbox, select, option","click",delegate);if(this.settings.invalidHandler)
$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())
$(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}
return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}
if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);}
this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}
this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}
this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)
$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)
count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin");}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))
return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name).not(this.settings.ignore)[0];}
var rules=$(element).rules();var dependencyMismatch=false;for(var method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,element.value.replace(/\r/g,""),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}
dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}
if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method",e);throw e;}}
if(dependencyMismatch)
return;if(this.objectLength(rules))
this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)
return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta&&meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)
return arguments[i];}
return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method),theregex=/\$?\{(\d+)\}/g;if(typeof message=="function"){message=message.call(this,rule.parameters,element);}else if(theregex.test(message)){message=jQuery.format(message.replace(theregex,'{$1}'),rule.parameters);}
this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)
toToggle=toToggle.add(toToggle.parent(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass,this.settings.validClass);this.showLabel(error.element,error.message);}
if(this.errorList.length){this.toShow=this.toShow.add(this.containers);}
if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}
if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,this.settings.validClass);}}
this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();}
if(!this.labelContainer.append(label).length)
this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}
if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}
this.toShow=this.toShow.add(label);},errorsFor:function(element){var name=this.idOrName(element);return this.errors().filter(function(){return $(this).attr('for')==name;});},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return /radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))
return this.findByName(element.name).filter(':checked').length;}
return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)
this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();this.formSubmitted=false;}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false;}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",{old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(var method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}
if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}
return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}
return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}
if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}
if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}
if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}
if(rules.messages){delete rules.messages;}
return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}
return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message!=undefined?message:$.validator.messages[name];if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))
return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var val=$(element).val();return val&&val.length>0;case'input':if(this.checkable(element))
return this.getLength(value,element)>0;default:return $.trim(value).length>0;}},remote:function(value,element,param){if(this.optional(element))
return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])
this.settings.messages[element.name]={};previous.originalMessage=this.settings.messages[element.name].remote;this.settings.messages[element.name].remote=previous.message;param=typeof param=="string"&&{url:param}||param;if(this.pending[element.name]){return"pending";}
if(previous.old===value){return previous.valid;}
previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){validator.settings.messages[element.name].remote=previous.originalMessage;var valid=response===true;if(valid){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};var message=response||validator.defaultMessage(element,"remote");errors[element.name]=previous.message=$.isFunction(message)?message(value):message;validator.showErrors(errors);}
previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(value),element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))
return"dependency-mismatch";if(/[^0-9-]+/.test(value))
return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(var n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)
nDigit-=9;}
nCheck+=nDigit;bEven=!bEven;}
return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param.replace(/,/g,'|'):"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){var target=$(param).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){$(element).valid();});return value==target.val();}}});$.format=$.validator.format;})(jQuery);;(function($){var pendingRequests={};if($.ajaxPrefilter){$.ajaxPrefilter(function(settings,_,xhr){var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}
pendingRequests[port]=xhr;}});}else{var ajax=$.ajax;$.ajax=function(settings){var mode=("mode"in settings?settings:$.ajaxSettings).mode,port=("port"in settings?settings:$.ajaxSettings).port;if(mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}
return(pendingRequests[port]=ajax.apply(this,arguments));}
return ajax.apply(this,arguments);};}})(jQuery);;(function($){if(!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){this.addEventListener(original,handler,true);},teardown:function(){this.removeEventListener(original,handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};function handler(e){e=$.event.fix(e);e.type=fix;return $.event.handle.call(this,e);}});};$.extend($.fn,{validateDelegate:function(delegate,type,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});}});})(jQuery);

var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function()
{var resolveOptions,assembleOptionsString,parseCookies,constructor,defaultOptions={expiresAt:null,path:'/',domain:null,secure:false};resolveOptions=function(options)
{var returnValue,expireDate;if(typeof options!=='object'||options===null)
{returnValue=defaultOptions;}
else
{returnValue={expiresAt:defaultOptions.expiresAt,path:defaultOptions.path,domain:defaultOptions.domain,secure:defaultOptions.secure};if(typeof options.expiresAt==='object'&&options.expiresAt instanceof Date)
{returnValue.expiresAt=options.expiresAt;}
else if(typeof options.hoursToLive==='number'&&options.hoursToLive!==0)
{expireDate=new Date();expireDate.setTime(expireDate.getTime()+(options.hoursToLive*60*60*1000));returnValue.expiresAt=expireDate;}
if(typeof options.path==='string'&&options.path!=='')
{returnValue.path=options.path;}
if(typeof options.domain==='string'&&options.domain!=='')
{returnValue.domain=options.domain;}
if(options.secure===true)
{returnValue.secure=options.secure;}}
return returnValue;};assembleOptionsString=function(options)
{options=resolveOptions(options);return((typeof options.expiresAt==='object'&&options.expiresAt instanceof Date?'; expires='+options.expiresAt.toGMTString():'')+'; path='+options.path+
(typeof options.domain==='string'?'; domain='+options.domain:'')+
(options.secure===true?'; secure':''));};parseCookies=function()
{var cookies={},i,pair,name,value,separated=document.cookie.split(';'),unparsedValue;for(i=0;i<separated.length;i=i+1)
{pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');try
{value=decodeURIComponent(pair[1]);}
catch(e1)
{value=pair[1];}
if(typeof JSON==='object'&&JSON!==null&&typeof JSON.parse==='function')
{try
{unparsedValue=value;value=JSON.parse(value);}
catch(e2)
{value=unparsedValue;}}
cookies[name]=value;}
return cookies;};constructor=function(){};constructor.prototype.get=function(cookieName)
{var returnValue,item,cookies=parseCookies();if(typeof cookieName==='string')
{returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}
else if(typeof cookieName==='object'&&cookieName!==null)
{returnValue={};for(item in cookieName)
{if(typeof cookies[cookieName[item]]!=='undefined')
{returnValue[cookieName[item]]=cookies[cookieName[item]];}
else
{returnValue[cookieName[item]]=null;}}}
else
{returnValue=cookies;}
return returnValue;};constructor.prototype.filter=function(cookieNameRegExp)
{var cookieName,returnValue={},cookies=parseCookies();if(typeof cookieNameRegExp==='string')
{cookieNameRegExp=new RegExp(cookieNameRegExp);}
for(cookieName in cookies)
{if(cookieName.match(cookieNameRegExp))
{returnValue[cookieName]=cookies[cookieName];}}
return returnValue;};constructor.prototype.set=function(cookieName,value,options)
{if(typeof options!=='object'||options===null)
{options={};}
if(typeof value==='undefined'||value===null)
{value='';options.hoursToLive=-8760;}
else if(typeof value!=='string')
{if(typeof JSON==='object'&&JSON!==null&&typeof JSON.stringify==='function')
{value=JSON.stringify(value);}
else
{throw new Error('cookies.set() received non-string value and could not serialize.');}}
var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options)
{var allCookies={},name;if(typeof options!=='object'||options===null)
{options={};}
if(typeof cookieName==='boolean'&&cookieName===true)
{allCookies=this.get();}
else if(typeof cookieName==='string')
{allCookies[cookieName]=true;}
for(name in allCookies)
{if(typeof name==='string'&&name!=='')
{this.set(name,null,options);}}};constructor.prototype.test=function()
{var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue)
{this.del(testName);returnValue=true;}
return returnValue;};constructor.prototype.setOptions=function(options)
{if(typeof options!=='object')
{options=null;}
defaultOptions=resolveOptions(options);};return new constructor();})();(function()
{if(window.jQuery)
{(function($)
{$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options)
{return this.each(function()
{var i,nameAttrs=['name','id'],name,$this=$(this),value;for(i in nameAttrs)
{if(!isNaN(i))
{name=$this.attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{if($this.is(':checkbox, :radio'))
{if($this.attr('checked'))
{value=$this.val();}}
else if($this.is(':input'))
{value=$this.val();}
else
{value=$this.html();}
if(typeof value!=='string'||value==='')
{value=null;}
$.cookies.set(name,value,options);break;}}}});},cookieFill:function()
{return this.each(function()
{var n,getN,nameAttrs=['name','id'],name,$this=$(this),value;getN=function()
{n=nameAttrs.pop();return!!n;};while(getN())
{name=$this.attr(n);if(typeof name==='string'&&name!=='')
{value=$.cookies.get(name);if(value!==null)
{if($this.is(':checkbox, :radio'))
{if($this.val()===value)
{$this.attr('checked','checked');}
else
{$this.removeAttr('checked');}}
else if($this.is(':input'))
{$this.val(value);}
else
{$this.html(value);}}
break;}}});},cookieBind:function(options)
{return this.each(function()
{var $this=$(this);$this.cookieFill().change(function()
{$this.cookify(options);});});}};$.each(extensions,function(i)
{$.fn[i]=this;});})(window.jQuery);}})();

(function($){var functions={};var view=function(path,obj)
{if(!functions[path])
{$.ajax({url:path,method:'GET',async:false,success:function(response){functions[path]=parseJhtml(response);}});}
return obj?functions[path](obj):functions[path];}
view.loadViewFunction=function(path,fn)
{functions[path]=fn;}
var parseJhtml=function(str)
{var parsed_str="var p=[],print=function(){p.push.apply(p,arguments);};"+"with(obj){p.push('"+
str.replace(/[\r\t\n]/g," ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');";return new Function("obj",parsed_str);}
MLD.View=view;})(jQuery);

Date.parseMysqlTimestamp=function(timestamp)
{var date=new Date();var parts=String(timestamp).split(/[- :]/);return Date.UTC(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5],0);};

(function(){var CrossDomain={cacheBust:1,postMessage:function(message,target,target_url)
{target=target||parent;if(window.addEventListener&&!window.attachEvent&&window.postMessage)
{var domain=target_url?target_url.replace(/([^:]+:\/\/[^\/]+).*/,'$1'):'*';target['postMessage'](message,domain);}
else
{if(!target_url)
{target_url=target.location.href;}
target.location=target_url.replace(/#.*$/,'')+'#'+(+new Date)+(Math.floor(Math.random()*10001))+(this.cacheBust++)+'&'+message;}},receiveMessage:function(callback,source_origin)
{var me=this;if(window.addEventListener&&!window.attachEvent&&window.postMessage)
{var attached_callback=function(e)
{if((typeof source_origin==='string'&&e.origin!==source_origin)||(Object.prototype.toString.call(source_origin)==="[object Function]"&&source_origin(e.origin)===!1))
{return!1;}
var destroy=callback(e);if(destroy==1)
{me.removeListener(attached_callback);}};me.addListener(attached_callback);}
else
{var intervalId;var lastHash;if(callback)
{intervalId=setInterval(function()
{var hash=document.location.hash;var re=/^#?\d+&/;if(hash!==lastHash&&re.test(hash))
{lastHash=hash;var destroy=callback({data:hash.replace(re,'')});if(destroy==1)
{clearInterval(intervalId);}}},100);}}},addListener:function(callback)
{if(window.addEventListener)
{window.addEventListener('message',callback,!1);}
else
{window.attachEvent('onmessage',callback);}},removeListener:function(callback)
{if(window.addEventListener)
{window.removeEventListener('message',callback,!1);}
else
{window.detachEvent('onmessage',callback);}}};MLD.CrossDomain=CrossDomain;})();

(function(XD,$){var host;var MLauth={options:null,popup:null,listeningForLogin:false,loginListeners:[],init:function(options)
{host=MLD.mylifeApiUrl;var defaultOptions={clientId:'',stateName:'',redirectUri:'',width:350,height:600};this.options=$.extend({},defaultOptions,options);},logout:function(url)
{var newLocation=typeof(url)!=='undefined'?url:location.protocol+'//'+location.host+'/';newLocation=host+'/api/public/logout.view?redirect_uri='+encodeURIComponent(newLocation);window.location.assign(newLocation);},forceLogin:function(email,password,redirectTo)
{var redirect=this.getAuthUrl('iframe',redirectTo);var url=host+'/api/public/logon.view?email='+encodeURIComponent(email)
+'&password='+encodeURIComponent(password)
+'&client_id=mylifedeals'
+'&redirect_uri='+encodeURIComponent(redirect);window.location=url;},remoteLogin:function(siteUrl)
{siteUrl+='/api/remote-sso?clientLocation='+window.location.href;var id='MLauth-iframe-hidden';$('body').append('<div id="'+id+'" style="display:none"> </div>');$container=$('#'+id);$container.append($('<iframe />',{src:siteUrl}));},checkLogin:function()
{this.displayLogin('iframe',false);},displayLogin:function(context,$container)
{context=context||'popup';var url=this.getAuthUrl(context);if(context=='iframe')
{if(!$container)
{var id='MLauth-iframe-hidden';$('body').append('<div id="'+id+'" style="display:none"> </div>');$container=$('#'+id);}
$container.append($('<iframe />',{src:url,width:this.options.width,height:this.options.height,align:'middle',scrolling:'no'}));}
else
{this.popup=window.open(url,'MLauth','width='+this.options.width+',height='+this.options.height+',menubar=no,toolbar=no');var popup=this.popup;this.addLoginListener(function(){popup.close();});}},displayRegistration:function()
{var url=this.getRegistrationUrl();this.popup=window.open(url,'MLauth','width='+this.options.width+',height='+this.options.height+',menubar=no,toolbar=no');var popup=this.popup;this.addLoginListener(function(){popup.close();});},openRegistration:function()
{var url=this.getRegistrationUrl();window.location.href=url;},getRegistrationUrl:function()
{var redirectUrl=encodeURIComponent(this.getAuthUrl('popup'));var url=host+'/api/public/reg.view?client_id=mylifedeals&redirect_uri='+redirectUrl;return url;},addLoginListener:function(onLogin)
{var self=this;this.loginListeners.push(onLogin);if(!this.listeningForLogin)
{XD.receiveMessage(function(evt){if(evt.data=='MLauth_success')
{$.each(self.loginListeners,function(i,listener){listener();});}});this.listeningForLogin=true;}},getAuthUrl:function(context,redirectRedirect)
{var redirect=this.options.redirectUri;redirect+='?clientLocation='+encodeURIComponent(window.location.href);redirect+='&context='+context;if(redirectRedirect!=null)
{redirect+='&redirectTo='+encodeURIComponent(redirectRedirect);}
if(window.location.protocol=='https:')
{redirect=redirect.replace('http:','https:');redirect+='&ssl=1';}
var url=host+'/api/oauth/user/authorize?response_type=code'
+'&client_id='+this.options.clientId
+'&state='+this.getState()
+'&redirect_uri='+encodeURIComponent(redirect);return url;},getState:function()
{var name=this.options.stateName;var matches=document.cookie.match(new RegExp(name+'=[a-z0-9]*','g'));var match=(matches&&matches.length>0)?matches[matches.length-1]:null;if(match)
{return match.substr(match.indexOf('=')+1);}
{window.location.reload();}}};window.MLauth=MLauth;})(MLD.CrossDomain,jQuery);

(function(CrossDomain,$){var Model=function(data)
{if(typeof(data)=='object')
{this.data=data;}
else
{this.data={};}}
Model.apiUrl='';Model.getDealUrl=function(uri)
{var url=Model.apiUrl?Model.apiUrl:'';if(uri!=null)
{url+=uri;}
return url;}
Model.extend=function(child)
{child.prototype=$.extend({},Model.prototype,child.prototype);child.prototype.constructor=child;child.load=function(id,success,error)
{Model.load.call(child,id,success,error);}
child.getListFromRestResponse=function(response)
{Model.getListFromRestResponse.call(response);}}
Model.ajax=function(params)
{params.originalSuccess=params.success;params.success=function(response)
{if(!response||!response.success)
{params.error(response);return;}
params.originalSuccess(response);};params.url='/api'+params.url;if(Model.apiUrl&&params.type=='GET')
{params.url=Model.apiUrl+params.url;params.dataType='jsonp';params.jsonp='jsonp_callback';params.timeout=10000;}
else if(Model.apiUrl&&params.type!='GET')
{Model.crossDomainRequest(params);return;}
else
{params.dataType='json';}
return $.ajax(params);}
Model.crossDomainRequest=function(params)
{var requestParams={};requestParams.id='MLD-crossdomain-iframe-hidden-'+Date.UTC()+'-'+Math.floor(Math.random()*10001);requestParams.type=params.type;requestParams.url=params.url;requestParams.data=params.data;var readyMessage=requestParams.id+'-ready';var targetUrl=Model.apiUrl+'/api/cross-domain/index.html?clientLocation='+encodeURIComponent(window.location.href)+'#'+requestParams.id;var $iframe=$('<iframe />',{id:requestParams.id,src:targetUrl,style:'display:none'});$('body').append($iframe);var jsonReceiver=function(e){try{var responseObj=JSON.parse(e.data);}catch(error){return 0;}
if(requestParams.id!=responseObj.id)return 0;if(responseObj.type=='success')
{params.success(responseObj.data,responseObj.textStatus,responseObj.jqXHR);}
else
{params.error(responseObj.jqXHR,responseObj.textStatus,responseObj.errorThrown);}
return 1;};CrossDomain.receiveMessage(function(e){if(e.data==readyMessage)
{CrossDomain.receiveMessage(jsonReceiver);var requestString=JSON.stringify(requestParams);CrossDomain.postMessage(requestString,$iframe.get(0).contentWindow,targetUrl);return 1;}
return 0;});}
Model.load=function(id,success,error)
{var self=this;if(!id)
{error();return;}
Model.ajax({'url':this.prototype.getBaseUri()+id,'type':'GET','success':function(response){success(new self(response[self.prototype.getRestEntityName()]));},'error':function(response){error(response);}});}
Model.getListFromRestResponse=function(response)
{var jsonArray=response[self.prototype.getRestEntityName()+'_list'];var entityArray=[];$.each(jsonArray,function(i,obj){entityArray.push(new self(obj));});return entityArray;}
Model.prototype={data:null,getId:function()
{return this.data.id;},save:function(success,error)
{var self=this;var url=this.getBaseUri();var restEntityName=this.getRestEntityName();var data;if(!this.getId())
{var originalSuccess=success;success=function(model){self.data.id=model.getId();originalSuccess(model);}
data=this.getCreateParams();}
else
{url+=this.getId();data=this.getUpdateParams();}
Model.ajax({'url':url,'type':'POST','data':data,'success':function(response){success(self.getNewSelfFromResponse(response));},'error':function(response){error(response);}});},getCreateParams:function()
{return this.data;},getUpdateParams:function()
{return this.data;},getBaseUri:function()
{return'/'+this.getRestEntityName().replace(/_/g,'-')+'/';},getNewSelfFromResponse:function(response)
{var entityName=this.getRestEntityName();var model=new this.constructor(response[this.getRestEntityName()]);return model;}}
MLD.Model=Model;})(MLD.CrossDomain,jQuery);

(function(Model,$){var Search=function(data)
{Model.call(this,data);}
Search.extend=function(child)
{child.prototype=$.extend({},Search.prototype,child.prototype);child.prototype.constructor=child;}
Search.prototype={data:{},getRows:function()
{return this.data.rows;},getPage:function()
{return parseInt(this.data.page);},getLastPage:function()
{return Math.ceil(this.getTotalCount()/this.getRowsPerPage());},getTotalCount:function()
{return parseInt(this.data.total_count);},getRowDisplayStart:function()
{return parseInt(this.data.row_display_start);},getRowDisplayEnd:function()
{return parseInt(this.data.row_display_end);},getRowsPerPage:function()
{return parseInt(this.data.rows_per_page);}}
Model.extend(Search);Model.Search=Search;})(MLD.Model,jQuery);

(function(Model,$){var SearchOffer=function(data)
{Model.Search.call(this,data);};SearchOffer.loadOfferedByAreaId=function(options,success,error)
{var self=this;var defaults={areaId:null,page:1,rowsPerPage:1};options=$.extend({},defaults,options);Model.ajax({url:'/offer/search-offered-by-area/?area_id='+options.areaId+'&page='+options.page+'&rows_per_page='+options.rowsPerPage,type:'GET',success:function(response)
{success(new self(response.offer_search));},error:function(response)
{error(response);}});}
SearchOffer.prototype={getFirstOffer:function()
{var offer;if(this.getRows().length){offer=new Model.Offer(this.getRows()[0].entity);}
return offer;}}
Model.Search.extend(SearchOffer);Model.SearchOffer=SearchOffer;})(MLD.Model,jQuery);

(function(Model,$){var SearchAreaOfferVoting=function(data)
{Model.Search.call(this,data);};SearchAreaOfferVoting.loadOffersInVotingByAreaId=function(options,success,error)
{var self=this;var defaults={areaId:null,personId:null,page:1,rowsPerPage:25,reservedSlot:0};options=$.extend({},defaults,options);Model.ajax({url:'/offer/search-area-offer-voting/',data:{area_id:options.areaId,person_id:options.personId,page:options.page,rows_per_page:options.rowsPerPage,reserved_slot:options.reservedSlot},type:'GET',success:function(response)
{success(new self(response.area_offer_voting_search));},error:function(response)
{error(response);}});}
SearchAreaOfferVoting.prototype={getRows:function()
{var rows=[];$.each(this.data.rows,function(i,rowData){rows.push(new Model.SearchAreaOfferVoting.Row(rowData));});return rows;}}
Model.Search.extend(SearchAreaOfferVoting);Model.SearchAreaOfferVoting=SearchAreaOfferVoting;})(MLD.Model,jQuery);

(function(Model,$){var Row=function(data)
{Model.Search.call(this,data);};Row.loadOffersInVotingByAreaId=function(options,success,error)
{var self=this;var defaults={areaId:null,personId:null,page:1,rowsPerPage:1};options=$.extend({},defaults,options);Model.ajax({url:'/offer/search-area-offer-voting/',data:{area_id:options.areaId,person_id:options.personId,page:options.page,rows_per_page:options.rowsPerPage},type:'GET',success:function(response)
{success(new self(response.offer_search));},error:function(response)
{error(response);}});}
Row.prototype={getOffer:function()
{var offer=new Model.Offer(this.data.offer);return offer;},hasVoted:function()
{return this.data.voted==1;}}
Model.Search.extend(Row);Model.SearchAreaOfferVoting.Row=Row;})(MLD.Model,jQuery);

(function(Model,$){var State=function(data)
{Model.call(this,data);}
State.loadAll=function(success,error)
{$.ajax({'url':'/api/state/','method':'GET','dataType':'json','success':function(response){if(!response||!response.success)
{this.error(response);return;}
var stateArray=[];$.each(response.state_list,function(i,data){stateArray.push(new State(data));});success(stateArray);},'error':function(response){error(response);}});}
State.prototype={data:{'id':null},getId:function()
{return this.data.id;},getAbbreviation:function()
{return this.data.abbreviation;},getName:function()
{return this.data.name;},getRestEntityName:function()
{return'state';}}
Model.extend(State);Model.State=State;})(MLD.Model,jQuery);

(function(Model,$){var Category=function(data)
{Model.call(this,data);}
Category.loadAll=function(success,error)
{$.ajax({'url':'/api/category/','method':'GET','dataType':'json','success':function(response){if(!response||!response.success)
{this.error(response);return;}
var categoryArray=[];$.each(response.category_list,function(i,data){categoryArray.push(new Category(data));});success(categoryArray);},'error':function(response){error(response);}});}
Category.prototype={data:{'id':null},getId:function()
{return this.data.id;},getCode:function()
{return this.data.code;},getName:function()
{return this.data.name;},getRestEntityName:function()
{return'category';}}
Model.extend(Category);Model.Category=Category;})(MLD.Model,jQuery);

(function(Model,$){var StreetAddress=function(data)
{Model.call(this,data);}
StreetAddress.prototype={getStreet1:function()
{return this.data.street1;},setStreet1:function(value)
{this.data.street1=value;return this;},getStreet2:function()
{return this.data.street2;},setStreet2:function(value)
{this.data.street2=value;return this;},getCity:function()
{return this.data.city;},setCity:function(value)
{this.data.city=value;return this;},getState:function()
{return this.data.state;},setState:function(value)
{this.data.state=value;return this;},getZipCode:function()
{return this.data.zip_code;},setZipCode:function(value)
{this.data.zip_code=value;return this;},getLatitude:function()
{return this.data.latitude;},setLatitude:function(value)
{this.data.latitude=value;return this;},getLongitude:function()
{return this.data.longitude;},setLongitude:function(value)
{this.data.longitude=value;return this;},getElevation:function()
{return this.data.elevation;},setElevation:function(value)
{this.data.elevation=value;return this;},getRestEntityName:function()
{return'street_address';}}
Model.extend(StreetAddress);Model.StreetAddress=StreetAddress;})(MLD.Model,jQuery);

(function(Model,$){var OrganizationLocation=function(data)
{this.streetAddress=new Model.StreetAddress(data.street_address);Model.call(this,data);}
OrganizationLocation.prototype={streetAddress:null,getStreetAddress:function()
{return this.streetAddress;},setStreetAddress:function(value)
{this.streetAddress=value;return this;},getName:function()
{return this.data.name;},setName:function(value)
{this.data.name=value;return this;},getPhoneNumber:function()
{return this.data.phone_number;},setPhoneNumber:function(value)
{this.data.phone_number=value;return this;},getUpdateParams:function()
{var params=$.extend({},this.data);params['street_address']=this.getStreetAddress().getUpdateParams();return params;},getRestEntityName:function()
{return'organization_location';}}
Model.extend(OrganizationLocation);Model.OrganizationLocation=OrganizationLocation;})(MLD.Model,jQuery);

(function(Model,$){var Area=function(data)
{Model.call(this,data);};Area.getOneByZipCode=function(zipCode,success,error)
{var self=this;Model.ajax({'url':'/area/zipcode/'+zipCode,'type':'GET','success':function(response){success(new Area(response['area']));},'error':function(response){error(response);}});};Area.subscribe=function(email,areaId,success,error)
{var self=this;var data={email:email,id:areaId};Model.ajax({'url':'/area/subscribe/','type':'POST',data:data,'success':function(response){success(response);},'error':function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});};Area.subscribeByCode=function(email,areaCode,success,error)
{var self=this;var data={email:email,code:areaCode};Model.ajax({'url':'/area/subscribe-code/','type':'POST',data:data,'success':function(response){success(response);},'error':function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});};Area.unsubscribe=function(email,areaId,success,error)
{var self=this;return Model.ajax({'url':'/area/subscribe?id='+areaId+'&email='+email,'type':'DELETE','success':function(response){success(response);},'error':function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});};Area.closest=function(areaId,amount,success,error)
{var self=this;var url='/area/closest/id/'+areaId+'/limit/'+amount;Model.ajax({'url':url,'type':'GET','success':function(response){var jsonArray=response['area_list'];var entityArray=[];$.each(jsonArray,function(i,obj){entityArray.push(new self(obj));});success(entityArray);},'error':function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});};Area.alerts=function(email,success,error)
{var self=this;var url='/email-address/alert-area/'+email;Model.ajax({'url':url,'type':'GET','success':function(response){var jsonArray=response['area_list'];var entityArray=[];$.each(jsonArray,function(i,obj){entityArray.push(new self(obj));});success(entityArray);},'error':function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});};Area.suggestions=function(email,success,error)
{var self=this;var url='/area/suggest/';var data={email:email};Model.ajax({'url':url,'type':'GET',data:data,'success':function(response){var jsonArray=response['area_list'];var entityArray=[];$.each(jsonArray,function(i,obj){entityArray.push(new self(obj));});success(entityArray);},'error':function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});};Area.prototype={getName:function()
{return this.data.name;},getStateCode:function()
{return this.data.state_id;},getUrl:function()
{return this.data.url;},getRestEntityName:function()
{return'area';}};Model.extend(Area);Model.Area=Area;})(MLD.Model,jQuery);

(function(Model,$){var Offer=function(data)
{var self=this;this.deal=new Model.Deal(data.deal);this.area=new Model.Area(data.area);self.organizationLocationList=[];$.each(data.organization_location_list,function(i,locationData)
{self.organizationLocationList.push(new Model.OrganizationLocation(locationData));});if(typeof(data.marketing_info)!='undefined'&&data.marketing_info)
{try{this.marketingInfo=new Model.OfferMarketingInfo(data.marketing_info);}catch(error){console.log(error);}}
Model.call(this,data);};Offer.dashSearch=function(options,success,error)
{var defaults={page:1,rowsPerPage:5};options=$.extend({},defaults,options);Model.ajax({url:'/offer/dashboard-search/',data:{page:options.page,rows_per_page:options.rowsPerPage},type:'GET',success:function(response)
{success(new Model.Search(response.offer_search));},error:function(response){error(response);}});};Offer.areaOfferVoteSearch=function(options,success,error)
{var defaults={page:1,rowsPerPage:5};options=$.extend({},defaults,options);Model.ajax({url:'/offer/dashboard-search/',data:{page:options.page,rows_per_page:options.rowsPerPage,areaId:options.areaId,personId:options.personId},type:'GET',success:function(response)
{success(new Model.Search(response.area_offer_voting_search));},error:function(response){error(response);}});};Offer.getAllSuggestedByAreaIdAndCategory=function(options,success,error)
{var self=this;var defaults={areaId:0,category:'all'};options=$.extend({},defaults,options);if(!options.areaId)
{return;}
Model.ajax({url:'/offer/area/'+areaId,data:{suggested:1,category:options.category},type:'GET',success:function(response)
{success(self.getListFromRestResponse(response));},error:function(response){error(response);}});};Offer.getAllByArea=function(options,success,error)
{var self=this;var defaults={areaId:0,zipCode:0,page:1,rowsPerPage:5,reserveSlot:0};options=$.extend({},defaults,options);if(!options.areaId&&!options.zipCode)
{return;}
var data={page:options.page,rows_per_page:options.rowsPerPage};if(!options.areaId&&options.zipCode>0)
{data.zip_code=options.zipCode;}
else
{data.area_id=options.areaId;}
data.reserve_slot=options.reserveSlot;Model.ajax({url:'/offer/search-offered-by-area/',data:data,type:'GET',success:function(response)
{success(new Model.SearchOffer(response.offer_search));},error:function(response){error(response);}});};Offer.prototype={deal:null,area:null,revenue:null,marketingInfo:null,getArea:function()
{return this.area;},isTipped:function()
{return this.data.is_tipped==1;},getStatus:function()
{return this.data.status;},getStart:function()
{return this.data.start;},getEnd:function()
{return this.data.end;},getVoucherExpiration:function()
{return this.data.voucher_expiration;},getVoucherInception:function()
{return this.data.voucher_inception;},getPurchaseCount:function()
{return this.data.purchased?this.data.purchased:0;},getVoteCount:function()
{return this.data.votes?this.data.votes:0;},getTitle:function()
{return this.deal.getTitle();},getDescription:function()
{return this.deal.getDescription();},getHighlights:function()
{return this.deal.getHighlights();},getFinePrint:function()
{return this.data.fine_print;},getCost:function()
{return this.deal.getCost();},getValue:function()
{return this.deal.getValue();},isAllowedToGift:function()
{return this.deal.isAllowedToGift();},getQuantityLimit:function()
{return this.deal.getQuantityLimit();},getImageUrl:function()
{return this.deal.getImageUrl();},getImageThumbnailUrl:function()
{return this.deal.getImageThumbnailUrl();},getMinimumThreshold:function()
{return this.deal.getMinimumThreshold();},getMaximumThreshold:function()
{return this.deal.getMaximumThreshold();},getRedemptionPeriod:function()
{return this.deal.getRedemptionPeriod();},getRedemptionPeriodInMonths:function()
{var months;switch(this.getRedemptionPeriod()){case'2_months':months=2;break;case'6_months':months=6;break;case'12_months':months=12;break;case'18_months':months=18;break;default:months=6;}
return months;},getShareLinkFacebook:function()
{return this.data.share_link_facebook;},getShareLinkTwitter:function()
{return this.data.share_link_twitter;},getShareLinkEmail:function()
{return this.data.share_link_email;},getPurchaseUrl:function()
{return Model.getDealUrl('/deal/'+this.getUrlFragment()+'/purchase');},getUrlFragment:function()
{return this.data.url_fragment;},getSavings:function()
{return this.getValue()-this.getCost();},getDiscount:function()
{return Number(100.0*this.getSavings()/this.getValue()).toFixed(0);},getPublisher:function()
{return this.deal.getPublisher();},getForeignDealId:function()
{return this.deal.getForeignDealId();},getForeignPromoId:function()
{return this.deal.getForeignPromoId();},setStart:function(value)
{this.data.start=value;return this;},setEnd:function(value)
{this.data.end=value;return this;},setVoucherExpiration:function(dateObject)
{this.data.voucher_expiration=dateObject.getTime();return this;},setVoucherInception:function(dateObject)
{this.data.voucher_inception=dateObject.getTime();return this;},schedule:function(startTime,endTime,expirationTime,marketingOptions,promoOptions,success,error)
{var self=this;var id=this.getId();if(startTime instanceof Date)
{startTime=startTime.getFullYear()
+'-'+(startTime.getMonth()+1)
+'-'+startTime.getDate()
+' '+startTime.getHours()
+':'+startTime.getMinutes()
+':00';}
else
{throw('startTime must be an instance of Date');}
if(endTime instanceof Date)
{endTime=endTime.getFullYear()
+'-'+(endTime.getMonth()+1)
+'-'+endTime.getDate()
+' '+endTime.getHours()
+':'+endTime.getMinutes()
+':00';}
else
{throw('endTime must be an instance of Date');}
if(expirationTime instanceof Date)
{expirationTime=expirationTime.getFullYear()
+'-'+(expirationTime.getMonth()+1)
+'-'+expirationTime.getDate()
+' '+expirationTime.getHours()
+':'+expirationTime.getMinutes()
+':00';}
else
{expirationTime='';}
var data={offer_id:id,offer_action:'schedule',start_time:startTime,end_time:endTime,expiration_time:expirationTime,'offer_marketing[email_radius]':marketingOptions.email_radius,'offer_marketing[email_subject_a]':marketingOptions.email_subject_a,'offer_marketing[email_subject_b]':marketingOptions.email_subject_b,quantity:promoOptions.quantity,bid:promoOptions.bid,site_id:promoOptions.site_id};$.each(marketingOptions.dma_list,function(i,dma){data['offer_marketing[dma_list]['+i+']']=dma;});$.each(marketingOptions.cbsa_list,function(i,cbsa){data['offer_marketing[cbsa_list]['+i+']']=cbsa;});$.each(marketingOptions.pmsa_list,function(i,pmsa){data['offer_marketing[pmsa_list]['+i+']']=pmsa;});$.each(marketingOptions.area_list,function(i,dma){data['offer_marketing[area_list]['+i+']']=dma;});Model.ajax({url:'/offer/action/',type:'POST',data:data,success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response,textStatus,errorThrown){error(response,textStatus,errorThrown);}});},end:function(success,error)
{var self=this;var id=this.getId();Model.ajax({url:'/offer/action/',type:'POST',data:{offer_id:id,offer_action:'end'},success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response){error(response);}});},close:function(success,error)
{var self=this;var id=this.getId();Model.ajax({url:'/offer/action/',type:'POST',data:{offer_id:id,offer_action:'close'},success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response){error(response);}});},getOrganizationLocations:function(success,error)
{var self=this;if(!this.organizationLocationList)
{var id=this.getId();Model.ajax({url:'/offer/organization-location-list/'+id,type:'GET',success:function(response)
{self.organizationLocationList=[];$.each(response.organization_location_list,function(i,locationData)
{self.organizationLocationList.push(new Model.OrganizationLocation(locationData));});success(self.organizationLocationList);},error:function(response){error(response);}});}
else
{success(this.organizationLocationList);}},addOrganizationLocation:function(orgLocation,success,error)
{var data=orgLocation.getCreateParams();data=$.extend({offer_id:this.getId()},data);Model.ajax({url:'/offer/organization-location/',type:'POST',success:function(response)
{success(new Model.OrganizationLocation(response.organization_location));},error:function(response){error(response);}});},vote:function(personId,success,error)
{if(personId instanceof Model.Person)
{personId=personId.getId();}
var self=this;Model.ajax({url:'/vote/',type:'POST',data:{offer_id:self.getId(),person_id:personId},success:function(response)
{success();},error:function(response)
{error(response);}});},getRevenue:function(success,error)
{if(this.revenue!==null){success(this.revenue);}
var self=this;var id=this.getId();Model.ajax({url:'/offer/revenue/',type:'GET',data:{id:id},success:function(response){self.revenue=response.revenue;success(response.revenue);},error:function(response){error(response);}});},getMarketingInfo:function()
{if(!this.marketingInfo){return null;}
return this.marketingInfo;},getRestEntityName:function()
{return'offer';},getTipprSites:function(success,error)
{Model.ajax({url:'/deal/tippr-sites/',type:'GET',success:function(response){success(response);},error:function(response){error(response);}});},getTipprPromo:function(promoId,success,error)
{Model.ajax({url:'/deal/tippr-promo/',type:'GET',data:{promo_id:promoId},success:function(response){success(response);},error:function(response){error(response);}});},hasAdditionalInfo:function()
{var hasInfo=false;if(this.getPublisher().name=="Tippr"){hasInfo=true;}
return hasInfo;}};Model.extend(Offer);Model.Offer=Offer;})(MLD.Model,jQuery);

(function(Model,$){var OfferMarketingInfo=function(data)
{Model.call(this,data);}
OfferMarketingInfo.prototype={data:{'id':null},getEmailRadius:function()
{return this.data.email_radius;},getEmailSubjectA:function()
{return this.data.email_subject_a;},getEmailSubjectB:function()
{return this.data.email_subject_b;},getDmaList:function()
{return this.data.dma_list;},getAreaNames:function()
{var areaNames=[];$.each(this.data.area_list,function(i,areaData)
{areaNames.push(areaData.name);});return areaNames;},getRestEntityName:function()
{return'marketing_info';}}
Model.extend(OfferMarketingInfo);Model.OfferMarketingInfo=OfferMarketingInfo;})(MLD.Model,jQuery);

(function(Model,$){var DealImage=function(data)
{this.data=data}
DealImage.prototype={data:null,getId:function()
{return this.data.id;},getOriginalId:function()
{return this.data.original_file.id;},getImageId:function()
{return this.data.image_file.id;},getThumbnailId:function()
{return this.data.image_thumbnail_file.id;},getOriginalUrl:function()
{return this.data.original_file.url;},getImageUrl:function()
{return this.data.image_file.url;},getThumbnailUrl:function()
{return this.data.image_thumbnail_file.url;},getUpdateParams:function()
{var self=this;var params={image_original_file_id:self.getOriginalId(),image_file_id:self.getImageId(),image_thumbnail_file_id:self.getThumbnailId()};return params;}}
Model.DealImage=DealImage;})(MLD.Model,jQuery);

(function(Model,$){var Deal=function(data)
{if(typeof(data.offer_list)!='undefined'&&data.offer_list)
{this.setOfferList(data.offer_list);}
data.offer_list=null;Model.call(this,data);};Deal.search=function(options,success,error)
{var defaults={page:1,rows_per_page:5};options=$.extend({},defaults,options);Model.ajax({url:'/deal/search/',data:options,type:'GET',success:function(response)
{success(new Model.Search(response.deal_search));},error:function(response){error(response);}});};Deal.dashSearch=function(options,success,error)
{var defaults={};options=$.extend({},defaults,options);Model.ajax({url:'/deal/dashboard-search/',data:{},type:'GET',success:function(response)
{success(new Model.Search(response.deal_search));},error:function(response){error(response);}});};Deal.prototype={data:{'id':null,'allowed_to_gift':1},dealImage:null,offerList:null,getCategory:function()
{return this.data.category;},getSubcategory:function()
{return this.data.subcategory;},setCategory:function(value)
{this.data.category=value;return this;},setSubcategory:function(value)
{this.data.subcategory=value;return this;},getStatus:function()
{return this.data.status;},getOrganization:function()
{return this.data.organization;},getPublisher:function()
{return this.data.publisher;},getTitle:function()
{return this.data.title;},getDescription:function()
{return this.data.description;},getHighlights:function()
{return this.data.highlights;},getFinePrint:function()
{return this.data.fine_print;},getCost:function()
{return this.data.cost;},getValue:function()
{return this.data.value;},isAllowedToGift:function()
{return this.data.allowed_to_gift==1;},getQuantityLimit:function()
{return this.data.quantity_limit;},getImageOriginalUrl:function()
{return this.data.image_original_url;},getImageUrl:function()
{return this.data.image_url;},getImageThumbnailUrl:function()
{return this.data.image_thumbnail_url;},getMinimumThreshold:function()
{return this.data.minimum_threshold;},getMaximumThreshold:function()
{return this.data.maximum_threshold;},getRedemptionPeriod:function()
{return this.data.redemption_period;},getRejectionMsg:function()
{return this.data.reject_msg;},getForeignDealId:function()
{return this.data.foreign_deal_id;},getForeignPromoId:function()
{return this.data.foreign_promotion_id;},getAskPrice:function()
{return this.data.ask_price;},setTitle:function(value)
{this.data.title=value;return this;},setDescription:function(value)
{this.data.description=value;return this;},setHighlights:function(value)
{this.data.highlights=value;return this;},setFinePrint:function(value)
{this.data.fine_print=value;return this;},setValue:function(value)
{this.data.value=value;return this;},setCost:function(value)
{this.data.cost=value;return this;},setMinimumThreshold:function(value)
{this.data.minimum_threshold=value;return this;},setMaximumThreshold:function(value)
{this.data.maximum_threshold=value;return this;},setQuantityLimit:function(value)
{this.data.quantity_limit=value;return this;},setIsAllowedToGift:function(value)
{this.data.allowed_to_gift=value?1:0;return this;},setRedemptionPeriod:function(value)
{this.data.redemption_period=value;return this;},setDealImage:function(dealImage)
{this.dealImage=dealImage;},setRejectionMsg:function(value)
{this.data.reject_msg=value;},getUpdateParams:function()
{var params=$.extend({},this.data);if(this.dealImage)
{params['image_id']=this.dealImage.getId();}
return params;},getRestEntityName:function()
{return'deal';},getOffers:function(success,error)
{var self=this;if(!this.offerList)
{var id=this.getId();Model.ajax({url:'/deal/offer-list/'+id,type:'GET',success:function(response)
{self.offerList=[];$.each(response.offer_list,function(i,offerData)
{self.offerList.push(new Model.Offer(offerData));});success(self.offerList);},error:function(response){error(response);}});}
else
{success(this.offerList);}},setOfferList:function(offerData)
{var self=this;self.offerList=[];$.each(offerData,function(i,offerRow)
{self.offerList.push(new Model.Offer(offerRow));});},approve:function(success,error)
{var self=this;var id=this.getId();Model.ajax({url:'/deal/approval/',type:'POST',data:{deal_id:id,approve:'1'},success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response){error(response);}});},reject:function(success,error)
{var self=this;var id=this.getId();var msg=this.getRejectionMsg();Model.ajax({url:'/deal/approval/',type:'POST',data:{deal_id:id,approve:'0',message:msg},success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response){error(response);}});},isApproved:function()
{return(this.getStatus()=='accepted');},isRejected:function()
{return($.inArray(this.getStatus(),['manually_rejected','system_rejected'])!=-1);},cropImage:function(coords,success,error)
{var self=this;var id=this.getId();Model.ajax({url:'/deal/image-crop/',type:'POST',data:{deal_id:id,x1:coords.x1,y1:coords.y1,x2:coords.x2,y2:coords.y2},success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response){error(response);}});}};Model.extend(Deal);Model.Deal=Deal;})(MLD.Model,jQuery);

(function(Model,$){var RedemptionPeriod=function(data)
{Model.call(this,data);}
RedemptionPeriod.loadAll=function(success,error)
{$.ajax({'url':'/api/redemption-period/','method':'GET','dataType':'json','success':function(response){if(!response||!response.success)
{this.error(response);return;}
var redemptionPeriodArray=[];$.each(response.redemption_period_list,function(i,data){redemptionPeriodArray.push(new RedemptionPeriod(data));});success(redemptionPeriodArray);},'error':function(response){error(response);}});}
RedemptionPeriod.prototype={data:{'id':null},getId:function()
{return this.data.id;},getCode:function()
{return this.data.code;},getName:function()
{return this.data.name;},getRestEntityName:function()
{return'redemption_period';}}
Model.extend(RedemptionPeriod);Model.RedemptionPeriod=RedemptionPeriod;})(MLD.Model,jQuery);

(function(Model,$){var Organization=function(data)
{Model.call(this,data);}
Organization.search=function(options,success,error)
{var defaults={page:1,rowsPerPage:5,name:null};options=$.extend({},defaults,options);var url='/organization/search/?page='+options.page
+'&rows_per_page='+options.rowsPerPage;if(options.name)
{url+='&name='+options.name;}
Model.ajax({url:url,type:'GET',success:function(response)
{success(new Model.Search(response.organization_search));},error:function(response){error(response);}});}
Organization.getProviderOptionList=function(success,error)
{Model.ajax({url:'/organization/provider-option-list',type:'GET',success:function(response)
{var providerOptionArray=[];$.each(response.provider_option_list,function(i,data){providerOptionArray.push({id:data.id,name:data.name});});success(providerOptionArray);},error:function(response){if(error)
{error(response);}}});}
Organization.prototype={person:null,paymentAddress:null,data:{'id':null},orgImage:null,getId:function()
{return this.data.id;},getName:function()
{return this.data.name;},getImageUrl:function()
{return this.data.image_url;},getImageThumbnailUrl:function()
{return this.data.image_thumbnail_url;},setName:function(value)
{this.data.name=value;return this;},isMerchant:function()
{return this.data.type=='merchant';},setType:function(value)
{this.data.type=value;return this;},setCategory:function(value)
{this.data.category=value;return this;},setPhoneNumber:function(value)
{this.data.phone_number=value.replace(/[^\d]/g,'');return this;},setPerson:function(person)
{this.person=person;return this;},setPaymentAddress:function(paymentAddress)
{this.paymentAddress=paymentAddress;return this;},setOrganizationImage:function(orgImage)
{this.orgImage=orgImage;},getRestEntityName:function()
{return'organization';},getCreateParams:function()
{var params=$.extend({},this.data);if(this.paymentAddress)
{params['payment_address']=this.paymentAddress.getUpdateParams();}
if(this.person)
{params['person']=this.person.getCreateParams();}
return params;}}
Model.extend(Organization);Model.Organization=Organization;})(MLD.Model,jQuery);

(function(Model,$){var Person=function(data)
{Model.call(this,data);}
Person.search=function(options,success,error)
{var defaults={page:1,rowsPerPage:5,name:null};options=$.extend({},defaults,options);var url='/person/search/?page='+options.page
+'&rows_per_page='+options.rowsPerPage;if(options.name)
{url+='&name='+options.name;}
Model.ajax({url:url,type:'GET',success:function(response)
{success(new Model.Search(response.person_search));},error:function(response){error(response);}});}
Person.prototype={data:{'id':null},getFirstName:function()
{return this.data.first_name;},setFirstName:function(value)
{this.data.first_name=value;return this;},getLastName:function()
{return this.data.last_name;},setLastName:function(value)
{this.data.last_name=value;return this;},getEmail:function()
{return this.data.email;},setEmail:function(value)
{this.data.email=value;return this;},getFacebookId:function()
{return this.data.facebook_id;},getOrganizationId:function()
{return this.data.organization_id;},getRole:function()
{return this.data.role;},getRestEntityName:function()
{return'person';}}
Model.extend(Person);Model.Person=Person;})(MLD.Model,jQuery);

(function(Model,$){var OrganizationImage=function(data)
{this.data=data;};OrganizationImage.prototype={data:null,getId:function()
{return this.data.id;},getOriginalId:function()
{return this.data.original_file.id;},getImageId:function()
{return this.data.image_file.id;},getThumbnailId:function()
{return this.data.image_thumbnail_file.id;},getOriginalUrl:function()
{return this.data.original_file.url;},getImageUrl:function()
{return this.data.image_file.url;},getThumbnailUrl:function()
{return this.data.image_thumbnail_file.url;},getUpdateParams:function()
{var self=this;var params={image_original_file_id:self.getOriginalId(),image_file_id:self.getImageId(),image_thumbnail_file_id:self.getThumbnailId()};return params;}};Model.OrganizationImage=OrganizationImage;})(MLD.Model,jQuery);

(function(Model,$){var Account=function(data)
{Model.call(this,data);}
Account.loadByPersonId=function(personId,success,error)
{var self=this;if(!personId)
{error();return;}
Model.ajax({'url':'/person/account/'+personId,'type':'GET','success':function(response){success(new Model.Account(response['account']));},'error':function(response){error(response);}});}
Account.prototype={data:{'id':null},getAvailableBalance:function()
{return this.data.available_balance;},setAvailableBalance:function(value)
{this.data.available_balance=value;return this;},getRestEntityName:function()
{return'account';}}
Model.extend(Account);Model.Account=Account;})(MLD.Model,jQuery);

(function(Model,$){var Purchase=function(data)
{Model.call(this,data);};Purchase.search=function(options,success,error)
{var defaults={page:1,rowsPerPage:5};options=$.extend({},defaults,options);Model.ajax({url:'/purchase/search/',data:{page:options.page,rows_per_page:options.rowsPerPage,offer_id:options.offer_id},type:'GET',success:function(response)
{success(new Model.Search(response.purchase_search));},error:function(response){error(response);}});};Purchase.prototype={data:{'id':null},voucherList:null,getStatus:function()
{return this.data.status;},getAmount:function()
{return this.data.amount;},getQuantity:function()
{return this.data.quantity;},getBuyerName:function()
{return this.data.buyer_name;},getRestEntityName:function()
{return'purchase';},getVouchers:function(success,error)
{var self=this;if(!this.voucherList){var id=this.getId();Model.ajax({url:'/purchase/voucher-list/'+id,type:'GET',success:function(response)
{self.voucherList=[];$.each(response.voucher_list,function(i,voucherData)
{self.voucherList.push(new Model.Voucher(voucherData));});success(self.voucherList);},error:function(response){error(response);}});}
else{success(this.voucherList);}},refund:function(success,error)
{var self=this;var id=this.getId();Model.ajax({url:'/purchase/refund/',type:'POST',data:{purchase_id:id},success:function(response){success(self.getNewSelfFromResponse(response));},error:function(response){error(response);}});}};Model.extend(Purchase);Model.Purchase=Purchase;})(MLD.Model,jQuery);

(function(Model,$){var Voucher=function(data)
{Model.call(this,data);}
Voucher.prototype={data:{'id':null},getId:function()
{return this.data.id;},getCode:function()
{return this.data.voucher_code;},getRestEntityName:function()
{return'voucher';}}
Model.extend(Voucher);Model.Voucher=Voucher;})(MLD.Model,jQuery);

(function(Model,$){var Comment=function(data)
{Model.call(this,data);}
Comment.search=function(options,success,error)
{var defaults={};options=$.extend({},defaults,options);Model.ajax({url:'/comment/offer/',data:{offer_id:options.offer_id},type:'GET',success:function(response){success(new Model.Search(response.comment_list));},error:function(response){error(response);}});};Comment.prototype={data:{'id':null},getId:function()
{return this.data.id;},getText:function()
{return this.data.text;},getAuthorId:function()
{return this.data.author_id;},getAuthorName:function()
{return this.data.author_name;},getAuthorLabel:function()
{return this.data.author_label;},setText:function(value)
{this.data.text=value;return this;},add:function(offerId,msg,success,error)
{Model.ajax({url:'/comment/',type:'POST',data:{offer_id:offerId,person_id:UserInfo.getPersonId(),text:msg},success:function(response)
{success();},error:function(response)
{error(response);}});},flag:function(success,error)
{Model.ajax({url:'/comment/flag/',type:'POST',data:{id:this.getId()},success:function(response)
{success();},error:function(response)
{error(response);}});},getRestEntityName:function()
{return'comment';},getCreateParams:function()
{var params=$.extend({},this.data);return params;}}
Model.extend(Comment);Model.Comment=Comment;})(MLD.Model,jQuery);

(function(Model,$){var Cbsa=function(data)
{Model.call(this,data);}
Cbsa.getOne=function(code,success,error)
{var self=this;Model.ajax({'url':'/cbsa/'+code,'type':'GET','success':function(response){success(new Cbsa(response['cbsa']));},'error':function(response){error(response);}});}
Cbsa.prototype={getName:function()
{return this.data.name;},getCbsaCode:function()
{return this.data.cbsa;},getName:function()
{return this.data.cbsa_name;},getRestEntityName:function()
{return'cbsa';}}
Model.extend(Cbsa);Model.Cbsa=Cbsa;})(MLD.Model,jQuery);

(function(Model,$){var Pmsa=function(data)
{Model.call(this,data);}
Pmsa.getOne=function(code,success,error)
{var self=this;Model.ajax({'url':'/pmsa/'+code,'type':'GET','success':function(response){success(new Pmsa(response['pmsa']));},'error':function(response){error(response);}});}
Pmsa.prototype={getName:function()
{return this.data.name;},getPmsaCode:function()
{return this.data.pmsa;},getName:function()
{return this.data.pmsa_name;},getRestEntityName:function()
{return'pmsa';}}
Model.extend(Pmsa);Model.Pmsa=Pmsa;})(MLD.Model,jQuery);

(function(Model,$){var UserInfo={data:null,load:function(success,error)
{this.loadInfo(false,success,error);},isLoggedIn:function()
{this.loadInfo();return this.data.logged_in;},isFacebookUser:function()
{return(this.getFacebookId())?true:false;},getFirstName:function()
{this.loadInfo();return this.data.person.getFirstName();},getLastName:function()
{this.loadInfo();return this.data.person.getLastName();},getEmail:function()
{this.loadInfo();return this.data.person.getEmail();},getFacebookId:function()
{this.loadInfo();return this.data.person.getFacebookId();},getPersonId:function()
{this.loadInfo();return this.data.person.getId();},getOrganizationId:function()
{this.loadInfo();return this.data.person.getOrganizationId();},getRole:function()
{this.loadInfo();return this.data.person.getRole();},reloadInfo:function()
{this.loadInfo(true);},loadInfo:function(forceReload,success,error)
{var async=$.isFunction(success);if(!forceReload&&this.data!==null)
{return;}
var self=this;if($.isFunction(window.citizenLocalUserInfo))
{this.loadFromJson(window.citizenLocalUserInfo());window.citizenLocalUserInfo=null;}
else
{Model.ajax({url:'/person/auth',async:async,type:'GET',success:function(response){self.loadFromJson(response);if(success)
{success(response);}},error:function(){if(error)
{error();}}});}},loadFromJson:function(response)
{this.data={};this.data.logged_in=response.is_signed_in?true:false;this.data.person=new Model.Person(response.person);},logout:function(success,error)
{Model.ajax({url:'/person/auth?_method=DELETE',async:true,type:'POST',dataType:'json',success:function(){success();},error:function(response){error(response);}});},clearData:function()
{this.data=null;}};MLD.UserInfo=UserInfo;})(MLD.Model,jQuery);

(function($){var Validator=function(validate,error)
{if(validate)
{this.validate=validate;}
if(error)
{this.error=error;}
this.validators=[];}
Validator.extend=function(child)
{child.prototype=$.extend({},Validator.prototype,child.prototype);child.prototype.constructor=child;}
Validator.prototype={validators:null,error:function(errorCode){alert('Error "'+errorCode+'" was received.')},validate:function(validator)
{var result=true;$.each(this.validators,function(i,val){result=val.isValid()&&result;});return result;},errorCode:null,isValid:function()
{var isValid;if($.isFunction(this.validate))
{isValid=this.validate(this);}
else
{isValid=this.validate.isValid();this.errorCode=this.validate.errorCode;}
if(!isValid)
{this.error(this.errorCode)}
return isValid;}}
MLD.Validator=Validator;})(jQuery);

(function(Validator,$){var Required=function(inputElement,error)
{if(!inputElement.size())
{throw('Validator.Required requires an input to validate.');}
this.inputElement=inputElement;Validator.call(this,null,error);}
Required.prototype={inputElement:null,validate:function()
{var value=this.inputElement.val();if(value==='')
{this.errorCode='isEmpty';return false;}
return true;}}
Validator.extend(Required);Validator.Required=Required;})(MLD.Validator,jQuery);

(function(Validator,$){var StreetAddress=function(inputElement,error)
{this.inputElement=inputElement;Validator.call(this,null,error);var $form=this.inputElement;this.validators.push(new Validator.Required($(':input[name="street1"]',$form),function(errorCode)
{$('.error-message.street1',$form).show();}));this.validators.push(new Validator.Required($(':input[name="city"]',$form),function(errorCode)
{$('.error-message.city',$form).show();}));this.validators.push(new Validator.Required($(':input[name="state"]',$form),function(errorCode)
{$('.error-message.state',$form).show();}));this.validators.push(new Validator(function(validator)
{if($(':input[name="zip_code"]',$form).val().match(/^\d\d\d\d\d$/)===null)
{this.errorCode='notValid';return false;}
return true;},function(errorCode)
{$('.error-message.zip_code',$form).show();}));}
StreetAddress.prototype={inputElement:null,validators:[],validate:function()
{var result=true;$.each(this.validators,function(i,validator){result=validator.isValid()&&result;});return result;}}
Validator.extend(StreetAddress);Validator.StreetAddress=StreetAddress;})(MLD.Validator,jQuery);

(function(Validator,$){var PersonEmail=function(inputElement,error)
{this.inputElement=inputElement;Validator.call(this,null,error);}
PersonEmail.prototype={inputElement:null,validate:function()
{var self=this;var email=this.inputElement.val();var exists=false;if(email==='')
{this.errorCode='isEmpty';return false;}
var url='/api/email-address/member/'+email;$.ajax({url:url,async:false,success:function(json){if(json.success){exists=true;self.errorCode='emailExists';}},error:function(json){exists=false;}});return!exists;}}
Validator.extend(PersonEmail);Validator.PersonEmail=PersonEmail;})(MLD.Validator,jQuery);

(function(Validator,$){var PhoneNumber=function(inputElement,error,options)
{this.inputElement=inputElement;Validator.call(this,null,error);this.settings=$.extend({},this.settings,options);}
PhoneNumber.prototype={inputElement:null,settings:{isRequired:false},validate:function()
{var result=Boolean(this.inputElement.val().replace(/[^\d]/g,'').match(/^\d\d\d\d\d\d\d\d\d\d$/)!==null);if(!result)
{this.errorCode='invalid';}
return result;}}
Validator.extend(PhoneNumber);Validator.PhoneNumber=PhoneNumber;})(MLD.Validator,jQuery);

(function($){$.fn.TextAreaSizer=function(options)
{return this.each(function(){var settings={minRows:5,maxRows:-1};$.extend(settings,options);var $this=$(this);var columnCount=$this.attr('cols');var adjustSize=function()
{var newRowCount=0;var j=0;$.each($this.val(),function(i,charVal){if(charVal=="\n"||j>columnCount)
{newRowCount++;j=0;}
else
{j++;}
if(settings.maxRows>-1&&newRowCount>=settings.maxRows)
{var tempVal=$this.val()
var tempValLength=tempVal.length;$this.val(tempVal.substring(0,i));var newValLength=$this.val().length;return false;}
return true;});if(newRowCount<settings.maxRows)
{newRowCount++;}
if(newRowCount<settings.minRows)
{newRowCount=settings.minRows;}
$this.attr('rows',newRowCount);}
$this.keyup(function(){adjustSize();});$this.blur(function(){adjustSize();});adjustSize();});}})(jQuery);

(function(View,$){$.fn.DealTextSortable=function(method)
{if(methods[method])
{return methods[method].apply(this,Array.prototype.slice.call(arguments,1));}
else if(typeof method==='object'||!method)
{return methods.init.apply(this,arguments);}
else
{$.error('Method '+method+' does not exist on DealTextSortable');}}
var methods={init:function(options)
{return this.each(function()
{var settings={min:1,max:5,initialCount:3,textMaxLength:90}
if(options)
{$.extend(settings,options);}
if(settings.initialCount<settings.min)
{settings.initialCount=settings.min;}
else if(settings.initialCount>settings.max)
{settings.initialCount=settings.max;}
var $this=$(this);var text=$this.html();var pattern=/<br>|<br\/>|<br \/>/gi;var textConvertedBr=text.replace(pattern,"\n");var textItems=textConvertedBr.split("\n");$.each(textItems,function(i,value){if($.trim(value).length<1)
{textItems.splice(i,1);}});if(textItems.length<1)
{textItems=[];for(var i=0;i<settings.initialCount;i++)
{textItems.push('');}}
var newHtml='';$.each(textItems,function(i,textItem){newHtml+=View('/dmapi/views/deal-text-sortable/text-item.jhtml',{textValue:textItem,textMaxLength:settings.textMaxLength});});$this.html(newHtml);$this.sortable({items:'div.text-item'});var calculateLimits=function()
{if($('div.text-item',$this).length<=settings.min)
{$('a.del-d-loc',$this).hide();}
else
{$('a.del-d-loc',$this).show();}
if($('div.text-item',$this).length>=settings.max)
{$('a.add-d-loc',$this).hide();}
else
{$('a.add-d-loc',$this).show();}}
$('a.del-d-loc',$this).live('click',function(){$(this).closest('div.text-item').remove();calculateLimits();});$('a.add-d-loc',$this).live('click',function(){$(this).closest('div.text-item').after(View('/dmapi/views/deal-text-sortable/text-item.jhtml',{textValue:'',textMaxLength:settings.textMaxLength}));calculateLimits();});calculateLimits();});},getText:function()
{var value='';$('div.text-item :input[type="text"]',$(this)).each(function(i){var tempValue=$(this).val();if($.trim(tempValue).length>0)
{value+=$(this).val()+"\n";}});return $.trim(value);}}})(MLD.View,jQuery);

(function(View,Model,$){$.fn.DealEditorImage=function(deal,options)
{return this.each(function()
{var widget=new DealEditorImage(this,deal,options);widget.render();$(this).data('DealEditorImage',widget);});};var DealEditorImage=function(element,deal,options)
{this.element=element;$.extend(this.settings,options);this.deal=deal;};DealEditorImage.prototype={element:null,deal:null,dealImage:null,settings:{uploadProcessing:function(){},uploadSuccess:function(){},thumbnailWidth:150,thumbnailHeight:100},render:function()
{var self=this;var $this=$(this.element);$this.append(View('/dmapi/views/deal-editor/image.jhtml'));$('.change input',$this).click(function(ev){ev.preventDefault();self.displayInput();});$('#crop-overlay .crop input').live('click',function(ev){ev.preventDefault();self.cropSubmit();});$('.deal-image',$this).attr('src',this.deal.getImageThumbnailUrl());$('.deal-image-link',$this).live('click',function(ev){ev.preventDefault();self.displayCrop();});$('.deal-img',$this).live('change',function(){self.upload();});},displayChangeButton:function()
{var $this=$(this.element);$('div.control',$this).hide();$('div.change',$this).show();},displayInput:function()
{var $this=$(this.element);$('div.control',$this).hide();$('div.file_input',$this).show();},displayProcessing:function()
{var $this=$(this.element);$('div.control',$this).hide();$('.crop img',$this).imgAreaSelect({hide:true});$('div.processing',$this).show();},displayError:function(message)
{var $this=$(this.element);$('div.control',$this).hide();$('div.error',$this).html(message).show();$('div.file_input',$this).show();},displayCrop:function()
{var $this=$(this.element);var self=this;var $overlay=$("#crop-overlay").data("overlay");$("#crop-overlay").data("overlay",null).overlay({mask:{color:'#999',opacity:0.5},load:true,fixed:false,left:"10%",top:"10%",onBeforeLoad:function(){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html(View('/dmapi/views/deal-editor/crop.jhtml'));$('.deal-image-original',wrap).attr('src',self.deal.getImageOriginalUrl());},onLoad:self.cropLoaded,onClose:self.cropClose}).data('cropDealId',self.deal.getId());},cropLoaded:function()
{var $this=$("#crop-overlay");var $overlay=$("#crop-overlay").data("overlay");var width=$('img',$this).width();$this.css("width","auto");$('.crop img',$this).imgAreaSelect({handles:true,aspectRatio:'3:2'});},cropSubmit:function()
{var $this=$(this.element);var $overlay=$("#crop-overlay");var self=this;var sel=$('.crop img',$overlay).imgAreaSelect({instance:true}).getSelection();if(self.deal.getId()!=$overlay.data('cropDealId')){return;}
if(sel.height==0&&sel.width==0){return;}
this.displayProcessing();$overlay.data("overlay").close();self.deal.cropImage(sel,function(deal)
{self.displayChangeButton();$('img.deal-image',$this).attr('src',deal.getImageThumbnailUrl());self.settings.uploadSuccess();},function()
{alert('An error occurred.');});},cropClose:function()
{var $this=$("#crop-overlay");$('.crop img',$this).imgAreaSelect({remove:true});},upload:function()
{this.displayProcessing();this.settings.uploadProcessing();var uploadSuccess=this.settings.uploadSuccess;var self=this;var $this=$(this.element);if(!this.validateImageFile()){return;}
var imageId='deal-img-'+this.deal.getId();$(':input[name="deal-img"]',$this).attr('id',imageId);$.ajaxFileUpload({url:'/ajax/deal-image/upload',secureuri:false,fileElementId:imageId,dataType:'json',success:function(data,status)
{if(!data.success||!data.deal_image)
{this.error(data,status);return;}
var dealImage=new Model.DealImage(data.deal_image);self.deal.setDealImage(dealImage);var imageUrl=dealImage.getThumbnailUrl();$('img.deal-image',$this).attr('src',imageUrl);self.displayInput();uploadSuccess();},error:function(data,status,e)
{var message;switch(data.error)
{case'invalidFormat':message='The image format was not recognized.';break;case'tooLarge':message='The image was too large.';break;default:message='There was an error with the image upload.';break;}
self.displayError(message);}});},getDealImage:function()
{return this.dealImage;},validateImageFile:function()
{var $this=$(this.element);var fileExtension=$(':input[name="deal-img"]',$this).val().split('.').pop();if($.inArray(fileExtension.toLowerCase(),['gif','png','jpg','jpeg'])==-1)
{var message='The image format was not recognized.';this.displayError(message);return false;}
return true;}};})(MLD.View,MLD.Model,jQuery);

(function(View,$){$.fn.DealEditorOfferRowLocation=function(orgLocation,options)
{return this.each(function()
{var widget=new DealEditorOfferRowLocation(this,orgLocation,options);$(this).data('DealEditorOfferRowLocation',widget);});}
var DealEditorOfferRowLocation=function(element,organizationLocation,options)
{var self=this;this.element=element;this.organizationLocation=organizationLocation;$.extend(this.settings,options);this.render();}
DealEditorOfferRowLocation.prototype={element:null,organizationLocation:null,settings:{edit:function(organizationLocation)
{alert('edit organization location id#'+organizationLocation.getId());}},render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/deal-editor/offer-location.jhtml',{location:self.organizationLocation}));$('.control-edit',$this).click(function(){self.settings.edit(self.organizationLocation);});}}})(MLD.View,jQuery);

(function(View,Model,$){$.fn.DealEditorOfferRowLocationEdit=function(orgLocation,options)
{return this.each(function()
{var widget=new DealEditorOfferRowLocationEdit(this,orgLocation,options);widget.renderEditForm();$(this).data('DealEditorOfferRowLocationEdit',widget);});}
var DealEditorOfferRowLocationEdit=function(element,organizationLocation,options)
{this.element=element;$.extend(this.settings,options);this.organizationLocation=organizationLocation;}
DealEditorOfferRowLocationEdit.prototype={element:null,organizationLocation:null,settings:{cancel:function(){alert('cancel action not implemented.');},save:function(){alert('save action not implemented.');}},renderEditForm:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/deal-editor/offer-location-edit.jhtml',{location:self.organizationLocation}));Model.State.loadAll(function(states){var optionsString=View('/dmapi/views/select_options.jhtml',{items:states,valueCallbackName:'getAbbreviation',displayCallbackName:'getName'});$('form :input[name="state"]',$this).html(optionsString);$('form :input[name="state"] option[value="'
+self.organizationLocation.getStreetAddress().getState()
+'"]',$this).attr('selected','selected');});$(':input[name="save"]',$this).click(function(){self.save();});$(':input[name="cancel"]',$this).click(function(){self.settings.cancel();});},save:function()
{var self=this;var $this=$(this.element);var loc=this.organizationLocation;var addr=this.organizationLocation.getStreetAddress();addr.setStreet1($('form :input[name="street1"]',$this).val()).setStreet2($('form :input[name="city"]',$this).val()).setCity($('form :input[name="city"]',$this).val()).setState($('form :input[name="state"]',$this).val()).setZipCode($('form :input[name="zip_code"]',$this).val());loc.setName($('form :input[name="name"]',$this).val()).setPhoneNumber($('form :input[name="phone_number"]',$this).val()).save(function(orgLocation)
{self.settings.save(orgLocation);},function(response)
{alert('An error has ocurred.');});}}})(MLD.View,MLD.Model,jQuery);

(function(View,Model,$){$.fn.DealEditorOfferRow=function(offer,options)
{return this.each(function()
{var widget=new DealEditorOfferRow(this,offer,options);widget.renderDetails();$(this).data('DealEditorOfferRow',widget);});};var DealEditorOfferRow=function(element,offer,options)
{this.element=element;$.extend(this.settings,options);this.offer=offer;};DealEditorOfferRow.prototype={element:null,offer:null,settings:{},renderDetails:function()
{var self=this;var $this=$(this.element);$this.html('');$this.append(View('/dmapi/views/deal-editor/offer-details.jhtml',{offer:self.offer}));if(self.offer.hasAdditionalInfo()){$this.append(View('/dmapi/views/deal-editor/offer-additional.jhtml',{offer:self.offer}));}
$this.append(View('/dmapi/views/deal-editor/offer-email.jhtml',{offer:self.offer,marketingInfo:self.offer.getMarketingInfo()}));$(':input[name="close_button"]',$this).click(function(){self.offerClose();});$('.schedule',$this).click(function(ev){ev.preventDefault();self.renderScheduleForm();});$(':input[name="locations_button"]',$this).click(function(){self.renderLocations();});$('.offer-email-table-open',$this).click(function(ev){ev.preventDefault();$('.offer-email-table',$this).slideDown();});$('.offer-additional-table-open',$this).click(function(ev){ev.preventDefault();$('.offer-additional-table',$this).slideDown();self.populateAdditionalTable();});},renderScheduleForm:function()
{var self=this;var $this=$(this.element);var offer=this.offer;$this.html(View('/dmapi/views/deal-editor/offer-schedule.jhtml',{offer:self.offer}));$(':input[name="start_date"]',$this).datepicker();$(':input[name="end_date"]',$this).datepicker();$(':input[name="expiration_date"]',$this).datepicker();$(':input[name="cancel_button"]',$this).click(function(){self.renderDetails();});$('.tippr-sites-select',$this).each(function(i){self.setupTipprSites();});$(':input[name="add_dma"]',$this).click(function(){var newDma=$(':input[name="new_dma"]',$this).val();if(newDma!=parseInt(Math.abs(newDma)))
{alert('DMA must be a number.');return;}
$(':input[name="new_dma"]',$this).val('');$('#dma_list',$this).append('<li><input type="hidden" value="'+newDma+'" />'+newDma+'</li>');});$(':input[name="add_cbsa"]',$this).click(function(){var newCbsa=$(':input[name="new_cbsa"]',$this).val();Model.Cbsa.getOne(newCbsa,function(cbsa)
{$(':input[name="new_cbsa"]',$this).val('');$('#cbsa_list',$this).append('<li><input type="hidden" value="'+newCbsa+'" />'+cbsa.getName()+'('+newCbsa+') <a class="delete">href="#">X</a></li>');},function()
{alert('The CBSA you entered is invalid.');});});$('#cbsa_list li .delete').live('click',function(evt){$(this).closest('li').remove();});$(':input[name="add_pmsa"]',$this).click(function(){var newPmsa=$(':input[name="new_pmsa"]',$this).val();Model.Pmsa.getOne(newPmsa,function(pmsa)
{$(':input[name="new_pmsa"]',$this).val('');$('#pmsa_list',$this).append('<li><input type="hidden" value="'+newPmsa+'" />'+pmsa.getName()+'('+newPmsa+') <a class="delete">href="#">X</a></li>');},function()
{alert('The PMSA you entered is invalid.');});});$('#pmsa_list li .delete').live('click',function(evt){$(this).closest('li').remove();});$(':input[name="submit_button"]',$this).click(function(){var dateValue=$(':input[name="start_date"]',$this).val();var startDate=null;if(dateValue){var hour=$(':input[name="start_hour"]',$this).val();var minute=$(':input[name="start_minute"]',$this).val();startDate=new Date(dateValue+' '+hour+':'+minute+':00');}
else{alert("No start date");return;}
dateValue=$(':input[name="end_date"]',$this).val();if(dateValue){hour=$(':input[name="end_hour"]',$this).val();minute=$(':input[name="end_minute"]',$this).val();var endDate=new Date(dateValue+' '+hour+':'+minute+':00');}
else{alert("No end date");return;}
var expirationDate=null;dateValue=$(':input[name="expiration_date"]',$this).val();if(dateValue){hour=$(':input[name="expiration_hour"]',$this).val();minute=$(':input[name="expiration_minute"]',$this).val();expirationDate=new Date(dateValue+' '+hour+':'+minute+':00');}
var marketingOptions=self.getMarketingOptions();var promoOptions=self.getPromoOptions();offer.schedule(startDate,endDate,expirationDate,marketingOptions,promoOptions,function(offer)
{self.offer=offer;alert('Offer ID#'+offer.getId()+' scheduled successfully.');self.renderDetails();},function(jqxhr,textStatus,errorThrown)
{var errMsg='An error occurred with scheduling the offer.';if(errorThrown){errMsg=errorThrown;}
errMsg="WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n "+errMsg;alert(errMsg);});});},renderLocations:function()
{var self=this;var $this=$(this.element);var offer=this.offer;$this.html(View('/dmapi/views/deal-editor/offer-location-list.jhtml'));offer.getOrganizationLocations(function(locationList)
{$.each(locationList,function(i,location){self.addLocationWidget(location);});$(':input[name="back"]',$this).click(function(){self.renderDetails();});},function(response)
{alert('There was an error loading the locations.');});},offerClose:function()
{var self=this;if(confirm('Are you sure you want to close the offer in '+self.offer.getArea().getName()))
{self.offer.close(function(offer){self.offer=offer;self.renderDetails();alert('The offer was successfully closed.');},function(){alert('An error occurred when attempting to close offer.');});}},addLocationWidget:function(location)
{var self=this;var $this=$(this.element);var div=$('<div> </div>');var editorOptions={cancel:function(){self.renderLocations();},save:function(orgLocation){self.renderLocations();}};var options={edit:function(orgLocation){var div=$('<div> </div>');div.DealEditorOfferRowLocationEdit(orgLocation,editorOptions);$this.html(div);}};$(div).DealEditorOfferRowLocation(location,options);$('div.location-list',$this).append(div);},getMarketingOptions:function()
{var $this=$(this.element);var obj={};obj.email_radius=$(':input[name="email_radius"]',$this).val();obj.email_subject_a=$(':input[name="email_subject_a"]',$this).val();obj.email_subject_b=$(':input[name="email_subject_b"]',$this).val();obj.dma_list=[];$('#dma_list :input',$this).each(function(index,input){obj.dma_list.push($(input).val());});obj.area_list=[];$('#area_list :input',$this).each(function(index,input){obj.area_list.push($(input).val());});obj.cbsa_list=[];$('#cbsa_list :input',$this).each(function(index,input){obj.cbsa_list.push($(input).val());});obj.pmsa_list=[];$('#pmsa_list :input',$this).each(function(index,input){obj.pmsa_list.push($(input).val());});return obj;},getPromoOptions:function()
{var $this=$(this.element);var obj={};obj.quantity=$(':input[name="quantity_to_reserve"]',$this).val();obj.bid=$(':input[name="counter_bid"]',$this).val();obj.site_id=$('.tippr-sites-select',$this).val();return obj;},setupTipprSites:function()
{var self=this;var $this=$(this.element);self.offer.getTipprSites(function(response){var ts=response.tipprsites;$.each(ts.sites,function(i,site){var market=site.market;var opt='<option value="'+site.id+'">'+market.label+'</option>';$('.tippr-sites-select',$this).append(opt);});self.populateTipprPromoFields();},function(){if(console){console.log('An error occurred getting Tippr sites');}});},populateAdditionalTable:function()
{var self=this;if(self.offer.getPublisher().name=="Tippr"){var promoId=self.offer.getForeignPromoId();if(!promoId){return;}
var $this=$(this.element);self.offer.getTipprPromo(promoId,function(response){var promo=response.promo;$('.offer-additional-table-quantity',$this).html(promo.quantity);$('.offer-additional-table-bid',$this).html(promo.bid);$('.offer-additional-table-site',$this).html(promo.site_name);$('.offer-additional-table-comments',$this).html(promo.comment_text);},function(){if(console!=undefined){console.log('An error occurred getting Tippr promo');}});}},populateTipprPromoFields:function()
{var self=this;var promoId=self.offer.getForeignPromoId();if(!promoId){return;}
var $this=$(this.element);self.offer.getTipprPromo(promoId,function(response){var promo=response.promo;$(':input[name="inventory_id"]',$this).val(promo.id);$(':input[name="quantity_to_reserve"]',$this).val(promo.quantity);$(':input[name="counter_bid"]',$this).val(promo.bid);self.setTipprSite(promo.site_id);},function(){if(console){console.log('An error occurred getting Tippr promo');}});},setTipprSite:function(siteId)
{var $this=$(this.element);$('.tippr-sites-select option',$this).each(function(i){if($(this).val()==siteId){$('.tippr-sites-select',$this).val(siteId);}});}};})(MLD.View,MLD.Model,jQuery);

(function(View,Model,$){$.fn.DealEditor=function(id)
{return $(this).each(function()
{$(this).data('DealEditor',new DealEditor(this,id));});}
var DealEditor=function(element,id){var self=this;this.element=$(element);if(id instanceof Model.Deal)
{this.dealLoadSuccess(id);}
else
{Model.Deal.load(id,function(deal){self.dealLoadSuccess(deal)},function(response){self.dealLoadError(response)});}}
DealEditor.prototype={element:null,deal:null,dealLoadSuccess:function(deal)
{var self=this;this.deal=deal;var $this=this.element;$this.html(View('/dmapi/views/deal-editor/edit.jhtml',{deal:deal}));$('.description-textarea',$this).TextAreaSizer();$('.fineprint-dealtext',$this).DealTextSortable();$('.highlights-dealtext',$this).DealTextSortable();this.updateDiscount();$('select[name="category"]',$this).val(deal.getCategory());$('select[name="subcategory"]',$this).val(deal.getSubcategory());Model.RedemptionPeriod.loadAll(function(redemptionPeriods){var optionsString='';$.each(redemptionPeriods,function(i,period){var selected=deal.getRedemptionPeriod()==period.getCode()?'selected':'';optionsString+='<option value="'
+period.getCode()
+'" '+selected+'>'
+period.getName()
+'</option>';});$('form :input[name="redemption_period"]',$this).html(optionsString);});this.addSaveListener();this.addApproveListener();this.addRejectListener();$('div.image-widget',$this).DealEditorImage(deal,{uploadProcessing:function()
{self.disableSave();},uploadSuccess:function()
{self.enableSave();}});$('.cancel-edit',$this).click(function(ev){ev.preventDefault();$this.siblings('.approval-steps').show();$this.remove();});$(':input[name="cost"]',$this).keyup(function(){self.updateDiscount();});$(':input[name="value"]',$this).keyup(function(){self.updateDiscount();});this.loadOffers();},dealLoadError:function(response)
{$(this).html('An error occurred.');},addSaveListener:function()
{var self=this;var $this=this.element;var $form=$('form',$this);$('.save-deal-btn a',$form).click(function(ev){ev.preventDefault();self.deal.setTitle($(':input[name="title"]',$form).val()).setDescription($('.description-textarea',$form).val()).setHighlights($('.highlights-dealtext',$this).DealTextSortable('getText')).setFinePrint($('.fineprint-dealtext',$this).DealTextSortable('getText')).setValue($(':input[name="value"]',$form).val()).setCost($(':input[name="cost"]',$form).val()).setMinimumThreshold($(':input[name="minimum_threshold"]',$form).val()).setMaximumThreshold($(':input[name="maximum_threshold"]',$form).val()).setQuantityLimit($(':input[name="quantity_limit"]',$form).val()).setIsAllowedToGift($(':input[name="allowed_to_gift"]',$form).is(':checked')).setRedemptionPeriod($(':input[name="redemption_period"]',$form).val()).setCategory($('select[name="category"]',$form).val()).setSubcategory($('select[name="subcategory"]',$form).val()).save(function(deal){self.dealLoadSuccess(deal);alert('Deal saved successfully!');},function(){alert('Deal save went horribly wrong.');});});},addApproveListener:function()
{var self=this;var $this=this.element;var $form=$('form',$this);$(':input[name="approve_button"]',$form).click(function(){if(confirm('Are you sure want to approve the deal?')){self.deal.approve(function(deal)
{self.dealLoadSuccess(deal);alert('The deal has been successfully approved.');},function()
{alert('An error occurred.');});}});},addRejectListener:function()
{var self=this;var $this=this.element;var $form=$('form',$this);$(':input[name="reject_button"]',$form).click(function(){if(confirm('Are you sure want to reject the deal?')){self.deal.reject(function(deal)
{self.dealLoadSuccess(deal);alert('The deal has been rejected.');},function()
{alert('An error occurred.');});}});},loadOffers:function()
{var self=this;var deal=this.deal;var $this=this.element;$('.offer-list',$this).html('');deal.getOffers(function(offerList)
{$.each(offerList,function(i,offer){$('.offer-list',$this).append($('<table class="offer-list-table"></table>').DealEditorOfferRow(offer,{offerClose:function(offer){self.offerClose(offer);}}));});},function(response)
{$this.append('Failed to load offer list');});},offerClose:function(offer)
{var self=this;if(confirm('Are you sure you want to close offer id#'+offer.getId()))
{offer.close(function(){self.loadOffers();},function(){alert('An error occurred when attempting to close offer.');});}},disableSave:function()
{var $this=$(this.element);$('.save-deal-btn a',$this).attr('disabled',true);},enableSave:function()
{var $this=$(this.element);$('.save-deal-btn a',$this).attr('disabled',false);},updateDiscount:function()
{var $this=$(this.element);var value=$(':input[name="value"]',$this).val();var cost=$(':input[name="cost"]',$this).val();var difference=value-cost;var discount=Math.round(difference/value*100);if(isNaN(discount)){discount=0;}
$('#discount_amount',$this).html(discount);}}})(MLD.View,MLD.Model,jQuery);

(function(View,$){$.fn.Paginator=function(search,options)
{return $(this).each(function()
{$(this).data('Paginator',new Paginator(this,search,options));});}
var Paginator=function(element,search,options)
{this.element=element;$.extend(this.settings,options);this.search=search;this.render();}
Paginator.prototype={element:null,search:null,settings:{renderPage:function(num){alert('Render page number '+num);},showPageInfo:true},render:function()
{var self=this;var $this=$(this.element);var search=this.search;var settings=this.settings;$this.html(View('/dmapi/views/paginator.jhtml',{search:search,settings:settings}));$('.previous_page',$this).click(function(){settings.renderPage(search.getPage()-1);});$('.next_page',$this).click(function(){settings.renderPage(search.getPage()+1);});$('.first_page',$this).click(function(){settings.renderPage(1);});$('.last_page',$this).click(function(){settings.renderPage(search.getLastPage());});$('.page',$this).click(function(){settings.renderPage($(':input',$(this)).val());});}}})(MLD.View,jQuery);

(function(View,$){$.fn.DealSearchRow=function(deal)
{return $(this).each(function()
{var widget=new DealSearchRow(this,deal);widget.setupApproveDeal();widget.setupRejectDeal();widget.setupEditDeal();widget.setupPurchaseList();$(this).data('DealSearchRow',widget);});}
var DealSearchRow=function(element,deal)
{this.element=element;this.deal=deal;var self=this;this.deal.getOffers(function(offerList){self.render();},function(response){console.log('DealSearchRow error');});}
DealSearchRow.prototype={element:null,deal:null,render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/deal-search/row.jhtml',{deal:self.deal}));$('.offer-list',$this).html(View('/dmapi/views/deal-search/row-offer-list.jhtml',{offerList:self.deal.offerList}));},refresh:function()
{var self=this;this.deal.getOffers(function(offerList){self.render();},function(response){console.log('DealSearchRow error');});},setupApproveDeal:function()
{var self=this;var $this=$(this.element);var deal=this.deal;$('.approve-btn .approval',$this).live('click',function(ev){ev.preventDefault();if(confirm('Are you sure you want to approve this deal?')){deal.approve(function(deal){self.deal=deal;self.refresh();},function(){alert('An error occurred while approving the deal.');});}});},setupRejectDeal:function()
{var self=this;var $this=$(this.element);var deal=this.deal;$('.approve-btn .rejection',$this).live('click',function(ev){ev.preventDefault();$('.reason',$this).removeClass('hide');$('.reject',$this).css({"cursor":"default","color":"#ccc","text-decoration":"none"});$('.reason textarea',$this).focus();});$('.reason .cancel',$this).live('click',function(ev){ev.preventDefault();$('.reason',$this).addClass('hide');$('.reject',$this).css({"cursor":"pointer","color":"#c33","text-decoration":"underline"});});$('.reason .submit-btn',$this).live('click',function(ev){ev.preventDefault();msg=jQuery.trim($('.reason textarea',$this).val());if(msg===""){alert("Please supply a reason");return;}
if(confirm('Are you sure you want to reject this deal?')){deal.setRejectionMsg(msg);deal.reject(function(deal){self.deal=deal;self.refresh();},function(){alert('An error occurred while rejecting the deal.');});}});},setupEditDeal:function()
{var self=this;var $this=$(this.element);var deal=this.deal;$('.reject-btn a',$this).live('click',function(ev){ev.preventDefault();$('.approval-steps',$this).after('<div class="deal-edit"></div>');$('.approval-steps',$this).hide();$('.deal-edit',$this).DealEditor(deal);});},setupPurchaseList:function()
{var self=this;var $this=$(this.element);$('.view-p-list',$this).live('click',function(ev){ev.preventDefault();var offerData=$(this).attr('title').split('|');if(offerData.length==2){$('.purchase-list',$this).PurchaseSearch({offer_id:offerData[1],area_name:offerData[0]});}});}};})(MLD.View,jQuery);

(function(View,Model,$){$.fn.DealSearch=function(options)
{return $(this).each(function()
{$(this).data('DealSearch',new DealSearch(this,options));});};var DealSearch=function(element,options)
{this.element=element;$.extend(this.settings,options);this.render();};DealSearch.prototype={element:null,settings:{page:1,rowsPerPage:15},render:function()
{var $this=$(this.element);var self=this;$this.html(View('/dmapi/views/deal-search/search.jhtml'));Model.Organization.getProviderOptionList(function(providerOptionList){$.each(providerOptionList,function(i,provider){$('select[name="provider_id"]',$this).append('<option value="'+provider.id+'">'+provider.name+'</option>');});});$('#deal-filter-btn, #user-search-btn',$this).click(function(ev){self.renderPage(self.settings.page);});$('#user-search-txt',$this).keyup(function(event){if(event.keyCode==13)
{$('#user-search-btn',$this).click();}});this.renderPage(this.settings.page);},renderPage:function(num)
{var $this=$(this.element);var self=this;var searchOptions={page:num,rows_per_page:self.settings.rowsPerPage,cbsa:$('select[name="cbsa"]',$this).val(),deal_status_id:$('select[name="deal_status_id"]',$this).val(),offer_status_id:$('select[name="offer_status_id"]',$this).val(),provider_id:$('select[name="provider_id"]',$this).val(),submitted_date_range:$('select[name="submitted_date_range"]',$this).val(),submitted_date_sort:$('select[name="submitted_date_sort"]',$this).val(),text_search:$('#user-search-txt',$this).val()};Model.Deal.search(searchOptions,function(search)
{$('.paginator',$this).Paginator(search,{renderPage:function(num){self.renderPage(num);}});self.getResultSetDiv().html('');var rows=search.getRows();$.each(rows,function(i,row){self.renderDealRow(new Model.Deal(row.deal));});},function(response)
{self.getResultSetDiv().html('An error occurred.');});},getResultSetDiv:function()
{return $('.result-set',$(this.element));},renderDealRow:function(deal)
{var li=$('<li class="not-approved"></li>');li.DealSearchRow(deal);this.getResultSetDiv().append(li);}};})(MLD.View,MLD.Model,jQuery);

(function(View,Model,$){$.fn.DealDash=function(options)
{return $(this).each(function()
{$(this).data('DealDash',new DealDash(this,options));});};var DealDash=function(element,options)
{this.element=element;$.extend(this.settings,options);this.render();};DealDash.prototype={element:null,settings:{page:1,rowsPerPage:5},render:function()
{var $this=$(this.element);$this.html(View('/dmapi/views/deal-dash/index.jhtml'));this.renderPage(this.settings.page);},renderPage:function(num)
{var $this=$(this.element);var self=this;Model.Deal.dashSearch({},function(search)
{self.getResultSetDiv().html('');var rows=search.getRows();$.each(rows,function(i,row){self.renderDealRow(new Model.Deal(row.deal));});},function(response)
{self.getResultSetDiv().html('An error occurred.');});Model.Offer.dashSearch({page:num,rowsPerPage:self.settings.rowsPerPage},function(search)
{$('.paginator',$this).Paginator(search,{renderPage:function(num){self.renderPage(num);},showPageInfo:false});if(num>1){self.getResultSetDiv().html('');}
var rows=search.getRows();$.each(rows,function(i,row){self.renderOfferRow(new Model.Offer(row.entity));});},function(response)
{self.getResultSetDiv().html('An error occurred.');});},getResultSetDiv:function()
{return $('.result-set',$(this.element));},renderDealRow:function(deal)
{var li=$('<li class="deal-row not-approved"></li>');li.DealDashPendingRow(deal);this.getResultSetDiv().append(li);},renderOfferRow:function(offer)
{var li=$('<li class="deal-row"></li>');li.DealDashRow(offer);this.getResultSetDiv().append(li);}};})(MLD.View,MLD.Model,jQuery);

(function(View,$){$.fn.DealDashRow=function(offer)
{return $(this).each(function()
{var widget=new DealDashRow(this,offer);widget.setupEndOffer();widget.setupDuplicateOffer();$(this).data('DealDashRow',widget);});};var DealDashRow=function(element,offer)
{this.element=element;this.offer=offer;this.render();};DealDashRow.prototype={element:null,offer:null,render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/deal-dash/row.jhtml',{offer:self.offer}));this.renderRevenue();},setupEndOffer:function()
{var self=this;var $this=$(this.element);var offer=this.offer;$('.end-now',$this).live('click',function(ev){ev.preventDefault();if(confirm('Are you sure you want to end this offer?')){offer.end(function(offer){self.offer=offer;self.render();},function(){alert('An error occurred with ending the offer.');});}});},setupDuplicateOffer:function()
{var self=this;var $this=$(this.element);var offer=this.offer;$('.duplicate',$this).live('click',function(ev){ev.preventDefault();if(confirm('Are you sure you want to duplicate this offer?')){var orgId=UserInfo.getOrganizationId();var dealId=offer.deal.getId();window.location.href='/getfeatured/submit/organization/'
+orgId+'/duplicate-deal-id/'+dealId;}});},renderRevenue:function()
{var self=this;var $this=$(this.element);self.offer.getRevenue(function(revenue){var dollars=String(Math.round(revenue*100)/100);if(dollars.length>2&&dollars.charAt(dollars.length-2)=="."){dollars=dollars+"0";}
$('.revenue',$this).html('$'+dollars);},function(){console.log('An error occurred getting offer revenue.');});}};})(MLD.View,jQuery);

(function(View,$){$.fn.DealDashPendingRow=function(deal)
{return $(this).each(function()
{var widget=new DealDashPendingRow(this,deal);widget.setupApproveDeal();widget.setupRejectDeal();$(this).data('DealDashPendingRow',widget);});};var DealDashPendingRow=function(element,deal)
{this.element=element;this.deal=deal;var self=this;this.deal.getOffers(function(offerList){self.render();},function(response){console.log('DealDashPendingRow error');});};DealDashPendingRow.prototype={element:null,deal:null,render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/deal-dash/pendingRow.jhtml',{deal:self.deal}));},setupApproveDeal:function()
{var self=this;var $this=$(this.element);var deal=this.deal;$('.approve-btn .approval',$this).live('click',function(ev){ev.preventDefault();if(confirm('Are you sure you want to approve this deal?')){deal.approve(function(deal){$('#dashboard-widget').data('DealDash').renderPage(1);},function(){alert('An error occurred with approving the deal.');});}});},setupRejectDeal:function()
{var self=this;var $this=$(this.element);var deal=this.deal;$('.approve-btn .rejection',$this).live('click',function(ev){ev.preventDefault();$('.reason',$this).removeClass('hide');$('.reject',$this).css({"cursor":"default","color":"#ccc","text-decoration":"none"});$('.reason textarea',$this).focus();});$('.reason .cancel',$this).live('click',function(ev){ev.preventDefault();$('.reason',$this).addClass('hide');$('.reject',$this).css({"cursor":"pointer","color":"#c33","text-decoration":"underline"});});$('.reason .submit-btn',$this).live('click',function(ev){ev.preventDefault();msg=jQuery.trim($('.reason textarea',$this).val());if(msg===""){alert("Please supply a reason");return;}
if(confirm('Are you sure you want to reject this deal?')){deal.setRejectionMsg(msg);deal.reject(function(deal){$('#dashboard-widget').data('DealDash').renderPage(1);},function(){alert('An error occurred with rejecting the deal.');});}});}};})(MLD.View,jQuery);

(function(View,$){$.fn.DealCutPieChart=function(options)
{return $(this).each(function()
{$(this).data('DealCutPieChart',new DealCutPieChart(this,options));});}
var DealCutPieChart=function(element,options){var self=this;$.extend(this.settings,options);this.element=$(element);this.render();}
DealCutPieChart.prototype={element:null,settings:{},render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/deal_cut_pie_chart.jhtml',{obj:self}));},getMerchantCut:function()
{return this.settings.merchantCut;},getPurchaserOwnerCut:function(isNotNetworked)
{return isNotNetworked?0:5;},getServiceProviderCut:function(isNetworked)
{return isNetworked?15:10;},getPublisherCut:function(isNetworked)
{return 100-this.getMerchantCut()-this.getPurchaserOwnerCut(!isNetworked)-this.getServiceProviderCut(isNetworked);}}})(MLD.View,jQuery);

(function(Validator,View,Model,$){$.fn.MerchantSignup=function(options)
{return $(this).each(function()
{$(this).data('MerchantSignup',new MerchantSignup(this,options));});}
var MerchantSignup=function(element,options){var self=this;$.extend(this.settings,options);this.element=$(element);this.render();}
MerchantSignup.prototype={element:null,settings:{success:function(merchant){alert('New merchant created as #'+merchant.getId());},cancel:function(){}},render:function()
{var self=this;$formDiv=$(this.element).show().html(View('/dmapi/views/merchant-selector/merchantAddForm.jhtml'));$('a.cancel-adding',$formDiv).click(function(){self.cancelMerchantAdd();});$(':input[name="submit-add"]',$formDiv).click(function(){self.submitMerchantForm();});Model.State.loadAll(function(states){var optionsString=View('/dmapi/views/select_options.jhtml',{items:states,valueCallbackName:'getAbbreviation',displayCallbackName:'getName'});$(':input[name="state"]',$formDiv).append(optionsString);});Model.Category.loadAll(function(categoryList){var optionsString=View('/dmapi/views/select_options.jhtml',{items:categoryList,valueCallbackName:'getCode',displayCallbackName:'getName'});$(':input[name="category"]',$formDiv).append(optionsString);});self.blankifyForm();$(':input[type="text"]',$formDiv).blur(function(){self.blankify($(this));});},cancelMerchantAdd:function()
{this.settings.cancel();},submitMerchantForm:function()
{var self=this;var $div=$('#new-merchant-details',$(this.element));$(':input.blank',$div).val('');if(!this.validateForm())
{$('p.error',$div).show().html('Some of the details you provided are invalid. Please check your information and try again.');self.blankifyForm();return;}
var merchant=new Model.Organization();var person=new Model.Person();var streetAddress=new Model.StreetAddress();person.setFirstName($(':input[name="first_name"]',$div).val()).setLastName($(':input[name="last_name"]',$div).val()).setEmail($(':input[name="email"]',$div).val());streetAddress.setStreet1($(':input[name="street1"]',$div).val()).setCity($(':input[name="city"]',$div).val()).setState($(':input[name="state"]',$div).val()).setZipCode($(':input[name="zip_code"]',$div).val());merchant.setName($(':input[name="name"]',$div).val()).setPhoneNumber($(':input[name="phone_number"]',$div).val()).setCategory($(':input[name="category"]',$div).val()).setType('business').setPerson(person).setPaymentAddress(streetAddress);merchant.save(function(merchant)
{self.settings.success(merchant);},function(response)
{$('p.error',$div).show().html('An error has occurred. Please check your information and try again.');self.blankifyForm();});},validateForm:function()
{var $this=$(this.element);$('ul.error-message-list, li.error-message').hide();var result=true;var $contactForm=$('fieldset.merchantContactInformation',$this);var contactForm=new Validator(null,function(errorCode)
{$('fieldset.merchantContactInformation ul.error-message-list',$this).show();});contactForm.validators.push(new Validator.Required($(':input[name="name"]',$contactForm),function(errorCode){$('.error-message.name',$contactForm).show();}));contactForm.validators.push(new Validator.Required($(':input[name="category"]',$contactForm),function(errorCode){$('.error-message.category',$contactForm).show();}));contactForm.validators.push(new Validator.Required($(':input[name="first_name"]',$contactForm),function(errorCode){$('.error-message.first_name',$contactForm).show();}));contactForm.validators.push(new Validator.Required($(':input[name="last_name"]',$contactForm),function(errorCode){$('.error-message.last_name',$contactForm).show();}));contactForm.validators.push(new Validator.PersonEmail($(':input[name="email"]',$contactForm),function(errorCode){switch(errorCode)
{case'emailExists':$('.error-message.email[errorCode="'+errorCode+'"]',$contactForm).show();break;default:$('.error-message.email:not([errorCode])',$contactForm).show();break;}}));contactForm.validators.push(new Validator.PhoneNumber($(':input[name="phone_number"]',$contactForm),function(errorCode){$('.error-message.phone_number',$contactForm).show();}));var addressForm=new Validator.StreetAddress($('fieldset.streetAddress',$this),function(errorCode)
{$('fieldset.streetAddress ul.error-message-list',$this).show();});result=contactForm.isValid()&&result;result=addressForm.isValid()&&result;return result;},unblankify:function(element)
{element.removeClass('blank').val('');element.unbind('focus');},blankify:function(element)
{var self=this;if(element.val()=='')
{element.addClass('blank').val(element.attr('label'));element.focus(function(){self.unblankify(element);});}},blankifyForm:function()
{var self=this;$(':input[type="text"]',$(this.element)).each(function(){self.blankify($(this));});}}})(MLD.Validator,MLD.View,MLD.Model,jQuery);

(function(View,Model,$){$.fn.MerchantSelector=function(arg1,options)
{if(typeof(arg1)=='string'&&isNaN(arg1))
{var returnValue=null;$(this).each(function()
{var widget=$(this).data('MerchantSelector');returnValue=widget[arg1].apply(widget,Array.prototype.slice.call(arguments,1));});return returnValue;}
else
{return $(this).each(function()
{var self=this;if(!isNaN(arg1)&&arg1>0)
{Model.Organization.load(arg1,function(merchant)
{$(self).data('MerchantSelector',new MerchantSelector(self,merchant,options));},function()
{});}
else
{$(this).data('MerchantSelector',new MerchantSelector(this,arg1,options));}});}}
var MerchantSelector=function(element,merchant,options){var self=this;$.extend(this.settings,options);this.element=$(element);this.renderSearch();this.setMerchant(merchant);}
MerchantSelector.prototype={element:null,merchant:null,settings:{rowsPerPage:5,updateSelection:function(merchant){}},renderSearch:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/merchant-selector/search.jhtml'));$(':input[name="merchant_name"]',$this).keyup(function(){self.searchMerchants(1);});$('a.add-merchant-details',$this).click(function(){self.displayAddMerchantForm();});},searchMerchants:function(pageNum)
{var self=this;var $this=$(this.element);var name=$(':input[name="merchant_name"]',$this).val();var $resultSet=$('div.search-results div.result-set',$this);Model.Organization.search({name:name,page:pageNum,rowsPerPage:self.settings.rowsPerPage},function(search)
{self.renderSearchResults(search);},function(response)
{$resultSet.html('Unable to find merchants.');});},renderSearchResults:function(search)
{var self=this;var $this=$(this.element);var $resultSet=$('div.search-results div.result-set',$this);var $paginator=$('div.search-results div.paginator',$this);$('div.search-results',$this).show();$resultSet.html('');if(search.getTotalCount()>0)
{var rows=search.getRows();for(i in rows)
{var merchant=new Model.Organization(rows[i].entity);var $div=this.createRow(merchant);$resultSet.append($div);$div.data('merchant',merchant);$div.click(function(){self.setMerchant($(this).data('merchant'));});}
if(search.getTotalCount()>self.settings.rowsPerPage)
{$paginator.Paginator(search,{renderPage:function(num){self.searchMerchants(num);}});}}
else
{$resultSet.html('No merchants matched your search.');}},setMerchant:function(merchant)
{var self=this;var $this=$(this.element);if(merchant)
{$('div.search',$this).hide();$('div.new-merchant-form',$this).hide();var $container=$('div.selected-merchant',$this).show();var $row=this.createRow(merchant);$container.html($row);$row.click(function(){self.setMerchant(null);});}
else
{$('div.search',$this).show();$('div.selected-merchant',$this).hide();}
this.merchant=merchant;this.settings.updateSelection(merchant);},createRow:function(merchant)
{var $div=$('<div> </div>').html(View('/dmapi/views/merchant-selector/row.jhtml',{merchant:merchant}));return $div;},getMerchantId:function()
{return this.merchant?this.merchant.getId():null;},displayAddMerchantForm:function()
{var self=this;var $this=$(this.element);$('div.search',$this).hide();$('div.selected-merchant',$this).hide();$('p#no-merchant',$this).hide();var $newDiv=$('<div> </div>').MerchantSignup({cancel:function(){self.cancelMerchantAdd();},success:function(merchant)
{self.setMerchant(merchant);}});$('div.new-merchant-form',$this).show().html($newDiv);},cancelMerchantAdd:function()
{var $this=$(this.element);$('div.search',$this).show();$('div.selected-merchant',$this).hide();$('p#no-merchant',$this).show();$('div.new-merchant-form',$this).html('').hide();}}})(MLD.View,MLD.Model,jQuery);

(function(View,Model,$){$.fn.OfferWidget=function(options)
{return $(this).each(function()
{$(this).data('OfferWidget',new OfferWidget(this,options));});};var OfferWidget=function(element,options){var self=this;this.element=$(element);this.setOptions(options);this.render(true);}
OfferWidget.prototype={element:null,offer:null,area:null,currentAreaId:null,settings:{titleColor:'3F475F',borderColor:'B4DEF0',offerTitleColor:'006699',textColor:'6C6D79',backgroundColor:'FFFFFF',dealTextColor:'6C6D79',dealBackgroundColor:'F2F3F5',areaId:null,scale:1,publisherName:null,isTest:0},setOptions:function(options)
{this.settings=$.extend({},this.settings,options);},render:function(updateArea)
{var self=this;if(updateArea&&(!this.offer||this.settings.areaId!=this.currentAreaId))
{this.currentAreaId=this.settings.areaId;Model.SearchOffer.loadOfferedByAreaId({areaId:this.settings.areaId},function(offerSearch)
{if(offerSearch.getTotalCount()>0)
{self.offer=offerSearch.getFirstOffer();if(self.offer){self.area=self.offer.getArea();self._render();}}
else
{self.offer=null;Model.Area.load(self.settings.areaId,function(area)
{self.area=area;self._render();},function(response)
{self.area=null;});}},function(response)
{self.offer=null;});}
else
{this._render();}},_render:function()
{var self=this;var $this=$(this.element);if(this.offer)
{var savings=this.offer.getValue()-this.offer.getCost();var discount=Math.ceil(savings/this.offer.getValue()*100);}
var script=this.getViewScript();$this.html(View(script,{settings:self.settings,offer:self.offer,area:self.area,savings:savings,discount:discount,scale:self.settings.scale}));this.updateTimeLeft();$('.clWidgetBuyButton, .clWidgetOfferTitle',$this).click(function(){var url='http://';url+=!self.settings.isTest?'www.citizenlocal.com':'test.citizenlocal.com';url+='/deal/'+self.offer.getUrlFragment();if(self.settings.publisherName)
{url+='/p/'+self.settings.publisherName;}
window.open(url);});$('.clWidgetNoDealButton',$this).click(function(){var url='http://';url+=!self.settings.isTest?'www.citizenlocal.com':'test.citizenlocal.com';url+=self.area.getUrl();if(self.settings.publisherName)
{url+='/p/'+self.settings.publisherName;}
window.open(url);});},updateTimeLeft:function()
{var self=this;var $this=$(this.element);$('.clWidgetTimeLeft',$this).html(self.getTimeLeftString());window.setTimeout(function(){self.updateTimeLeft();},500);},getTimeLeftString:function()
{if(!this.offer)
{return;}
var date=new Date();var diff=Math.floor((Date.parseMysqlTimestamp(this.offer.getEnd())-date.getTime())/1000);if(diff<=0)
{return'00:00:00';}
var string='';var days=Math.floor(diff/86400);var hours=Math.floor(diff%86400/3600);var minutes=Math.floor(diff%3600/60);var seconds=Math.floor(diff%60);string+=((hours>=10)?hours:String(0)+hours)+':'+
((minutes>=10)?minutes:String(0)+minutes);if(days>0)
{string=days+'d '+string;}
else
{string+=':'+((seconds>=10)?seconds:String(0)+seconds);}
return string;},renderNoDeals:function()
{var $this=$(this.element);$this.html('<img src="http://www.citizenlocal.com/i/cl_nodeal_widget.jpg" />');},getViewScript:function()
{var theme=this.getTheme('main');var script;script=this.offer?theme.deal:theme.nodeal;return script;},getTheme:function(theme)
{var obj;switch(theme)
{default:obj={deal:'/dmapi/views/offer-widget/main.jhtml',nodeal:'/dmapi/views/offer-widget/main-no-deal.jhtml'}}
return obj;}}
MLD.Widget=function(options)
{var id='MLDWidget-'+Date.UTC()+'-'+Math.floor(Math.random()*10001);document.write('<div id="'+id+'"> </div>');$('#'+id).OfferWidget(options);}})(MLD.View,MLD.Model,jQuery);

(function(Model,$){$.fn.OfferWidgetMaker=function(options)
{return $(this).each(function()
{$(this).data('OfferWidgetMaker',new OfferWidgetMaker(this,options));});};var OfferWidgetMaker=function(element,options){var self=this;this.element=$(element);this.settings=$.extend({},this.defaultSettings,options);this.scriptPath=options.scriptPath;this.init();}
OfferWidgetMaker.prototype={element:null,currentZipCode:null,offerWidget:null,settings:null,defaultSettings:{titleColor:'3F475F',borderColor:'B4DEF0',textColor:'6C6D79',offerTitleColor:'006699',backgroundColor:'FFFFFF',areaId:null,scale:1,publisherName:null,isTest:0},init:function()
{var self=this;var $this=$(this.element);Model.Area.load($(':input[name="areaId"]').val(),function(area)
{self.updateArea(area);},function(response)
{self.updateArea(null);});var $zipInput=$(':input[name="zipCode"]',$this);$zipInput.keyup(function(){var zipValue=$(this).val();if(zipValue.length==5&&zipValue!=self.currentZipCode)
{self.setZipCode(zipValue);}});$.each(this.settings,function(name,value){$(':input[name="'+name+'"]',$this).val(value);});$(':input[name$="Color"]',$this).each(function(){self.addColorPicker($(this).attr('name'));}).keyup(function(){$(this).ColorPickerSetColor($(this).val());self.update(false);});;},addColorPicker:function(name)
{var $this=$(this.element);var self=this;$(':input[name="'+name+'"]',$this).ColorPicker({onBeforeShow:function()
{$(this).ColorPickerSetColor($(this).val());},onChange:function(hsb,hex,rgb,el)
{$(':input[name="'+name+'"]',$this).val(hex);self.update(false);}});},setZipCode:function(zipValue)
{var self=this;var $this=$(this.element);self.currentZipCode=zipValue;Model.Area.getOneByZipCode(zipValue,function(area)
{self.updateArea(area);},function(response)
{self.updateArea(null);});},updateArea:function(area)
{var areaId;var areaName;if(area)
{areaId=area.getId();areaName=area.getName();}
else
{areaId=null;areaName='Area not found.';}
var $this=$(this.element);$(':input[name="areaId"]',$this).val(areaId);$('#areaTitle',$this).html(areaName);this.update(true);},update:function(updateArea)
{var options=this.getWidgetOptions();this.renderExampleWidget(options,updateArea);this.renderSnippet();},renderExampleWidget:function(widgetOptions,updateArea)
{var $this=$(this.element);if(!this.offerWidget)
{var newDiv=$('<div> </div>');newDiv.OfferWidget(widgetOptions);this.offerWidget=newDiv.data('OfferWidget');$('#exampleWidget',$this).html(newDiv);}
else
{this.offerWidget.setOptions(widgetOptions);this.offerWidget.render(updateArea);}},renderSnippet:function()
{var $this=$(this.element);var optionsString=this.getSerializedWidgetOptions();var snippet='<script type="text/javascript" src="'
+this.scriptPath
+'"> </script><script type="text/javascript">MLD.Widget('
+optionsString
+');</script>';$('#widgetSnippet').text(snippet);},getWidgetOptions:function()
{var $this=$(this.element);var options={};$.each(this.defaultSettings,function(name,defaultValue){inputValue=$(':input[name="'+name+'"]',$this).val();if(inputValue&&defaultValue!=inputValue)
{options[name]=inputValue;}});return options;},getSerializedWidgetOptions:function()
{var options=this.getWidgetOptions();var optionsArray=new Array();$.each(options,function(name,value){optionsArray.push(name+':\''+value+'\'');});var optionsString='{'+optionsArray.join(',')+'}';return optionsString;}}})(MLD.Model,jQuery);

(function(View,Model,$){$.fn.OrgEditorLogo=function(org,options)
{return this.each(function()
{var widget=new OrgEditorLogo(this,org,options);$(this).data('OrgEditorLogo',widget);});};var OrgEditorLogo=function(element,id,options){this.element=element;$.extend(this.settings,options);var self=this;Model.Organization.load(id,function(org){self.orgLoadSuccess(org);},function(response){self.displayError("Organization load problem");});};OrgEditorLogo.prototype={element:null,org:null,orgImage:null,settings:{uploadProcessing:function(){},uploadSuccess:function(){}},render:function()
{var self=this;var $this=$(this.element);$this.append(View('/dmapi/views/org-editor/logo.jhtml'));$('#choose-logo',$this).click(function(ev){ev.preventDefault();self.displayBrowse();});var imgSrc=this.org.getImageThumbnailUrl();if(imgSrc){$('img.organization-logo',$this).attr('src',this.org.getImageThumbnailUrl());this.displayImage();}
$('#organization-img',$this).live('change',function(){self.upload();});},orgLoadSuccess:function(org)
{this.org=org;this.render();},displayBrowse:function()
{var $this=$(this.element);$('.error',$this).hide();$('.processing',$this).hide();$('.change',$this).hide();$('.file_input',$this).show();},displayProcessing:function()
{var $this=$(this.element);$('.processing',$this).show();},displayImage:function()
{var $this=$(this.element);$('.error',$this).hide();$('.processing',$this).hide();$('.file_input',$this).hide();$('.image',$this).show();$('.change',$this).show();},displayError:function(message)
{var $this=$(this.element);$('.processing',$this).hide();$('.error',$this).html(message).show();},upload:function()
{this.displayProcessing();this.settings.uploadProcessing();var uploadSuccess=this.settings.uploadSuccess;var self=this;var $this=$(this.element);if(!this.validateImageFile()){return;}
$.ajaxFileUpload({url:'/ajax/organization-image/upload',secureuri:false,fileElementId:'organization-img',dataType:'json',success:function(data,status)
{if(!data.success||!data.organization_image){this.error(data,status);return;}
var orgImage=new Model.OrganizationImage(data.organization_image);self.org.setOrganizationImage(orgImage);self.setOrgImage(orgImage);var imageUrl=orgImage.getThumbnailUrl();$('img.organization-logo',$this).attr('src',imageUrl);self.updateFormInputs();self.displayImage();uploadSuccess();},error:function(data,status,e)
{var message;switch(data.error)
{case'invalidFormat':message='The image format was not recognized.';break;default:message='There was an error with the image upload.';break;}
self.displayError(message);}});},setOrgImage:function(img)
{this.orgImage=img;},getOrgImage:function()
{return this.orgImage;},validateImageFile:function()
{var $this=$(this.element);var fileExtension=$('#organization-img',$this).val().split('.').pop();if($.inArray(fileExtension.toLowerCase(),['gif','png','jpg','jpeg'])===-1)
{var message='The image format was not recognized.';this.displayError(message);return false;}
return true;},updateFormInputs:function()
{var $this=$(this.element);var img=this.getOrgImage();$(':input[name="image_id"]',$this).val(img.getId());}};})(MLD.View,MLD.Model,jQuery);

(function(View,Model,$){$.fn.OfferSuggestedList=function(options)
{return $(this).each(function()
{$(this).data('OfferSuggestedList',new OfferSuggestedList(this,options));});};var OfferSuggestedList=function(element,options){this.element=element;this.settings=$.extend({},this.defaultSettings,options);this.render();};OfferSuggestedList.prototype={element:null,search:null,defaultSettings:{areaId:0,anonymousVoteClick:function(suggestedOfferWidget){},processResult:function(areOffers){},page:1,rowsPerPage:3},render:function()
{var $this=$(this.element);$this.html(View('/dmapi/views/offer-suggested-list/search.jhtml'));this.renderPage(this.settings.page);},renderPage:function(num)
{var $this=$(this.element);var self=this;Model.SearchAreaOfferVoting.loadOffersInVotingByAreaId({areaId:self.settings.areaId,personId:MLD.UserInfo.getPersonId(),page:num,rowsPerPage:self.settings.rowsPerPage,reservedSlot:3},function(search)
{self.search=search;$('.sb-deal-nav',$this).OfferSuggestedPaginator(search,{renderPage:function(num){self.renderPage(num);}});self.getResultSetDiv().html('');var rows=search.getRows();$.each(rows,function(i,row){if(i!=2||num!=1)
{var $div=$('<div></div>');$div.OfferSuggestedNode({row:row,anonymousVoteClick:self.settings.anonymousVoteClick});self.getResultSetDiv().append($div);}});if(num==1)
{var url=MLD.UserInfo.isLoggedIn()?'/getfeatured/signup':'/getfeatured';self.getResultSetDiv().append(View('/dmapi/views/offer-suggested-list/get-featured-link.jhtml',{url:url}));}
self.settings.processResult(search.getTotalCount()>0);},function(response)
{});},getResultSetDiv:function()
{return $('.result-set',$(this.element));}};})(MLD.View,MLD.Model,jQuery);

(function(UserInfo,Model,View,$){$.fn.OfferSuggestedNode=function(options)
{return $(this).each(function()
{$(this).data('OfferSuggestedNode',new OfferSuggestedNode(this,options));});};var OfferSuggestedNode=function(element,options){this.element=element;this.row=options.row;delete options.row;this.settings=$.extend({},this.defaultSettings,options);this.render();};OfferSuggestedNode.prototype={element:null,row:null,settings:null,defaultSettings:{anonymousVoteClick:function(suggestedOfferWidget){alert('Unable to vote. Please log in.');},voteSuccess:function(suggestedOfferWidget){alert('You have cast your vote successfully.');}},render:function()
{var $this=$(this.element);var row=this.row;var hasVoted=row.hasVoted();$this.html(View('/dmapi/views/offer-suggested-list/node.jhtml',{offer:row.getOffer(),voteCount:row.getOffer().getVoteCount(),hasVoted:row.hasVoted()}));var self=this;$('.vote',$this).click(function(){if(UserInfo.isLoggedIn()){self.vote();}
else{self.settings.anonymousVoteClick(this);}});$("h4 a[rel]",$this).overlay({fixed:false,mask:{color:'#999',opacity:0.5},onBeforeLoad:function(ev){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html('<div class="popup"><img src="/i/loading.gif" /></div>');var el=ev.originalTarget||ev.srcElement;var index=$('.suggested-area .titleLink').index(el);wrap.data('suggestedIndex',index);wrap.load(this.getTrigger().attr("href"),function(){});}});},vote:function()
{var $this=$(this.element);this.row.getOffer().vote(UserInfo.getPersonId(),function()
{var currentVoteInt=parseInt($('.vote-count strong',$this).html())+1;var voteText="Votes";if(parseInt(currentVoteInt)==1||parseInt(currentVoteInt)==0){voteText="Vote";}
var thanksMsg='<div class="votedText"><strong>Thanks</strong> why not promote this deal?<span class="arrow"></span></div>';var votedImage='<div class="imgVoted">&nbsp;</div>';var voteMsg="<strong>"+currentVoteInt+"</strong> "+voteText;$('.offerText',$this).hide().after($(thanksMsg));$('.imgVote',$this).hide().after($(votedImage));$('.vote-count',$this).html(voteMsg);},function(response)
{});}};})(MLD.UserInfo,MLD.Model,MLD.View,jQuery);

(function(View,$){$.fn.OfferSuggestedPaginator=function(search,options)
{return $(this).each(function()
{$(this).data('OfferSuggestedPaginator',new OfferSuggestedPaginator(this,search,options));});};var OfferSuggestedPaginator=function(element,search,options)
{this.element=element;$.extend(this.settings,options);this.search=search;this.render();};OfferSuggestedPaginator.prototype={element:null,search:null,settings:{renderPage:function(num){},showPageInfo:false},render:function()
{var $this=$(this.element);var search=this.search;var settings=this.settings;$this.html(View('/dmapi/views/offer-suggested-list/offer-suggested-paginator.jhtml',{search:search,settings:settings}));$('.previous_page',$this).click(function(ev){ev.preventDefault();settings.renderPage(search.getPage()-1);});$('.next_page',$this).click(function(ev){ev.preventDefault();settings.renderPage(search.getPage()+1);});$('.first_page',$this).click(function(ev){ev.preventDefault();settings.renderPage(1);});$('.last_page',$this).click(function(ev){ev.preventDefault();settings.renderPage(search.getLastPage());});$('.page',$this).click(function(ev){ev.preventDefault();settings.renderPage($('a',this).attr('rel'));});}};})(MLD.View,jQuery);

(function(View,Model,$){$.fn.PurchaseSearch=function(options)
{return $(this).each(function()
{$(this).data('PurchaseSearch',new PurchaseSearch(this,options));});}
var PurchaseSearch=function(element,options)
{this.element=element;$.extend(this.settings,options);this.render();}
PurchaseSearch.prototype={element:null,settings:{page:1,rowsPerPage:100},render:function()
{var $this=$(this.element);$this.html(View('/dmapi/views/purchase-search/search.jhtml'));this.renderPage(this.settings.page);},renderPage:function(num)
{var $this=$(this.element);var self=this;Model.Purchase.search({page:num,rowsPerPage:self.settings.rowsPerPage,offer_id:self.settings.offer_id},function(search)
{$('.paginator',$this).Paginator(search,{renderPage:function(num){self.renderPage(num);}});self.getResultSetDiv().html('');var rows=search.getRows();$.each(rows,function(i,row){self.renderPurchaseRow(new Model.Purchase(row.entity),self.settings.area_name);});},function(response)
{self.getResultSetDiv().html('An error occurred.');});},getResultSetDiv:function()
{return $('.result-set',$(this.element));},renderPurchaseRow:function(purchase,areaName)
{var tr=$('<tr class="user-purchase first"></tr>');tr.PurchaseSearchRow(purchase,areaName);this.getResultSetDiv().append(tr);}}})(MLD.View,MLD.Model,jQuery);

(function(View,$){$.fn.PurchaseSearchRow=function(purchase,areaName)
{return $(this).each(function()
{var widget=new PurchaseSearchRow(this,purchase,areaName);widget.setupVoucherList();widget.setupRefundBtn();$(this).data('PurchaseSearchRow',widget);});};var PurchaseSearchRow=function(element,purchase,areaName)
{this.element=element;this.purchase=purchase;this.areaName=areaName;var self=this;self.render();};PurchaseSearchRow.prototype={element:null,purchase:null,areaName:null,render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/purchase-search/row.jhtml',{purchase:self.purchase,areaName:self.areaName}));},setupVoucherList:function()
{var self=this;var $this=$(this.element);var purchase=this.purchase;$('.show-v-list',$this).live('click',function(ev){ev.preventDefault();purchase.getVouchers(function(voucherList){self.renderVoucherList(voucherList);},function(response){console.log('PurchaseSearchRow getVouchers error');});});},setupRefundBtn:function()
{var self=this;var $this=$(this.element);var purchase=this.purchase;$('.refund',$this).live('click',function(ev){ev.preventDefault();if(confirm('Are you sure want to refund this purchase?')){self.purchase.refund(function(purchase)
{self.purchase=purchase;self.render();alert('The purchase has been successfully refunded.');},function()
{alert('An error occurred.');});}});},renderVoucherList:function(voucherList)
{var $this=$(this.element);var tr=$('<tr class="voucher-list"></tr>');tr.PurchaseVoucherRow(voucherList);$this.after(tr);}};})(MLD.View,jQuery);

(function(View,$){$.fn.PurchaseVoucherRow=function(voucherList)
{return $(this).each(function()
{var widget=new PurchaseVoucherRow(this,voucherList);$(this).data('PurchaseVoucherRow',widget);});}
var PurchaseVoucherRow=function(element,voucherList)
{this.element=element;this.voucherList=voucherList;var self=this;self.render();}
PurchaseVoucherRow.prototype={element:null,render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/purchase-search/voucher-row.jhtml',{voucherList:self.voucherList}));}};})(MLD.View,jQuery);

(function(UserInfo,View,Model,$){$.fn.CommentWidget=function(offerId,options)
{return $(this).each(function()
{var widget=new CommentWidget(this,offerId,options);widget.setupClicks();widget.setupForm();$(this).data('CommentWidget',widget);});};var CommentWidget=function(element,offerId,options)
{this.element=element;this.offerId=offerId;this.isAdmin=(UserInfo.getRole()=='superuser');$.extend(this.settings,options);this.render();};CommentWidget.prototype={element:null,offerId:null,isAdmin:null,settings:{},render:function()
{var $this=$(this.element);var self=this;$this.html(View('/dmapi/views/comment-widget/main.jhtml'));Model.Comment.search({offer_id:this.offerId},function(search)
{self.getResultSetDiv().html('');var rows=search.data;$.each(rows,function(i,row){self.renderCommentRow(new Model.Comment(row));});$('blockquote:first',$this).addClass('first').removeClass('hide');var expandLinkMsg=null;if(rows.length>0){expandLinkMsg='Join the discussion';}
else{expandLinkMsg='Be the first to comment on this deal';}
$('.leave-comments',$this).html(expandLinkMsg);},function(response)
{self.getResultSetDiv().html('An error occurred.');});},renderAfterAdd:function()
{var $this=$(this.element);var self=this;$this.html(View('/dmapi/views/comment-widget/main.jhtml'));Model.Comment.search({offer_id:this.offerId},function(search)
{self.getResultSetDiv().html('');var rows=search.data;$.each(rows,function(i,row){self.renderCommentRow(new Model.Comment(row));});$('blockquote:first',$this).addClass('first').removeClass('hide');var expandLinkMsg='Thank you for your comment';$('.leave-comments',$this).html(expandLinkMsg);},function(response)
{self.getResultSetDiv().html('An error occurred.');});},setupClicks:function()
{var self=this;var $this=$(this.element);$('.view-comments',$this).live('click',function(ev){ev.preventDefault();$('.view-comments',$this).addClass('hide');$('blockquote',$this).removeClass('hide');$('.hide-comments',$this).removeClass('hide');});$('.leave-comments',$this).live('click',function(ev){ev.preventDefault();$('.leave-comments',$this).addClass('hide');$('.add-comments',$this).removeClass('hide');$('blockquote',$this).removeClass('hide');$('.hide-comments',$this).removeClass('hide');});$('.cancel-comment a',$this).live('click',function(ev){ev.preventDefault();$('.add-comments',$this).addClass('hide');$('.leave-comments',$this).removeClass('hide');});},setupForm:function()
{var self=this;var $this=$(this.element);$('.comment-form',$this).submit(function(ev){ev.preventDefault();if(!UserInfo.isLoggedIn()){$('.signin .login-btn').click();}
var msg=$('.comment-form textarea',$this).val();if(msg!==''){var newComment=new Model.Comment();newComment.add(self.offerId,msg,function(comment){self.renderAfterAdd();},function(){console.log('CommentWidget: setupForm: Comment.save error');});}});},getResultSetDiv:function()
{return $('.comment-result-set',$(this.element));},renderCommentRow:function(comment)
{var bq=$('<blockquote class="group hide"></blockquote>');bq.CommentWidgetRow(comment,this.isAdmin);this.getResultSetDiv().append(bq);}};})(MLD.UserInfo,MLD.View,MLD.Model,jQuery);

(function(View,$){$.fn.CommentWidgetRow=function(comment,isAdmin)
{return $(this).each(function()
{var row=new CommentWidgetRow(this,comment,isAdmin);row.setupFlagging();$(this).data('CommentWidgetRow',row);});};var CommentWidgetRow=function(element,comment,isAdmin)
{this.element=element;this.comment=comment;this.isAdmin=isAdmin;this.render();};CommentWidgetRow.prototype={element:null,comment:null,render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/comment-widget/row.jhtml',{comment:self.comment,isAdmin:self.isAdmin}));},setupFlagging:function()
{var self=this;var $this=$(this.element);$('.flag-link',$this).live('click',function(ev){ev.preventDefault();if(confirm('Are you sure you want to hide this comment?')){self.comment.flag(function(comment){$this.fadeOut();},function(){console.log('CommentWidgetRow: setupFlagging: Comment.flag error');});}});}};})(MLD.View,jQuery);

(function(View,Model,$){$.fn.OfferList=function(options)
{return $(this).each(function()
{$(this).data('OfferList',new OfferList(this,options));});};var OfferList=function(element,options){this.element=element;this.settings=$.extend({},this.defaultSettings,options);this.render();};OfferList.prototype={element:null,search:null,currentInd:0,botDisplayInd:0,scrolling:false,defaultSettings:{areaId:0,page:1,rowsPerPage:10,featuredOffer:null},render:function()
{var $this=$(this.element);$this.html(View('/dmapi/views/offer-list/search.jhtml'));this.renderPage(this.settings.page);},renderPage:function(num)
{var $this=$(this.element);var self=this;$('.nav-items',$this).html('');Model.Offer.getAllByArea({areaId:self.settings.areaId,page:num,rowsPerPage:self.settings.rowsPerPage,reserveSlot:self.settings.featuredOffer!=null?1:0},function(search)
{self.search=search;self.getResultSetDiv().html('');var rows=search.getRows();if(self.settings.featuredOffer!=null)
{self.renderOfferNode(self.settings.featuredOffer);}
$.each(rows,function(i,row){var offer=new Model.Offer(row.entity);if(self.settings.featuredOffer==null||offer.getId()!=self.settings.featuredOffer.getId())
{self.renderOfferNode(offer);}});self.currentInd=0;self.setupTopNav();self.renderTopNav();self.setupBotNav();self.renderBotNav();self.setupOverlays();},function(response)
{});},renderOfferNode:function(offer)
{var $this=$(this.element);var $el=$('<li class="offr-deals"></li>');$el.OfferNode(offer);this.getResultSetDiv().append($el);$('.nav-items',$this).append(View('/dmapi/views/offer-list/bot-nav.jhtml',{offer:offer}));},setupOverlays:function()
{var $this=$(this.element);$('.share-earn a[rel]',$this).overlay({mask:{color:'#999',opacity:0.5},onBeforeLoad:function(ev){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html('<div class="popup"><img src="/i/loading.gif" /></div>');wrap.load(this.getTrigger().attr("href"),function(){});}});$("a.gift[rel]").overlay({mask:{color:'#999',opacity:0.5},fixed:false,onBeforeLoad:function(ev){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html('<div class="popup"><img src="/i/loading.gif" /></div>');wrap.load(this.getTrigger().attr("href"),function(){$('#gift-txt').show();dMInitGiftOverlay();});}});},setupTopNav:function()
{var $this=$(this.element);var self=this;$('#curr-deals .next',$this).live('click',(function(ev){ev.preventDefault();if(self.scrolling){return;}
if(self.currentInd<(self.getDisplayCount()-1)){self.scrollNext();self.currentInd++;}}));$('#curr-deals .prev',$this).live('click',(function(ev){ev.preventDefault();if(self.scrolling){return;}
if(self.currentInd>0){self.scrollPrev();self.currentInd--;}}));},renderTopNav:function()
{var $this=$(this.element);var self=this;$('.top-nav',$this).html(View('/dmapi/views/offer-list/top-nav.jhtml',{currentInd:this.currentInd,total:self.getDisplayCount()}));},setupBotNav:function()
{var $this=$(this.element);var self=this;$('.bot-nav-btn .next',$this).live('click',(function(ev){ev.preventDefault();if(self.scrolling){return;}
if(self.currentInd<(self.getDisplayCount()-1)){self.scrollNext();self.currentInd++;}}));$('.bot-nav-btn .prev',$this).live('click',(function(ev){ev.preventDefault();if(self.scrolling){return;}
if(self.currentInd>0){self.scrollPrev();self.currentInd--;}}));$('.nav-items a',$this).live('click',(function(ev){ev.preventDefault();if(self.scrolling){return;}
var targetInd=$(this).index();var diff=targetInd-self.currentInd;self.currentInd=targetInd;self.scrolling=true;var scrollFinished=function(){self.scrolling=false;self.renderTopNav();self.renderBotNav();};$('#offer-scroll-list .offr-deals',$this).animate({left:'-='+(diff*718)},{complete:scrollFinished});self.renderTopNav();self.renderBotNav();}));},renderBotNav:function()
{var $this=$(this.element);var self=this;if(this.search.getTotalCount()>1){$('.nav-items a',$this).removeClass('active');$('.nav-items a',$this).eq(this.currentInd).addClass('active');}
else{$('.c-nav',$this).hide();$('.bot-nav-btn',$this).hide();}},scrollNext:function()
{var $this=$(this.element);var self=this;this.scrolling=true;var scrollFinished=function(){self.scrolling=false;self.renderTopNav();self.renderBotNav();};if((this.currentInd-this.botDisplayInd)>1){this.botDisplayInd++;$('.nav-items',$this).animate({left:'-=220'});}
$('#offer-scroll-list .offr-deals',$this).animate({left:'-=718'},{complete:scrollFinished});},scrollPrev:function()
{var $this=$(this.element);var self=this;this.scrolling=true;var scrollFinished=function(){self.scrolling=false;self.renderTopNav();self.renderBotNav();};if((this.currentInd-this.botDisplayInd)<1){this.botDisplayInd--;$('.nav-items',$this).animate({left:'+=220'});}
$('#offer-scroll-list .offr-deals',$this).animate({left:'+=718'},{complete:scrollFinished});},getDisplayCount:function()
{var displayCount=this.search.getTotalCount();if(displayCount>this.search.getRowsPerPage()){displayCount=this.search.getRowsPerPage();}
return displayCount;},getResultSetDiv:function()
{return $('.result-set',$(this.element));}};})(MLD.View,MLD.Model,jQuery);

(function(UserInfo,Model,View,$){$.fn.OfferNode=function(offer)
{return $(this).each(function()
{$(this).data('OfferNode',new OfferNode(this,offer));});};var OfferNode=function(element,offer){this.element=element;this.offer=offer;this.render();};OfferNode.prototype={element:null,offer:null,render:function()
{var $this=$(this.element);var self=this;$this.html(View('/dmapi/views/offer-list/node.jhtml',{offer:self.offer}));var countdownFormat='HMS';var countdownLayout='<ul class="fTimer">{h<}{m<}{s<}<li>{hn}</li><li>{mn}</li><li>{sn}{s>}</li>{m>}{h>}</ul><ul class="fTimer"><li class="textTimer">Hrs</li><li class="textTimer">Min</li><li class="textTimer">Sec</li></ul>';var countdownStart=new Date.parse(this.offer.getEnd()+" utc");var countdownMinus1Day=countdownStart.clone().add(-1).days();if(countdownMinus1Day.isAfter(new Date())){countdownFormat='DHM';countdownLayout='<ul class="fTimer">{d<}{h<}{m<}<li>{dn}</li><li>{hn}</li><li>{mn}</li>{m>}{h>}{d>}</ul><ul class="fTimer"><li class="textTimer">Day</li><li class="textTimer">Hrs</li><li class="textTimer">Min</li></ul>';}
$('.timeLeft div#formatTimer',$this).countdown({until:countdownStart,compact:false,format:countdownFormat,layout:countdownLayout});this.offer.getOrganizationLocations(function(locationList)
{var title=(locationList.length>1)?'Locations':'Location';$('.deal-locations',$this).append('<h3>'+title+'</h3>');$.each(locationList,function(i,location){self.addLocation(location);});},function(response)
{console.log('OfferNode: render: error loading locations');});},addLocation:function(loc)
{var $this=$(this.element);var locHtml=View('/dmapi/views/offer-list/location.jhtml',{loc:loc});$('.deal-locations',$this).append(locHtml);}};})(MLD.UserInfo,MLD.Model,MLD.View,jQuery);

(function(View,Model,$){$.fn.Alerts=function(options)
{return $(this).each(function()
{var widget=new Alerts(this,options);$(this).data('Alerts',widget);});};var Alerts=function(element,options){var self=this;this.element=$(element);this.setOptions(options);self.refresh();};Alerts.prototype={element:null,area:null,alerts:[],suggested:[],settings:{},setOptions:function(options)
{this.settings=$.extend({},this.settings,options);},refresh:function()
{var self=this;self.render();Model.Area.alerts(self.settings.email,function(areas)
{self.alerts=areas;self.renderAlerts(areas);self.setupSuggested();},function(response)
{self.renderAlerts([]);self.setupSuggested();});},render:function()
{var self=this;var $this=$(this.element);$this.html(View('/dmapi/views/alerts/main.jhtml',{email:self.settings.email}));this.setupValidation();},renderAlerts:function(areas)
{var self=this;var $this=$(this.element);if(areas.length){$('#my-deal-alerts-section',$this).html(View('/dmapi/views/alerts/alerts.jhtml',{areas:areas}));$("#my-deal-alerts").submit(function(ev){ev.preventDefault();var $unsubscribed=$('#my-deal-alerts input[type="checkbox"]:not(:checked)');if($unsubscribed.length==0){return;}
var unsubscribeAreas=[];$unsubscribed.each(function(ind){var unsubId=$(this).val();$.each(self.alerts,function(i,obj){if(obj.getId()==unsubId){unsubscribeAreas.push(obj);}});});self.displayUnsubscribed(unsubscribeAreas);});$("#my-deal-alerts .unsub-all").click(function(ev){ev.preventDefault();var unsubscribeAreas=self.alerts;self.displayUnsubscribed(unsubscribeAreas);});}
else{$('#my-deal-alerts-section',$this).html('');}},renderSuggested:function(areas)
{var self=this;var $this=$(this.element);var nearbyAreas=areas;if(nearbyAreas.length){$('#available-deal-alerts-section',$this).html(View('/dmapi/views/alerts/suggested.jhtml',{areas:nearbyAreas}));$("#available-deal-alerts").submit(function(ev){ev.preventDefault();var $subscribeTo=$('#available-deal-alerts input[type="checkbox"]:checked');if($subscribeTo.length==0){return;}
var subscribeAreas=[];$subscribeTo.each(function(ind){var subId=$(this).val();$.each(self.suggested,function(i,obj){if(obj.getId()==subId){subscribeAreas.push(obj);}});});self.displaySubscribedLocal(subscribeAreas);});}
else{$('#available-deal-alerts-section',$this).html('');}},setupSuggested:function()
{var $this=$(this.element);var self=this;Model.Area.suggestions(self.settings.email,function(areas)
{self.suggested=areas;self.renderSuggested(self.suggested);},function(response)
{self.renderSuggested([]);});},setupValidation:function()
{var self=this;var $this=$(this.element);$("#opt-in-form").validate({rules:{},messages:{},preventDefaultSubmit:true,submitHandler:function(form){var email=self.settings.email;var areaId=$('#opt-in-form :input[name="area_select"]').val();Model.Area.subscribeByCode(email,areaId,function(response){var alert=response['areasubscriber'];var alertAreaNames=[];alertAreaNames.push(alert.area_name);$.each(self.alerts,function(i,obj){alertAreaNames.push(obj.getName());});self.displaySubscribed(alertAreaNames);},function(jqxhr,textStatus,errorThrown){alert(errorThrown);});}});},displaySubscribed:function(alertAreaNames)
{var $this=$(this.element);var self=this;$("#alerts-overlay").data("overlay",null).overlay({mask:{color:'#999',opacity:0.5},load:true,onBeforeLoad:function(){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html(View('/dmapi/views/alerts/subscribed.jhtml',{areas:alertAreaNames}));},onLoad:function(){$("#alerts-overlay input").click(function(ev){ev.preventDefault();$("#alerts-overlay").data("overlay").close();});},onClose:function(){self.refresh();}});},displaySubscribedLocal:function(subscribeAreas)
{var $this=$(this.element);var self=this;$("#alerts-overlay").data("overlay",null).overlay({mask:{color:'#999',opacity:0.5},load:true,onBeforeLoad:function(){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html(View('/dmapi/views/alerts/subscribedLocal.jhtml',{areas:subscribeAreas}));},onLoad:function(){$("#alerts-overlay .call-to-action .btn-ok").click(function(ev){ev.preventDefault();self.subscribeTo(subscribeAreas);});$("#alerts-overlay .call-to-action a").click(function(ev){ev.preventDefault();$("#alerts-overlay").data("overlay").close();});},onClose:function(){self.refresh();}});},displayUnsubscribed:function(unsubscribeAreas)
{var $this=$(this.element);var self=this;$("#alerts-overlay").data("overlay",null).overlay({mask:{color:'#999',opacity:0.5},load:true,onBeforeLoad:function(){this.getOverlay().appendTo('body');var wrap=this.getOverlay().find(".contentWrap");wrap.html(View('/dmapi/views/alerts/unsubscribed.jhtml',{areas:unsubscribeAreas}));},onLoad:function(){$("#alerts-overlay .call-to-action .btn-ok").click(function(ev){ev.preventDefault();self.unsubscribeFrom(unsubscribeAreas);});$("#alerts-overlay .call-to-action a").click(function(ev){ev.preventDefault();$("#alerts-overlay").data("overlay").close();});},onClose:function(){self.refresh();}});},unsubscribeFrom:function(unsubscribeAreas)
{var self=this;var unsubFuncs=[];$.each(unsubscribeAreas,function(i,obj){unsubFuncs.push(function(){return Model.Area.unsubscribe(self.settings.email,unsubscribeAreas[i].getId(),function(){},function(){});}());});$.when.apply($,unsubFuncs).then(function(){$("#alerts-overlay").data("overlay").close();}).fail(function(){$("#alerts-overlay").data("overlay").close();alert("There was an error when unsubscribing");});},subscribeTo:function(subscribeAreas)
{var self=this;var subFuncs=[];$.each(subscribeAreas,function(i,obj){subFuncs.push(function(){return Model.Area.subscribe(self.settings.email,subscribeAreas[i].getId(),function(){},function(){});}());});$.when.apply($,subFuncs).then(function(){$("#alerts-overlay").data("overlay").close();}).fail(function(){$("#alerts-overlay").data("overlay").close();alert("There was an error when subscribing");});}};})(MLD.View,MLD.Model,jQuery);MLD.View.loadViewFunction('/dmapi/views/deal-text-sortable/text-item.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="text-item">  <input type="text" value="',textValue,'" maxlength="',textMaxLength,'" />  <a class="del-d-loc">Delete</a>  <a class="add-d-loc">Add</a>  <div class="clear"></div> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/image.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<a class="deal-image-link" href="#">  <img class="deal-image" /> </a> <div class="control error" style="display:none"> </div> <div class="control change">  <input type="button" name="change" value="Change" /> </div> <div class="control processing" style="display:none">  Processing... </div> <div class="control file_input" style="display:none">  <input class="deal-img" type="file" name="deal-img" /> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/crop.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="control crop">   <img class="deal-image-original" src="/i/loading.gif" />   <p>    <input type="button" name="crop" value="Crop" />   </p>  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-location.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="node">  <p class="name">',location.getName(),'</p>   <p class="street1">',location.getStreetAddress().getStreet1(),'</p>   <p class="street2">',location.getStreetAddress().getStreet2(),'</p>   <p class="city-state-zip">   ',location.getStreetAddress().getCity(),',&nbsp;   ',location.getStreetAddress().getState(),'&nbsp;   ',location.getStreetAddress().getZipCode(),'  </p>   <p class="phone">',location.getPhoneNumber(),'</p>   <div class="control-edit">edit</div> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-location-edit.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<h4>Edit Location</h4> <form> <div class="name">  <input name="name" value="',location.getName(),'" size="50" /> </div> <div class="street1">  <input name="street1" value="',location.getStreetAddress().getStreet1(),'" size="50" /> </div> <div class="city-state-zip-phone">  <input name="city" value="',location.getStreetAddress().getCity(),'" size="15" />  <select name="state"> </select>  <input name="zip_code" value="',location.getStreetAddress().getZipCode(),'" size="10" /> </div> <div class="phone">  <input name="phone_number" value="',location.getPhoneNumber(),'" size="15" /> </div> </form> <input type="button" name="cancel" value="Cancel"/> <input type="button" name="save" value="Save"/> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/select_options.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');for(var i in items){var item=items[i];p.push(' <option value="',item[valueCallbackName](),'">  ',item[displayCallbackName](),' </option> ');}p.push(' ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-details.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<thead>  <tr class="table-heading">   <th>City</th>   <th>Status</th>   <th>Start/End date</th>   <th>Expires</th>   <th>Votes</th>   <th>Purchases</th>  </tr> </thead> <tr class="offer-data"> ');var startDate=new Date.parse(offer.getStart()+" utc");var endDate=new Date.parse(offer.getEnd()+" utc");var now=new Date();var statusSpanClass='';var statusText='Voting';if(offer.getStatus()=='scheduled'){statusSpanClass='live';statusText='Scheduled';}else if(offer.getStatus()=='offered'){statusSpanClass='ended';statusText='Ended';if(endDate.isAfter(now)){statusSpanClass='live';statusText='Live';}}else if(offer.getStatus()=='closed'){statusSpanClass='ended';statusText='Closed';}else if(offer.getStatus()=='tipped'){statusSpanClass='live';statusText='Tipped';}else if(offer.getStatus()=='expired'){statusSpanClass='ended';statusText='Expired';}var voucherExpiryStr="";if(offer.getVoucherExpiration()){var voucherExpiry=new Date.parse(offer.getVoucherExpiration());voucherExpiryStr=voucherExpiry.toString('MMMM d, yyyy');}p.push(' <td>',offer.getArea().getName(),'</td> <td><span class="deal-status bold ',statusSpanClass,'">',statusText,'</span></td> <td>  <a class="schedule" href="#">  ');if(offer.getStatus()!='community_voting'){p.push('   ',offer.getStart(),'  ');}else{p.push('  Schedule  ');}p.push('  </a> <br> ');if(offer.getStatus()!='community_voting'){p.push('  ',offer.getEnd(),' ');}p.push(' </td> <td> ',voucherExpiryStr,' </td> <td>',offer.getVoteCount(),'</td> <td>',offer.getPurchaseCount(),'</td> </tr>    ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-additional.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<tr>  <td colspan="6">   - <a class="offer-additional-table-open" href="#" >Additional info</a>  <table class="offer-additional-table" style="display:none">   <tr>    <td>Quantity to Reserve</td>    <td class="offer-additional-table-quantity">     <img class="offer-additional-loading" src="/i/loading.gif" />    </td>   </tr>   <tr>    <td>Counter Bid</td>    <td class="offer-additional-table-bid">     <img class="offer-additional-loading" src="/i/loading.gif" />    </td>   </tr>   <tr>    <td>Site</td>    <td class="offer-additional-table-site">     <img class="offer-additional-loading" src="/i/loading.gif" />    </td>   </tr>   <tr>    <td>Comments</td>    <td class="offer-additional-table-comments">     <img class="offer-additional-loading" src="/i/loading.gif" />    </td>   </tr>  </table>  </td>  </tr>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-email.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<tr>  <td colspan="6">   - <a class="offer-email-table-open" href="#">Email</a>  <table class="offer-email-table" style="display:none">   <tr>    <td>Alert</td>    <td>     <a href="/deal/',offer.getUrlFragment(),'/email" target="_blank">Html</a> -     <a href="/deal/',offer.getUrlFragment(),'/email/text/1" target="_blank">Text</a>    </td>   </tr>   <tr>    <td>Radius</td>    <td>     ',marketingInfo?marketingInfo.getEmailRadius():'','    </td>   </tr>   <tr>    <td>Subject A</td>    <td>     ',marketingInfo?marketingInfo.getEmailSubjectA():'','    </td>   </tr>   <tr>    <td>Subject B</td>    <td>     ',marketingInfo?marketingInfo.getEmailSubjectB():'','    </td>   </tr>   <tr>    <td>DMAs</td>    <td>     ',marketingInfo?marketingInfo.getDmaList().join(', '):'','    </td>   </tr>   <tr>    <td>CBSAs</td>    <td>     ');if(marketingInfo&&typeof(marketingInfo.data.cbsa_list)!='undefined'){p.push('      ');for(var i in marketingInfo.data.cbsa_list){p.push('       ',marketingInfo.data.cbsa_list[i].cbsa_name+' ('+marketingInfo.data.cbsa_list[i].cbsa_code+')','       <br/>      ');}p.push('     ');}p.push('    </td>   </tr>   <tr>    <td>PMSAs</td>    <td>     ');if(marketingInfo&&typeof(marketingInfo.data.pmsa_list)!='undefined'){p.push('      ');for(var i in marketingInfo.data.pmsa_list){p.push('       ',marketingInfo.data.pmsa_list[i].pmsa_name+' ('+marketingInfo.data.pmsa_list[i].pmsa_code+')','       <br/>      ');}p.push('     ');}p.push('    </td>   </tr>  </table>  </td>  </tr>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-schedule.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<tr> ');var startDate='',startHour='',startMinute='';if(offer.getStart()){var start=Date.parse(offer.getStart());var startTimeArr=start.toString('H:m').split(':');startDate=start.toString('MM/dd/yyyy');startHour=startTimeArr[0];startMinute=startTimeArr[1];}var endDate='',endHour='',endMinute='';if(offer.getEnd()){var end=Date.parse(offer.getEnd());var endTimeArr=end.toString('H:m').split(':');endDate=end.toString('MM/dd/yyyy');endHour=endTimeArr[0];endMinute=endTimeArr[1];}p.push(' <td colspan="7">  <label for="start_date" style="margin-left:1.15em;">  Start  </label>  <input type="text" name="start_date" value="',startDate,'" />  <select name="start_hour">  ');for(var i=0;i<24;i++){p.push('   <option value="',i,'" ',(i==startHour)?'selected="selected"':null,'>    ',i>9?i:'0'+String(i),'   </option>  ');}p.push('  </select>  &nbsp;:&nbsp;  <select name="start_minute">  ');for(var i=0;i<60;i++){p.push('   <option value="',i,'" ',(i==startMinute)?'selected="selected"':null,'>    ',i>9?i:'0'+String(i),'   </option>  ');}p.push('  </select>  EST<br />    <label for="end_date" style="margin-left:1.5em;">  End  </label>  <input type="text" name="end_date" value="',endDate,'" />  <select name="end_hour">  ');for(var i=0;i<24;i++){p.push('   <option value="',i,'" ',(i==endHour)?'selected="selected"':null,'>    ',i>9?i:'0'+String(i),'   </option>  ');}p.push('  </select>  &nbsp;:&nbsp;  <select name="end_minute">  ');for(var i=0;i<60;i++){p.push('   <option value="',i,'" ',(i==endMinute)?'selected="selected"':null,'>    ',i>9?i:'0'+String(i),'   </option>  ');}p.push('  </select>  EST<br />   ');if(offer.getPublisher().name=="Tippr"){p.push('   <label for="quantity_to_reserve">    Quantity to Reserve   </label>   <input type="text" name="quantity_to_reserve" size="6" maxlength="6" />   <br/>   <label for="counter_bid" style="margin-left:3.5em;">    Counter Bid   </label>   <input type="text" name="counter_bid" size="9" maxlength="9" />   <br/>   <label for="tippr_sites" style="margin-left:7.1em;">    Site   </label>   <select class="tippr-sites-select" name="tippr_sites">    <option value="default"></option>   </select>   <br/>  ');}p.push('    <label for="email_radius" style="margin-left:1.15em;">  Email Radius  </label>  <input type="text" name="email_radius" />  <br/>  <label for="email_subject_a">  Email Subject A  </label>  <input type="text" name="email_subject_a" />  <br/>  <label for="email_subject_b">  Email Subject B  </label>  <input type="text" name="email_subject_b" />  <br/>  <label for="new_dma">  DMAs  </label>  <input type="text" name="new_dma" />  <input type="button" value="Add" name="add_dma" />  <ul id="dma_list"> </ul>  <br/>  <label for="new_cbsa">   CBSAs  </label>  <input type="text" name="new_cbsa" />  <input type="button" value="Add" name="add_cbsa" />  <ul id="cbsa_list"> </ul>  <br/>  <label for="new_pmsa">   PMSAs  </label>  <input type="text" name="new_pmsa" />  <input type="button" value="Add" name="add_pmsa" />  <ul id="pmsa_list"> </ul>  <br/>  <input type="button" value="Submit" name="submit_button" />  <input type="button" value="Cancel" name="cancel_button" /> </td> </tr> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/offer-location-list.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div>  <div class="location-list">  </div>  <div class="location-list-controls">   <input type="button" name="back" value="Back" />  </div> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-editor/edit.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="edit-post">  <div class="group deal-details-wrap">  <form>   <fieldset class="e-deal-title">    <label>     <span class="label-title">Title</span>     <span><input id="deal-title" type="text" name="title" value="',deal.getTitle(),'" class="deal-title-txt" size="110" /></span>    </label>   </fieldset>   <fieldset class="f-set-1">    <div>     <label>      <span class="label-title mid-align">Image</span>      <span><div class="image-widget"></div></span>     </label>     <div class="disc-price">      <label>       <span class="label-title">Offered Price</span>       <span><input type="text" name="cost" value="',deal.getCost(),'" size="4" /></span>      </label>      <label>       <span class="label-title">Actual Value</span>       <span><input type="text" name="value" value="',deal.getValue(),'" size="4" /></span>      </label>      <span class="disc h6">Discount <span id="discount_amount">0</span>%</span>     </div>     <label>      <span class="label-title">Tipping at</span>      <span><input type="text" name="minimum_threshold" value="',deal.getMinimumThreshold(),'" size="2" /></span>     </label>     <label>      <span class="label-title">Purchase Limit <small>for each buyer</small></span>      <span><input type="text" name="quantity_limit" value="',deal.getQuantityLimit(),'" size="2" /></span>     </label>     <label>      <span class="label-title">Max Sale Limit</span>      <span><input type="text" name="maximum_threshold" value="',deal.getMaximumThreshold(),'" size="2" /></span>     </label>     <label>      <span class="label-title">Allow Gifting</span>      <span><input type="checkbox" name="allowed_to_gift" ',deal.isAllowedToGift()?'checked="checked"':null,' /></span>     </label>     <label>      <span class="label-title">Redemption Period</span>      <span>       <select name="redemption_period"></select>      </span>     </label>     <label>      <span class="label-title">Category</span>      <span>       <select name="category">        <option value="food">Food</option>        <option value="fun">Fun</option>        <option value="health_beauty">Health/Beauty</option>        <option value="shopping">Shopping</option>        <option value="travel_vacation">Travel/Vacation</option>        <option value="automotive">Automotive</option>        <option value="other">Everything Else</option>       </select>      </span>     </label>     <label>      <span class="label-title">Sub Category</span>      <span>       <select name="subcategory">        <option value="american">American</option>        <option value="bakery">Bakery</option>        <option value="bar_pub">Bar/Pub</option>        <option value="brazilian">Brazilian</option>        <option value="cafe">Cafe</option>        <option value="chinese">Chinese</option>        <option value="coffee_shop">Coffee Shop</option>        <option value="deli">Deli</option>        <option value="diner">Diner</option>        <option value="dinner_theatre">Dinner Theatre</option>        <option value="family">Family</option>        <option value="fine_dining">Fine Dining</option>        <option value="greek">Greek</option>        <option value="ice_cream">Ice Cream/Yogurt</option>        <option value="indian">Indian</option>        <option value="irish">Irish</option>        <option value="italian">Italian</option>        <option value="japanese">Japanese</option>        <option value="mediterranean">Mediterranean</option>        <option value="mexican">Mexican</option>        <option value="peruvian">Peruvian</option>        <option value="pizza">Pizza</option>        <option value="seafood">Seafood</option>        <option value="spanish">Spanish</option>        <option value="steakhouse">Steakhouse</option>        <option value="sushi">Sushi</option>        <option value="thai">Thai</option>        <option value="boat_rentals">Boat Rentals</option>        <option value="bowling">Bowling</option>        <option value="comedy">Comedy</option>        <option value="driving_range">Driving Range</option>        <option value="golf">Golf</option>        <option value="Lasertag">Lasertag</option>        <option value="live_theatre">Live Theatre</option>        <option value="miniature_golf">Miniature Golf</option>        <option value="movie_theatre">Movie Theatre</option>        <option value="museum">Museum</option>        <option value="paintball">Paintball</option>        <option value="scuba_diving">Scuba Diving</option>        <option value="skiing">Skiing</option>        <option value="snorkeling">Snorkeling</option>        <option value="theme_park">Theme Park</option>        <option value="tours">Tours</option>        <option value="white_water_rafting">White Water Rafting</option>        <option value="fitness">Fitness</option>        <option value="salon">Salon</option>        <option value="spa">Spa</option>        <option value="yoga">Yoga</option>        <option value="clothing">Clothing</option>        <option value="electronics">Electronics</option>        <option value="flowers">Flowers</option>        <option value="household">Household</option>        <option value="pet">Pet</option>        <option value="shoes">Shoes</option>        <option value="hotel">Hotel</option>        <option value="bed_and_breakfast">Bed &amp; Breakfast</option>        <option value="resort">Resort</option>        <option value="car_wash">Car Wash</option>        <option value="detail">Detail</option>        <option value="inspection">Inspection</option>        <option value="oil_change">Oil Change</option>        <option value="everything_else">Seriously... Everything Else</option>       </select>      </span>     </label>     <label>      <span class="label-title">Merchant</span>      ');var org=deal.getOrganization();p.push('      <span>',org.name,'</span>     </label>     <label>      <span class="label-title">Publisher</span>      ');var pub=deal.getPublisher();p.push('      ');if(pub){p.push('      <span>',pub.name,'</span>      ');}p.push('     </label>     ');var status=deal.getStatus();var statusClass;switch(status){case"submitted":case"in_review":case"merchant_accepted":case"acceptance_pending":statusClass='pending';break;case"accepted":statusClass='live';break;default:statusClass='rejected';}p.push('     <label>      <span class="label-title">Status</span>      <span class="deal-status ',statusClass,'">',status,'</span>     </label>     <label>      <span class="label-title">Ask Price</span>      ');var price=parseFloat(deal.getAskPrice());p.push('      <span>$',price.toFixed(2),'</span>     </label>    </div>   </fieldset>   <fieldset class="f-set-2">    <div>     <label class="group">      <span class="label-title">Description</span>      <textarea class="description-textarea" name="description" cols="50">',deal.getDescription(),'</textarea>     </label>     <label class="group highlights">      <span class="label-title">Highlights</span>     </label>     <div class="highlights-dealtext">',deal.getHighlights(),'</div>     <label class="group highlights">      <span class="label-title">Fine Print</span>     </label>     <div class="fineprint-dealtext">',deal.getFinePrint(),'</div>    </div>   </fieldset>   <fieldset class="f-set-3">    <label>     <span class="label-title">Foreign Deal Id</span>     <span>',deal.getForeignDealId(),'</span>    </label>    <h3>Deal Offers</h3>    <div class="offer-list clear">    </div>   </fieldset>   <ul class="approval-steps group">    <li class="approve-btn save-deal-btn"><a href="#" class="save-deal"></a></li>    <li class="cancel"><a class="cancel-edit" href="#">Cancel</a></li>   </ul>  </form>  </div> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/paginator.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var page=search.getPage();var lastPage=search.getLastPage();var displayPageStart=page-2>1?page-2:1;var displayPageEnd=page+2<lastPage?page+2:lastPage;p.push(' <div class="paginator">  ');if(settings.showPageInfo){p.push('  <div class="pageInfo">   Showing ',search.getRowDisplayStart(),' to ',search.getRowDisplayEnd(),' of ',search.getTotalCount(),' entries  </div>  ');}p.push('   <div class="dataTables_paginate paging_full_numbers">   ');if(displayPageStart>2){p.push('   <span class="first_page paginate_button">    First   </span>   ');}p.push('   ');if(page>1){p.push('   <span class="previous_page paginate_button">    Previous   </span>   ');}p.push('   <span class="page_buttons">    ');for(var i=displayPageStart;i<=displayPageEnd;i++){p.push('    <span class="page ',i==page?'paginate_active':'',' paginate_button">     ',i,'     <input type="hidden" value="',i,'"/>    </span>    ');}p.push('   </span>   ');if(page<lastPage){p.push('   <span class="next_page paginate_button">    Next   </span>   ');}p.push('   ');if(displayPageEnd<lastPage-1){p.push('   <span class="last_page paginate_button">    Last   </span>   ');}p.push('  </div> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-search/row.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var status=deal.getStatus();var statusClass;switch(status){case"submitted":case"in_review":case"merchant_accepted":case"acceptance_pending":statusClass='pending';break;case"accepted":statusClass='live';break;default:statusClass='rejected';}var offer1=deal.offerList[0];p.push('  <span class="deal-status ext bold ',statusClass,'">',status,'</span>  <span class="deal-date small"></span>  <div class="deal-sect-details group">   <h4 class="ff-2 h3">    <a href="/deal/',offer1.getUrlFragment(),'" target="_blank">',deal.getTitle(),'</a>   </h4>   <ul class="offer-list">   </ul>   <div class="purchase-list"></div>   <ul class="approval-steps group">    <li class="preview-btn">     <a href="/deal/',offer1.getUrlFragment(),'" target="_blank"></a>    </li>    ');if(status=='merchant_accepted'){p.push('    <li class="approve-btn">     <a href="#" class="approval"></a>    </li>    <li class="approve-btn">     <a href="#" class="rejection"></a>    </li>    ');}p.push('    <li class="reject-btn edit-details">     <a href="#">Edit deal details</a>    </li>   </ul>   ');if(status=='merchant_accepted'){p.push('   <div class="reason hide">    <h4 class="mar-btm-0">Why are you rejecting this deal?</h4>    <textarea rows="2" cols="116"></textarea>    <a href="#" class="submit-btn"></a>&nbsp;&nbsp;or&nbsp;&nbsp;<a class="cancel" href="#">Cancel</a>   </div>   ');}p.push('  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-search/row-offer-list.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var len=offerList.length;for(var i in offerList){var offer=offerList[i];var offerStatus="";var offerInfo="";if(offer.getStatus()=='community_voting'){offerStatus="Voting";var vCount=offer.getVoteCount();offerInfo='<span class="fade">('+vCount+(vCount==1?' vote)':' votes)</span>');}else if(offer.getStatus()=='scheduled'){offerStatus="Scheduled";offerInfo='(purchase-list)';}else if(offer.getStatus()=='offered'){offerStatus="Offered";offerInfo='(purchase-list)';}else if(offer.getStatus()=='closed'){offerStatus="Closed";offerInfo='(purchase-list)';}if(offerInfo=='(purchase-list)'){var offerData=offer.area.getName()+' '+offer.area.getStateCode()+'|'+offer.getId();offerInfo='<a class="view-p-list" href="#" title="';offerInfo+=offerData;offerInfo+='">('+offer.getPurchaseCount()+' bought)</a>';}p.push(' <li class="deal-attr">  <p class="mar-btm-0 disp-i-bl">   <strong>    ',offer.area.getName(),'    ',offer.area.getStateCode(),'   </strong>   ');if(offerStatus){p.push('    &mdash; ',offerStatus,' ',offerInfo,'   ');};p.push('  </p> </li> ');};p.push(' ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-search/search.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="filter-container">  <div class="nav user-nav group mar-btm-10">   <ul>    <li class="top d-list">     <select name="cbsa">      <option value="all">CBSA Area</option>      <option value="12060">Atlanta</option>      <option value="12420">Austin</option>      <option value="12580">Baltimore</option>      <option value="14460">Boston</option>      <option value="15380">Buffalo</option>      <option value="16980">Chicago</option>      <option value="17460">Cleveland</option>      <option value="19100">Dallas</option>      <option value="19740">Denver</option>      <option value="19820">Detroit</option>      <option value="26420">Houston</option>      <option value="29820">Las Vegas</option>      <option value="31100">Los Angeles</option>      <option value="33100">Miami</option>      <option value="33460">Minneapolis</option>      <option value="35620">New York</option>      <option value="37980">Philadelphia</option>      <option value="38060">Phoenix</option>      <option value="38300">Pittsburgh</option>      <option value="40140">Riverside</option>      <option value="40900">Sacramento</option>      <option value="41740">San Diego</option>      <option value="41860">San Francisco</option>      <option value="42660">Seattle</option>      <option value="41180">St. Louis</option>      <option value="45300">Tampa</option>      <option value="47900">Washington DC</option>     </select>    </li>    <li class="top d-list">     <select name="deal_status_id">      <option value="all">Deal Status</option>      <option value="1">Submitted</option>      <!--<option value="2">In Review</option>-->      <option value="5">Accepted</option>      <option value="6">Merchant Accepted</option>      <option value="7">Merchant Rejected</option>      <option value="3">Manually Rejected</option>      <option value="4">System Rejected</option>      <option value="8">Acceptance Pending</option>      <option value="9">Acceptance Rejected</option>     </select>    </li>    <li class="top d-list">     <select name="offer_status_id">      <option value="all">Offer Status</option>      <option value="1">Community Voting</option>      <option value="2">Scheduled</option>      <option value="5">Closed</option>     </select>    </li>    <li class="top d-list">     <select name="provider_id">      <option value="all">Provider</option>     </select>    </li>    <li class="top d-list">     <select name="submitted_date_range">      <option value="all">Submitted In</option>      <option value="30">Last 30 Days</option>      <option value="60">Last 60 Days</option>      <option value="90">Last 90 Days</option>     </select>    </li>    <li class="top d-list">     <select name="submitted_date_sort">      <option value="DESC">DESC</option>      <option value="ASC">ASC</option>     </select>    </li>    <li class="top d-list">     <input type="button" id="deal-filter-btn" name="deal-filter-btn" value="Filter"/>    </li>   </ul>   <div id="user-search">    <input type="search" id="user-search-txt" name="user-search-txt"/>    <input type="submit" id="user-search-btn" name="user-search-btn" value="Search"/>   </div>  </div> </div> <ul class="result-set" id="deal-sect-list"> <li><img id="loading" src="/i/loading.gif" /></li> </ul> <div class="paginator"> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-dash/index.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="filter-container">  </div>  <ul class="result-set" id="deal-sect-list">  <li><img id="loading" src="/i/loading.gif" /></li>  </ul>  <div class="paginator">  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-dash/row.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var startDate=new Date.parse(offer.getStart()+" utc");var endDate=new Date.parse(offer.getEnd()+" utc");var now=new Date();var displayDate='';var statusSpanClass='';var statusText='Voting';if(offer.getStatus()=='scheduled'||offer.getStatus()=='offered'||offer.getStatus()=='tipped'){statusSpanClass='ended';statusText='Ended';displayDate=endDate.clone();if(endDate.isAfter(now)){statusSpanClass='live';statusText='Live';displayDate=startDate.clone();}}if(offer.getStatus()=='closed'||offer.getStatus()=='expired'){statusSpanClass='ended';statusText='Closed';}var displayDateStr='';if(displayDate){var datePartStr=displayDate.toString('dddd, MMMM d, yyyy');if(displayDate.is().today()){datePartStr='Today';}displayDateStr=datePartStr+' at '+displayDate.toString('h:mm tt');}p.push('  <span class="deal-status bold ',statusSpanClass,'">',statusText,'</span><span class="deal-date small">  ',displayDateStr,'  </span>  <ul class="deal-actions">   ');if(statusText=='Live'){p.push('   <li><a class="end-now" href="#">End Now</a></li>   ');}p.push('   ');if(false){p.push('   <li><a class="duplicate" href="#">Duplicate</a></li>   ');}p.push('  </ul>  <div class="deal-sect-details group">      <h4 class="ff-3"><a href="/deal/',offer.getUrlFragment(),'">',offer.getTitle(),'</a></h4>   <div class="clear"></div>   <p class="f-left ff-3">City: <span class="slant dark">',offer.area.getName(),' ',offer.area.getStateCode(),'</span></p>      <span class="deal-stats last"><span class="deal-count">',offer.getVoteCount(),'</span>Votes</span>   ');if(offer.getStatus()=='scheduled'||offer.getStatus()=='offered'||offer.getStatus()=='closed'){p.push('   <span class="deal-stats"><span class="deal-count">',offer.getPurchaseCount(),'</span>Sold</span>   <span class="deal-stats"><span class="deal-count revenue"></span>Our revenue</span>   ');}p.push('      <a class="share-deal" href="',offer.getShareLinkFacebook(),'" target="_blank"><img src="/i/facebook-l.png" /></a>   <a class="share-deal share-twit" href="',offer.getShareLinkTwitter(),'" target="_blank"><img src="/i/twitter-l.png" /></a>  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal-dash/pendingRow.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var statusSpanClass='pending';var statusText='Pending';if(deal.getStatus()=='merchant_rejected'||deal.getStatus()=='manually_rejected'||deal.getStatus()=='system_rejected'){statusSpanClass='rejected';statusText='Rejected';}if(deal.getStatus()=='accepted'){statusSpanClass='accepted';statusText='Accepted';}p.push('  <span class="deal-status bold ',statusSpanClass,'">',statusText,'</span>  <div class="deal-sect-details group">   <h4 class="ff-3 h3 fs-16 bold">    <a href="/deal/',deal.offerList[0].getUrlFragment(),'" target="_blank">',deal.getTitle(),'</a>   </h4>   <p class="disp-i-bl p-share f-left ff-3">    <!--Share for each purchase: $ <br />  -->    ');if(deal.getQuantityLimit()>0){p.push('    Limit of purchase: ',deal.getQuantityLimit(),'    ');}p.push('   </p>   <p class="ff-3">    Cities where the deal will launch: <br />    <span class="slant dark ff-3">    ');var len=deal.offerList.length;for(var i in deal.offerList){var offer=deal.offerList[i];p.push('    ',offer.area.getName(),'    ',offer.area.getStateCode(),'',i<(len-2)?', ':'','',i==(len-2)?' and ':'','    ');};p.push('    </span>   </p>   ');if(statusText=='Pending'&&$('#dash-info-orgtype').val()=='business'&&deal.getStatus()!='merchant_accepted'){p.push('   <ul class="approval-steps group">    <li class="preview-btn"><a href="/deal/',deal.offerList[0].getUrlFragment(),'" target="_blank"></a></li>    <li class="approve-btn"><a href="#" class="approval"></a></li>    <li class="approve-btn"><a href="#" class="rejection"></a></li>   </ul>   ');}p.push('   <div class="reason hide ff-3">    <h4 class="mar-btm-0">Why are you rejecting this deal?</h4>    <textarea rows="2" cols="86"></textarea>    <div class="clear"></div>    <a href="#" class="submit-btn"></a>&nbsp;&nbsp;or&nbsp;&nbsp;<a class="cancel" href="#">Cancel</a>    <div class="clear"></div>   </div>  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/deal_cut_pie_chart.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="pie_chart_container"> <div class="chart_display">  <div class="chart">   <img src="/deal_cut_chart/?merchantCut=',obj.getMerchantCut()/100,'&scale=1" />  </div>  <div class="left_column">   <h4>Standard</h4>  </div>  <div class="right_column">   <h4>Networked</h4>  </div> </div> <div class="percentages">  <table>   <thead>    <tr>     <th> </th>     <th>Standard</th>     <th>Networked</th>    </tr>   </thead>   <tbody>    <tr class="merchantCut">     <td>Merchant</td>     <td class="percentage">',obj.getMerchantCut(),'%</td>     <td class="percentage">',obj.getMerchantCut(),'%</td>    </tr>    <tr class="publisherCut">     <td>Publisher</td>     <td class="percentage">',obj.getPublisherCut(),'%</td>     <td class="percentage">',obj.getPublisherCut(true),'%</td>    </tr>    <tr class="serviceProviderCut">     <td>CitizenLocal</td>     <td class="percentage">',obj.getServiceProviderCut(),'%</td>     <td class="percentage">',obj.getServiceProviderCut(true),'%</td>    </tr>    <tr class="purchaserOwnerCut">     <td>Affiliate</td>     <td class="percentage">N/A</td>     <td class="percentage">',obj.getPurchaserOwnerCut(),'%</td>    </tr>   </tbody>  </table> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/merchant-selector/merchantAddForm.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<fieldset id="new-merchant-details" >   <p class="error" style="display:none"> </p>  <fieldset class="merchant-info merchantContactInformation">    <p class="mar-btm-0"><input type="text" name="name" size="35" label="Merchant Name" /></p>   <p class="mar-btm-0">    <select name="category">     <option value="">Select Category</option>    </select>   </p>   <span class="label-address h5 ff-1 fade">Merchant Contact Details</span>    <p class="mar-btm-0"><input type="text" name="first_name" size="15" label="First Name" /><input type="text" name="last_name" size="15" label="Last Name" /></p>      <p class="mar-btm-0"><input type="text" name="email" size="36" label="Email" /></p>   <p class="mar-btm-0"><input type="text" name="phone_number" size="36" label="Phone Number" /></p>   <p class="mar-btm-0 note-2 h6 slant fade">If the business and person do not already exist in our database we will create them and email the contact person with instructions for creating their account and approving the deal once it is submitted.</p>    <ul style="display:none" class="error-message-list">    <li style="display:none" class="error-message name">You must provide the name of the merchant.</li>    <li style="display:none" class="error-message category">You must select a category.</li>    <li style="display:none" class="error-message first_name">You must provide a valid first name.</li>    <li style="display:none" class="error-message last_name">You must provide a valid last name.</li>    <li style="display:none" class="error-message email">You must provide a valid email address.</li>    <li style="display:none" class="error-message email" errorCode="emailExists">The email you provided is already registered with us.</li>    <li style="display:none" class="error-message phone_number">You must provide a valid phone number.</li>   </ul>  </fieldset>   <fieldset class="merchant-info streetAddress">    <span class="label-address h5 ff-1 fade">Merchant Address Details</span>    <p class="mar-btm-0"><input type="text" name="street1" size="35" label="Street Address" /></p>      <p class="mar-btm-0"><input type="text" name="city" size="15" label="City" />    <select name="state">     <option value="">Select State</option>   </select>   <input type="text" name="zip_code" size="10" label="Zip Code" /></p>    <p class="mar-btm-0 note-2 small slant fade">This is the address where the payment will be mailed.</p>    <ul style="display:none" class="error-message-list">    <li style="display:none" class="error-message street1">Street Address is required.</li>    <li style="display:none" class="error-message city">City must be a valid city.</li>    <li style="display:none" class="error-message state">Please select a state.</li>    <li style="display:none" class="error-message zip_code">Please provide a valid zip code.</li>   </ul>  </fieldset>   <p><input type="button" class="button ext" name="submit-add" value="Add Merchant" /><span class="h6"> or <a class="cancel-adding" href="#">Cancel</a></span></p>  </fieldset>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/merchant-selector/search.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="search">  <div class="criteria">   Merchant Name: <input name="merchant_name"/>  </div>  <div class="search-results" style="display:none">   <div class="result-set">   </div>   <div class="paginator">   </div>  </div>  <p id="no-merchant" class="fade ff-1"><a class="add-merchant-details" href="#"> + Add New</a></p>  </div> <div class="selected-merchant" style="display:none"> </div> <div class="new-merchant-form" style="display:none">  </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/merchant-selector/row.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="merchant-row">  ',merchant.getName(),' </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-widget/main.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var savings=offer.getValue()-offer.getCost();var discount=Math.ceil(savings/offer.getValue()*100);var scale=settings.scale;p.push(' <style type="text/css"> #citizenlocal-widget { position:relative; width:',300*scale,'px; border-radius:1.5%; -webkit-border-radius:4px; -moz-border-radius:1.5%; background-color:#',settings.borderColor,'; padding:1% 0.6% 3%; font-size:',13*scale,'px; font-family:"Segoe UI","Helvetica Neue",Arial,sans-serif; } #citizenlocal-widget div { color:#',settings.textColor,'; } #citizenlocal-widget img.clWidgetLogo {  width:',73*scale,'px; height:',16*scale,'px; float:right; margin-top:2%; margin-right:2%; } #citizenlocal-widget div.clWidgetTitle { font-size:135%; color:#',settings.titleColor,'; font-family:"Segoe UI","Helvetica Neue",Arial,sans-serif; margin-bottom:1%; padding:0 3% 2%; } #citizenlocal-widget div.clWidgetOfferTitle { font-size:100%; color:#',settings.offerTitleColor,'; padding: 2% 3% 1%; cursor:pointer; margin-bottom:1%; font-weight:bold; } #citizenlocal-widget div.clWidgetOfferTitle:hover { text-decoration:underline; } #citizenlocal-widget img.clWidgetOfferImage { width:',150*scale,'px; height:',100*scale,'px; float:left; } #citizenlocal-widget div.clWidgetDealContainer { background-color:#',settings.backgroundColor,'; -moz-box-shadow:0 0 10px rgba(0, 0, 0, 0.25); -webkit-box-shadow: rgba(0, 0, 0, 0.246094) 0px 0px 10px; //height:',175*scale,'px; padding-bottom:4%; } #citizenlocal-widget div.clWidgetDealInfo { width:',150*scale,'px; height:',100*scale,'px; color:#',settings.dealTextColor,'; background-color:#',settings.dealBackgroundColor,'; float:left; }  #citizenlocal-widget div.clWidgetBuyButton { cursor:pointer; -moz-border-radius:1.5%; -webkit-border-radius:1.5%; -moz-box-shadow:0 0 5px rgba(0, 0, 0, 0.3); -webkit-box-shadow: rgba(0, 0, 0, 0.296875) 0px 0px 5px; text-decoration: none; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3); font:130% Georgia,serif; width:80%; margin-left:auto; margin-right:auto; margin-top:7%; margin-bottom:7%; padding:2%; text-align:left; border:2px solid #',settings.buttonBorderColor,'; background:-moz-linear-gradient(center top , #FAA51A, #F47A20) repeat scroll 0 0 transparent; background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#FAA51A), to(#F47A20)); background: #FAA51A; border: 2px solid #FFFFFF; } #citizenlocal-widget div.clWidgetBuyButton:hover { background:-moz-linear-gradient(center top , #F88E11, #F06015) repeat scroll 0 0 transparent; background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#F88E11), to(#F06015)); background: #F88E11; } #citizenlocal-widget div.clWidgetBuyButtonText { color:#FEF4E9; display:inline-block; } #citizenlocal-widget div.clWidgetBuyButtonPrice { color:#9C4C0C; border-right:1px solid rgba(0, 0, 0, 0.1); display:inline-block; width:33%; text-align:center; } #citizenlocal-widget div.clWidgetInfoItemList { margin-left:auto; margin-right:auto; width:80%; font-size:85%; } #citizenlocal-widget div.clWidgetInfoItem { margin-left:auto; margin-right:auto; display:inline-block; text-align:center; padding-left:1%; padding-right:1%; width: 29%; color: #9097AC; font-size: 92%; } #citizenlocal-widget div.clWidgetInfoItem div { font-family:"Segoe UI","Helvetica Neue",Arial,sans-serif; font-weight:bold; font-size: 117%; color: #6C6D79; } #citizenlocal-widget div.clWidgetExtraStuff { margin-left:auto; margin-right:auto; width:75%; font-size:90%; margin-top:40%; clear:both; } #citizenlocal-widget div.clWidgetExtraStuffText { display:inline-block; padding:1%; margin-left:auto; margin-right:auto; } #citizenlocal-widget div.clWidgetExtraStuffValue { font-weight:bold; display:inline; } #citizenlocal-widget div.clWidgetExtraStuffTextLast { float:right; } </style> <div id="citizenlocal-widget">  <img class="clWidgetLogo" src="http://www.citizenlocal.com/i/logotype-cl-widget.png" />  <div class="clWidgetTitle">',offer.getArea().getName()+' Daily&nbsp;Deal','</div>  <div class="clWidgetDealContainer">   <div class="clWidgetOfferTitle">',offer.getTitle(),'</div>   <img class="clWidgetOfferImage" src="',scale>1?offer.getImageUrl():offer.getImageThumbnailUrl(),'" alt="Logo" height="100" />   <div class="clWidgetDealInfo">    <div class="clWidgetBuyButton">     <div class="clWidgetBuyButtonPrice"><small>$</small>',offer.getCost(),'</div>     <div class="clWidgetBuyButtonText">Buy Now</div>    </div>    <div class="clWidgetInfoItemList">     <div class="clWidgetInfoItem">Value <div>$',offer.getValue(),'</div></div>     <div class="clWidgetInfoItem">Discount <div>',discount,'%</div></div>     <div class="clWidgetInfoItem">Save <div>$',savings,'</div></div>    </div>   </div>   <div class="clWidgetExtraStuff">    <div class="clWidgetExtraStuffText">Purchased: <div class="clWidgetExtraStuffValue">',offer.getPurchaseCount(),'</div></div>    <div class="clWidgetExtraStuffText clWidgetExtraStuffTextLast">Time Left: <div class="clWidgetExtraStuffValue clWidgetTimeLeft"> </div></div>   </div>  </div> </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-widget/main-no-deal.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var scale=settings.scale;p.push('  <style type="text/css"> @font-face  {  font-family: "LeagueGothicRegular";  src: url("http://www.citizenlocal.com/css/League_Gothic-webfont.eot");  src: local("☺"),   url("http://www.citizenlocal.com/css/League_Gothic-webfont.woff") format("woff"),   url("http://www.citizenlocal.com/css/League_Gothic-webfont.ttf") format("truetype"),   url("http://www.citizenlocal.com/css/League_Gothic-webfont.svg#webfontOTINA1xY") format("svg");  font-weight: normal;  font-style: normal; }  #citizenlocal-widget {  position:relative;  width:',300*scale,'px;  border-radius:1.5%;  -webkit-border-radius:4px;  -moz-border-radius:1.5%;  background-color:#',settings.borderColor,';  padding:1% 0.6% 3%;  font-size:',13*scale,'px;  font-family:"Segoe UI","Helvetica Neue",Arial,sans-serif; }  #citizenlocal-widget div {  color:#EE5921;  /*color:#',settings.textColor,';*/ }  #citizenlocal-widget img.clWidgetLogo {  width:',73*scale,'px;  height:',16*scale,'px;  float:right;  margin-top:2%;  margin-right:2%; }  #citizenlocal-widget div.clWidgetTitle {  font-size:135%;  color:#',settings.titleColor,';  font-family:"Segoe UI","Helvetica Neue",Arial,sans-serif;  margin-bottom:1%;  padding:0 3% 2%; }  #citizenlocal-widget div.clWidgetOfferTitle {  font-size:100%;  color:#',settings.offerTitleColor,';  padding: 2% 3% 1%;  cursor:pointer;  margin-bottom:1%;  font-weight:bold; }  #citizenlocal-widget div.clWidgetOfferTitle:hover {  text-decoration:underline; }  #citizenlocal-widget img.WidgetDealContainerBg {  //z-index:2;  position:absolute;  top:0;  left:0;  width:100%;  height:100%; }  #citizenlocal-widget div.clWidgetDealContainer {  position:relative;  height:',175*scale,'px;  padding-bottom:4%;  text-transform:uppercase; }  #citizenlocal-widget div.clWidgetDealContainer div {  z-index:1; }  #citizenlocal-widget div.clWidgetNoDealDetails {  font:',32*scale,'px/0.8 "LeagueGothicRegular",Arial,serif;  left:',20*scale,'px;  letter-spacing:1px;  position:absolute;  top:',30*scale,'px;  text-align:center;  color:#EE5921; }  #citizenlocal-widget div.clWidgetNoDealDetailsPercent {  font-size:',76*scale,'px;  line-height:',68*scale,'px; }  #citizenlocal-widget div.clWidgetNoDealButton {  padding:2% 7%;  font:bold ',14*scale,'px "Segoe UI","Helvetica Neue",sans-serif;  position:absolute;  top:',152*scale,'px;  left:',121*scale,'px;  cursor:pointer;  -moz-border-radius:1.5%;  -webkit-border-radius:1.5%;  -moz-box-shadow:0 0 5px rgba(0, 0, 0, 0.3);  -webkit-box-shadow: rgba(0, 0, 0, 0.296875) 0px 0px 5px;  text-decoration: none;  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);  text-align:left;  background: #FF7D4D;  background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#FF7D4D), to(#EF5A22));  background:-moz-linear-gradient(center top , #FF7D4D, #EF5A22);  color:#FFFFFF;  text-shadow:0 1px 1px rgba(0, 0, 0, 0.3); }  #citizenlocal-widget div.clWidgetNoDealButton:hover {  text-shadow:none; }  </style>  <div id="citizenlocal-widget">  <img class="clWidgetLogo" src="http://www.citizenlocal.com/i/logotype-cl-widget.png" />  <div class="clWidgetTitle">',area.getName()+' Daily&nbsp;Deal','</div>  <div class="clWidgetDealContainer">   <div class="clWidgetNoDealDetails">    <div>Get Up To</div>    <div class="clWidgetNoDealDetailsPercent">     90%    </div>    <div>Off</div>   </div>   <div class="clWidgetNoDealButton">See Todays Deal</div>   <img class="WidgetDealContainerBg" src="http://www.citizenlocal.com/i/no-deal-bnr.png" />  </div> </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/org-editor/logo.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<span class="widget image" style="display:none">   <img class="organization-logo disp-i-bl mar-btm-0 bordered" />  </span>  <span class="widget error" style="display:none">  </span>  <span class="widget change">   <a class="button ext" id="choose-logo" href="#">Choose Logo</a><br />   <span class="note" style="display:none">Image will be scaled to 390x260 pixels. Image must be less than 2Mb in size.</span>  </span>  <span class="widget processing" style="display:none">   Processing...  </span>  <span class="widget file_input" style="display:none">   <input type="file" id="organization-img" name="organization-img" />  </span>    <input type="hidden" name="image_id" value="" />  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-suggested-list/search.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="result-set"></div>  <div class="sb-deal-nav ff-1 bold">  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-suggested-list/get-featured-link.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<a href="',url,'" title="get featured" class="getFeaturedTile"><img src="/i/placeholder-f.png" class="temporary" /></a> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-suggested-list/node.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push(' <div class="sb-deal group">   <h4><a rel="#suggested-overlay"    href="/deal/',offer.getUrlFragment(),'/suggested?',(+new Date)+(Math.floor(Math.random()*10001)),'">    ',offer.getTitle(),'</a>   </h4>      ');if(hasVoted){p.push('    <div class="action-blk ff-1">          <div class="voteContainer">      <div class="imgVoted">&nbsp;</div>      <div class="vote-count">       <strong>',voteCount,'</strong> Vote',voteCount==1||voteCount==0?null:'s','      </div>     </div>          <div class="clear"></div>    </div>   ');}else{p.push('    <div class="action-blk ff-1">          <div class="voteContainer">      <a href="#" class="imgVote vote" id="offer',offer.getId(),'" onclick="javascript: return false;">&nbsp;</a>      <div class="vote-count">       <strong>',voteCount,'</strong> Vote',voteCount==1||voteCount==0?null:'s','      </div>     </div>          <div class="clear"></div>    </div>   ');}p.push('       <div class="clear"></div>      <div class="saveContainer">    ');if(hasVoted){p.push('     <div class="votedText"><strong>Thanks</strong> why not promote this deal?<span class="arrow"></span></div>    ');}else{p.push('     <div class="offerText">SAVE<br><strong>',offer.getDiscount(),'%</strong></div>    ');}p.push('   </div>        <div class="imgOffer">    <img src="',offer.getImageThumbnailUrl(),'" alt="" width="120" height="90" />   </div>      <p class="shareOffer">    <strong class="ff-1">Share:</strong>    <a class="fb large" href="',offer.getShareLinkFacebook(),'" target="_blank">Facebook</a>    <a class="tw large" href="',offer.getShareLinkTwitter(),'" target="_blank">Twitter</a>    <a class="em large last" href="',offer.getShareLinkEmail(),'" target="_blank">Email</a>   </p>  </div> ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-suggested-list/offer-suggested-paginator.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var page=search.getPage();var lastPage=Math.ceil((search.getTotalCount()+1)/search.getRowsPerPage());var displayPageStart=page-2>1?page-2:1;var displayPageEnd=page+2<lastPage?page+2:lastPage;p.push('  ');if(lastPage>1){p.push('  <ul>   ');if(page>1){p.push('   <li>    <a class="previous_page" href="#">&laquo;</a>   </li>   ');}p.push('   ');for(var i=displayPageStart;i<=displayPageEnd;i++){p.push('   <li class="page ',i==page?'active-page':'','">    <a href="#" rel="',i,'">',i,'</a>   </li>   ');}p.push('   ');if(page<lastPage){p.push('   <li>    <a class="next_page" href="#">&raquo;</a>   </li>   ');}p.push('  </ul>  ');}p.push('  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/purchase-search/search.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div class="filter-container">  </div>  <table class="ff-1 user-list-table purchase-table">   <tbody>    <tr class="user-pur p-details h5">     <td colspan="4">      <table>       <col width="12%">       <col width="12%">       <col width="12%">       <col width="14%">       <col width="12%">       <col width="7%">       <col width="29%">       <thead>        <tr class="p-heading">         <td>Purchase ID</td>         <td>Name</td>         <td>City</td>         <td>Quantity</td>         <td>Unit Price</td>         <td>Total</td>         <td></td>        </tr>       </thead>       <tbody class="result-set">       </tbody>      </table>     </td>    </tr>   </tbody>  </table>  <div class="paginatorX">  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/purchase-search/row.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var purchAmount=purchase.getAmount();var amountFormatted=String(Math.round(purchAmount*100)/100);if(amountFormatted.length>2&&amountFormatted.charAt(amountFormatted.length-2)=="."){amountFormatted=amountFormatted+"0";}p.push('  <td><span class="purchase-id">',purchase.getId()+'&nbsp;('+purchase.getStatus()+')','</span></td>  <td><span class="name">',purchase.getBuyerName(),'</span></td>  <td><span>',areaName,'</span></td>  <td><span>',purchase.getQuantity(),' <a href="#" class="show-v-list">Voucher List</a></span></td>  <td>$',amountFormatted/purchase.getQuantity(),'</td>  <td>$',amountFormatted,'</td>  ');if(purchase.getStatus()!='refunded'){p.push('  <td><a href="#" class="refund button ext">Refund</a></td>  ');}p.push('  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/purchase-search/voucher-row.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');var cols=4;p.push('  <td colspan="8">   <table>    <col width="25%"></col>    <col width="25%"></col>    <col width="25%"></col>    <col width="25%"></col>    <tbody>    ');$.each(voucherList,(function(ind,voucher){p.push('     ');if(ind%cols==0){p.push('     <tr class="v-list last">     ');}p.push('      <td>       <span class="bold dark disp-bl mar-btm-0">#',voucher.getCode(),'</span>      </td>     ');if(ind%cols==(cols-1)){p.push('     </tr>     ');}p.push('    ');}));p.push('    </tbody>   </table>  </td>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/comment-widget/main.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<h4 class="l-fade bold">Discuss this Deal</h4>  <div class="comment-result-set">  </div>  <p>   <a href="#" class="leave-comments h5"></a>  </p>  <div class="add-comments hide">   <form class="comment-form" action="" method="post" name="comment-form">    <label><span>Comment</span><textarea name="comment-text" cols="35" rows="5"></textarea></label>    <input type="submit" class="add-comment" value="Add" />    <p class="cancel-comment h6">or <a href="#">Cancel</a></p>   </form>  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/comment-widget/row.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<span class="comment-id comment-id18 hide">',comment.getId(),'</span>  <p class="meta">   <span class="left-q">“</span>   ',comment.getText(),'  </p>  <span class="m-fade f-right h6">—',comment.getAuthorName(),'</span>  ');if(isAdmin){p.push('   <a class="flag-link" href="#">Flag</a>  ');}p.push('  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-list/search.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<div id="creditPolicy-overlay" class="overlay-main">   <div class="contentWrap"></div>  </div>  <div id="gift-overlay" class="overlay-main">   <div class="contentWrap"></div>  </div>    <div class="jcarousel-scroll top-nav">  </div>    <div id="offer-scroll-list">   <ul class="result-set">    <li><img src="/i/loading.gif" alt="loading..." /></li>   </ul>  </div>    <div class="clear">&nbsp;</div>    <div class="c-nav jcarousel-control">   <div class="nav-items">   </div>  </div>    <div class="bot-nav-btn jcarousel-scroll">   <a href="#" class="prev jcarousel-prev jcarousel-prev-disabled mycarousel-prev">&laquo; Prev</a>   <a href="#" class="next jcarousel-next mycarousel-next">Next &raquo;</a>  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-list/bot-nav.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<a href="#" class="active">   <span class="active-pointer"></span>   <span class="h3 ff-1">',offer.getTitle(),'</span>   <span class="saving ext">Save <strong>',offer.getDiscount(),'%</strong></span>  </a>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-list/top-nav.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');if(total>1){p.push('  <p id="curr-deals" class="ff-1">     ');var tempInd=currentInd+1;var prevLinkDisabled;var nextLinkDisabled;if(tempInd==total){nextLinkDisabled="next-link-disabled";}else{nextLinkDisabled="";}if(tempInd==1){prevLinkDisabled="prev-link-disabled";}else{prevLinkDisabled="";}p.push('     Showing ',tempInd,' of ',total,' deals       <a href="#" class="bold prev jcarousel-prev jcarousel-prev-disabled mycarousel-prev ',prevLinkDisabled,'">&laquo; Prev</a>   <span class="m-fade">|</span>   <a href="#" class="bold next jcarousel-next mycarousel-next ',nextLinkDisabled,'">Next &raquo;</a>  </p>  ');}p.push('  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-list/node.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');function prepareForHtml(text){return text.replace(/(\r\n|\n|\r)/g,'|');}function prepareWithHtmlBreaks(text){return text.replace(/(\r\n|\n|\r)/g,'<br>');}function htmlListifyText(text){var lines=text.split('|');var html='';$.each(lines,function(i,line){html+='<li>';html+=line;html+='</li>';});return html;}var hasEnded=false;var endDate=new Date.parse(offer.getEnd());if(endDate.isBefore(new Date())){hasEnded=true;}var publisher=offer.getPublisher();var publisherLogoUrl=false;if(publisher.id!=1){publisherLogoUrl=publisher.image_url;}var voucherExpiry;var voucherExpiryStr;if(offer.getVoucherExpiration()===null){var monthsToExpire=offer.getRedemptionPeriodInMonths();voucherExpiry=endDate.clone().addMonths(monthsToExpire);voucherExpiryStr=voucherExpiry.toString('MMMM d, yyyy');}else{voucherExpiry=new Date.parse(offer.getVoucherExpiration());voucherExpiryStr=voucherExpiry.toString('MMMM d, yyyy');}p.push('  <div class="deal-main-title-wrap">   <h2><a href="/deal/',offer.getUrlFragment(),'">',offer.getTitle(),'</a></h2>   <div class="share-top last">    <span class="share">     <a class="fb large" href="',offer.getShareLinkFacebook(),'" target="_blank">Facebook</a>     <a class="tw large" href="',offer.getShareLinkTwitter(),'" target="_blank">Twitter</a>     <a class="em large" href="',offer.getShareLinkEmail(),'" target="_blank">Email</a>    </span>   </div>       <div class="share-earn ff-1">    <a class="h6" rel="#creditPolicy-overlay" href="/index/creditpolicy">&nbsp;</a>   </div>      <div class="clear"></div>     </div>  <div class="section-inner group">   <div class="deal-comp">    <img src="',offer.getImageUrl(),'" alt="deal-i" width="390" height="260" />   </div>         <div class="deal-info">      ');if(!hasEnded){p.push('    <a class="buyOrange" href="/deal/',offer.getUrlFragment(),'/purchase">Buy for $',offer.getCost(),'</a>    ');if(false){p.push('     <a class="giftDeals" rel="#gift-overlay" href="',offer.getUrlFragment(),'">Gift to a Friend</a>    ');}p.push('   ');}else{p.push('    <a class="buyOrange" href="#">      Deal Over    </a>   ');}p.push('      <ul>     <li>Value<br><span>$',offer.getValue(),'</span></li>     <li>Discount<br><span>',offer.getDiscount(),'%</span></li>     <li class="last">Savings<br><span>$',offer.getSavings(),'</span></li>    </ul>         <ul class="more-info">          <li class="timeLeft">Time Left<br><div id="formatTimer"></div></li>          <li id="purchased">Purchased<br><span>',offer.getPurchaseCount(),'</span></li>          ');if(offer.isTipped()){p.push('      <li class="last">The Deal is<br><span>ON</span></li>     ');}else{p.push('      <li class="last">Tipping at<br><span>',offer.getMinimumThreshold(),'</span></li>     ');}p.push('          ');if(offer.isTipped()){p.push('      <li class="tipped"><div class="tippedContainer">Tipped with ',offer.getMinimumThreshold(),' bought</div></li>     ');}else{p.push('      <li class="tipped"><div class="tippedContainer2">',(offer.getMinimumThreshold()-offer.getPurchaseCount()),' more needed to get the deal</div></li>     ');}p.push('         </ul>   </div>  </div>  <div class="deal-details">   <div class="comment ff-1 group hide">    <div class="col col1of2">     <div class="comment-widget"></div>    </div>    <div class="col col2of2 last">     ');if(publisherLogoUrl){p.push('     <p class="brought-by ff-2 slant mar-btm-0">Brought to you by:<br>      <img src="',publisherLogoUrl,'" alt="publisher logo" />     </p>     ');}p.push('    </div>   </div>      <div class="col col1of2">        <h3 class="ff-3 fs-18 bold">About the deal</h3>    <p>',prepareWithHtmlBreaks(offer.getDescription()),'</p>        <div class="clear"></div>        <p class="note expiry">     * Voucher expires on <span class="date">',voucherExpiryStr,'</span>    </p>        </div>       <div class="col col2of2 last">    <h3 class="ff-3">Highlights</h3>    <ul id="detail-highlights" class="std-list">     ',htmlListifyText(prepareForHtml(offer.getHighlights())),'    </ul>    <h3 class="ff-3">The Fine Print</h3>    <ul id="detail-fineprint" class="std-list">     ',htmlListifyText(prepareForHtml(offer.getFinePrint())),'    </ul>           </div>      <div class="deal-locations group">   </div>      <div class="clear"></div>     </div>    ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/offer-list/location.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('');function formatPhone(num){var numStr='';if(num.length==10){numStr=num.substring(0,3)+'-';numStr+=num.substring(3,6)+'-';numStr+=num.substring(6);}else{numStr=num;}return numStr;}p.push('  <div class="vcard">   <p class="street-address"><b>',loc.getName(),'</b><br>   ',loc.getStreetAddress().getStreet1(),'<br>   ',loc.getStreetAddress().getCity(),',   ',loc.getStreetAddress().getState(),'   ',loc.getStreetAddress().getZipCode(),'<br>   ',formatPhone(loc.getPhoneNumber()),'   </p>  </div>  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/alerts/main.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<form action="" method="post" id="opt-in-form" novalidate> <fieldset> <p id="error-message" class="error" style="display:none"></p> <div id="alerts-prefs" class="group">  <div class="col1of2">   <label for="state">I want to see deals in &nbsp;   <select name="area_select">    <option value="los-angeles-ca">Los Angeles, CA</option>    <option value="san-diego-ca">San Diego, CA</option>    <option value="san-francisco-ca">San Francisco, CA</option>    <option value="washington-dc">Washington, DC</option>    <option value="miami-fl">Miami, FL</option>    <option value="tampa-fl">Tampa, FL</option>    <option value="atlanta-ga">Atlanta, GA</option>    <option value="boston-ma">Boston, MA</option>    <option value="baltimore-md">Baltimore, MD</option>    <option value="detroit-mi">Detroit, MI</option>    <option value="minneapolis-mn">Minneapolis, MN</option>    <option value="saint-louis-mo">Saint Louis, MO</option>    <option value="new-york-ny">New York, NY</option>    <option value="philadelphia-pa">Philadelphia, PA</option>    <option value="austin-tx">Austin, TX</option>    <option value="dallas-tx">Dallas, TX</option>    <option value="houston-tx">Houston, TX</option>   </select>   </label>  </div><!-- .col1of2 -->  <div class="col2of2 last">   <div class="call-to-action">    <input id="btn-send-me-deals" src="/i/btn_send_me_deals_default.png" name="btn-send_me_deals" type="image">   </div>  </div>  <div class="clear">&nbsp;</div>  <div class="noCol">   <label for="email" style="float:left">Emails will be sent to:</label>   <input id="email" class="text" type="email" required="required" tabindex="130"     value="',email,'" name="email" style="width:305px;" disabled="disabled">  </div>   </div><!-- #billing-info .group --> </fieldset> </form>  <hr /> <div id="available-deal-alerts-section">  <img class="deal-image-original" src="/i/loading.gif" /> </div>  <div id="my-deal-alerts-section">  <img class="deal-image-original" src="/i/loading.gif" /> </div>  <div id="general-emails-section"> </div>   ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/alerts/alerts.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<form id="my-deal-alerts" method="post" action="">   <h3 class="bold">My Deal Alerts:</h3>   <a class="unsub-all" href="#">Unsubscribe All</a>   <table>  ');var cols=3;var totalRows=Math.floor((areas.length+(cols-1))/cols);p.push('  ');for(var i=0;i<(totalRows*cols);i=i+cols){p.push('  <tr>   ');for(var j=0;j<cols;j++){p.push('   <td>    ');if((i+j)<areas.length){p.push('    <input id="alert_area',areas[i+j].getId(),'" type="checkbox" checked="checked"     value="',areas[i+j].getId(),'" name="alert_area',areas[i+j].getId(),'">    <label for="alert_area',areas[i+j].getId(),'">',areas[i+j].getName(),'</label>    ');}p.push('   </td>   ');}p.push('  </tr>  ');}p.push('   </table>   <p>    To unsubscribe from one area uncheck and click update at the bottom of this form.    To unsubscribe from all deal alerts click unsubscribe all.   </p>  <div class="call-to-action">   <input class="btn-update" src="/i/btn_update_default.png" name="btn-update" type="image">  </div>  </form><!-- #my-deal-alerts -->  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/alerts/suggested.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<form id="available-deal-alerts" method="post" action="">  <fieldset>   <h3 class="bold">Available Deal Alerts Near Me:</h3>   <p>Based on your current deal alerts we think you might be interested in deals in the following areas.   <br />Select areas and click update.</p>   <table>  ');var cols=3;var totalRows=Math.floor((areas.length+(cols-1))/cols);p.push('  ');for(var i=0;i<(totalRows*cols);i=i+cols){p.push('  <tr>   ');for(var j=0;j<cols;j++){p.push('   <td>    ');if((i+j)<areas.length){p.push('    <input id="suggested_area',areas[i+j].getId(),'" type="checkbox"     value="',areas[i+j].getId(),'" name="',areas[i+j].getId(),'" >    <label for="suggested_area',areas[i+j].getId(),'">',areas[i+j].getName(),'</label>    ');}p.push('   </td>   ');}p.push('  </tr>  ');}p.push('   </table>   <div class="call-to-action">    <input class="btn-update" src="/i/btn_update_default.png" name="btn-update" type="image">   </div><!-- .call-to-action -->  </fieldset>  </form><!-- #available-deal-alerts -->  <hr />  ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/alerts/subscribed.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<h1>Thanks For Subscribing</h1>    <p>You are now subscribed to:</p>    <table>  ');var cols=3;var totalRows=Math.floor((areas.length+(cols-1))/cols);p.push('  ');for(var i=0;i<(totalRows*cols);i=i+cols){p.push('  <tr>   ');for(var j=0;j<cols;j++){p.push('   <td>    ');if((i+j)<areas.length){p.push('     <span>',areas[i+j],'</span>    ');}p.push('   </td>   ');}p.push('  </tr>  ');}p.push('  </table>    <div class="call-to-action">   <input id="btn-ok" src="/i/btn_ok_default.png" name="btn-ok" type="image">  </div>    ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/alerts/subscribedLocal.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<h1>Subscribe?</h1>    <p>You will receive the following alerts:</p>    <table>  ');var cols=3;var totalRows=Math.floor((areas.length+(cols-1))/cols);p.push('  ');for(var i=0;i<(totalRows*cols);i=i+cols){p.push('  <tr>   ');for(var j=0;j<cols;j++){p.push('   <td>    ');if((i+j)<areas.length){p.push('     <span>',areas[i+j].getName(),'</span>    ');}p.push('   </td>   ');}p.push('  </tr>  ');}p.push('  </table>    <div class="call-to-action">   <input class="btn-ok" src="/i/btn_ok_default.png" name="btn-ok" type="image" />   <a href="#">Cancel</a>  </div>    ');}return p.join('');});

MLD.View.loadViewFunction('/dmapi/views/alerts/unsubscribed.jhtml',function(obj){var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('<h1>Unsubscribe?</h1>    <p>You will no longer receive the following alerts:</p>    <table>  ');var cols=3;var totalRows=Math.floor((areas.length+(cols-1))/cols);p.push('  ');for(var i=0;i<(totalRows*cols);i=i+cols){p.push('  <tr>   ');for(var j=0;j<cols;j++){p.push('   <td>    ');if((i+j)<areas.length){p.push('     <span>',areas[i+j].getName(),'</span>    ');}p.push('   </td>   ');}p.push('  </tr>  ');}p.push('  </table>    <div class="call-to-action">   <input class="btn-ok" src="/i/btn_ok_default.png" name="btn-ok" type="image" />   <a href="#">Cancel</a>  </div>    ');}return p.join('');});;MLD.mylifeApiUrl='https://mlapi.mylife.com'})()
