/*!
 * fancyBox - jQuery Plugin
 * version: 2.1.5 (Fri, 14 Jun 2013)
 * @requires jQuery v1.6 or later
 *
 * Examples at http://fancyapps.com/fancybox/
 * License: www.fancyapps.com/fancybox/#license
 *
 * Copyright 2012 Janis Skarnelis - janis@fancyapps.com
 *
 */
(function(window,document,$,undefined){"use strict";var H=$("html"),W=$(window),D=$(document),F=$.fancybox=function(){F.open.apply(this,arguments);},IE=navigator.userAgent.match(/msie/i),didUpdate=null,isTouch=document.createTouch!==undefined,isQuery=function(obj){return obj&&obj.hasOwnProperty&&obj instanceof $;},isString=function(str){return str&&$.type(str)==="string";},isPercentage=function(str){return isString(str)&&str.indexOf('%')>0;},isScrollable=function(el){return(el&&!(el.style.overflow&&el.style.overflow==='hidden')&&((el.clientWidth&&el.scrollWidth>el.clientWidth)||(el.clientHeight&&el.scrollHeight>el.clientHeight)));},getScalar=function(orig,dim){var value=parseInt(orig,10)||0;if(dim&&isPercentage(orig)){value=F.getViewport()[dim]/ 100*value;}
return Math.ceil(value);},getValue=function(value,dim){return getScalar(value,dim)+'px';};$.extend(F,{version:'2.1.5',defaults:{padding:15,margin:20,width:800,height:600,minWidth:100,minHeight:100,maxWidth:9999,maxHeight:9999,pixelRatio:1,autoSize:true,autoHeight:false,autoWidth:false,autoResize:true,autoCenter:!isTouch,fitToView:true,aspectRatio:false,topRatio:0.5,leftRatio:0.5,scrolling:'auto',wrapCSS:'',arrows:true,closeBtn:true,closeClick:false,nextClick:false,mouseWheel:true,autoPlay:false,playSpeed:3000,preload:3,modal:false,loop:true,ajax:{dataType:'html',headers:{'X-fancyBox':true}},iframe:{scrolling:'auto',preload:true},swf:{wmode:'transparent',allowfullscreen:'true',allowscriptaccess:'always'},keys:{next:{13:'left',34:'up',39:'left',40:'up'},prev:{8:'right',33:'down',37:'right',38:'down'},close:[27],play:[32],toggle:[70]},direction:{next:'left',prev:'right'},scrollOutside:true,index:0,type:null,href:null,content:null,title:null,tpl:{wrap:'<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',image:'<img class="fancybox-image" src="{href}" alt="" />',iframe:'<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'+(IE?' allowtransparency="true"':'')+'></iframe>',error:'<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',closeBtn:'<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',next:'<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',prev:'<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'},openEffect:'fade',openSpeed:250,openEasing:'swing',openOpacity:true,openMethod:'zoomIn',closeEffect:'fade',closeSpeed:250,closeEasing:'swing',closeOpacity:true,closeMethod:'zoomOut',nextEffect:'elastic',nextSpeed:250,nextEasing:'swing',nextMethod:'changeIn',prevEffect:'elastic',prevSpeed:250,prevEasing:'swing',prevMethod:'changeOut',helpers:{overlay:true,title:true},onCancel:$.noop,beforeLoad:$.noop,afterLoad:$.noop,beforeShow:$.noop,afterShow:$.noop,beforeChange:$.noop,beforeClose:$.noop,afterClose:$.noop},group:{},opts:{},previous:null,coming:null,current:null,isActive:false,isOpen:false,isOpened:false,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:false},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(group,opts){if(!group){return;}
if(!$.isPlainObject(opts)){opts={};}
if(false===F.close(true)){return;}
if(!$.isArray(group)){group=isQuery(group)?$(group).get():[group];}
$.each(group,function(i,element){var obj={},href,title,content,type,rez,hrefParts,selector;if($.type(element)==="object"){if(element.nodeType){element=$(element);}
if(isQuery(element)){obj={href:element.data('fancybox-href')||element.attr('href'),title:element.data('fancybox-title')||element.attr('title'),isDom:true,element:element};if($.metadata){$.extend(true,obj,element.metadata());}}else{obj=element;}}
href=opts.href||obj.href||(isString(element)?element:null);title=opts.title!==undefined?opts.title:obj.title||'';content=opts.content||obj.content;type=content?'html':(opts.type||obj.type);if(!type&&obj.isDom){type=element.data('fancybox-type');if(!type){rez=element.prop('class').match(/fancybox\.(\w+)/);type=rez?rez[1]:null;}}
if(isString(href)){if(!type){if(F.isImage(href)){type='image';}else if(F.isSWF(href)){type='swf';}else if(href.charAt(0)==='#'){type='inline';}else if(isString(element)){type='html';content=element;}}
if(type==='ajax'){hrefParts=href.split(/\s+/,2);href=hrefParts.shift();selector=hrefParts.shift();}}
if(!content){if(type==='inline'){if(href){content=$(isString(href)?href.replace(/.*(?=#[^\s]+$)/,''):href);}else if(obj.isDom){content=element;}}else if(type==='html'){content=href;}else if(!type&&!href&&obj.isDom){type='inline';content=element;}}
$.extend(obj,{href:href,type:type,content:content,title:title,selector:selector});group[i]=obj;});F.opts=$.extend(true,{},F.defaults,opts);if(opts.keys!==undefined){F.opts.keys=opts.keys?$.extend({},F.defaults.keys,opts.keys):false;}
F.group=group;return F._start(F.opts.index);},cancel:function(){var coming=F.coming;if(!coming||false===F.trigger('onCancel')){return;}
F.hideLoading();if(F.ajaxLoad){F.ajaxLoad.abort();}
F.ajaxLoad=null;if(F.imgPreload){F.imgPreload.onload=F.imgPreload.onerror=null;}
if(coming.wrap){coming.wrap.stop(true,true).trigger('onReset').remove();}
F.coming=null;if(!F.current){F._afterZoomOut(coming);}},close:function(event){F.cancel();if(false===F.trigger('beforeClose')){return;}
F.unbindEvents();if(!F.isActive){return;}
if(!F.isOpen||event===true){$('.fancybox-wrap').stop(true).trigger('onReset').remove();F._afterZoomOut();}else{F.isOpen=F.isOpened=false;F.isClosing=true;$('.fancybox-item, .fancybox-nav').remove();F.wrap.stop(true,true).removeClass('fancybox-opened');F.transitions[F.current.closeMethod]();}},play:function(action){var clear=function(){clearTimeout(F.player.timer);},set=function(){clear();if(F.current&&F.player.isActive){F.player.timer=setTimeout(F.next,F.current.playSpeed);}},stop=function(){clear();D.unbind('.player');F.player.isActive=false;F.trigger('onPlayEnd');},start=function(){if(F.current&&(F.current.loop||F.current.index<F.group.length-1)){F.player.isActive=true;D.bind({'onCancel.player beforeClose.player':stop,'onUpdate.player':set,'beforeLoad.player':clear});set();F.trigger('onPlayStart');}};if(action===true||(!F.player.isActive&&action!==false)){start();}else{stop();}},next:function(direction){var current=F.current;if(current){if(!isString(direction)){direction=current.direction.next;}
F.jumpto(current.index+1,direction,'next');}},prev:function(direction){var current=F.current;if(current){if(!isString(direction)){direction=current.direction.prev;}
F.jumpto(current.index-1,direction,'prev');}},jumpto:function(index,direction,router){var current=F.current;if(!current){return;}
index=getScalar(index);F.direction=direction||current.direction[(index>=current.index?'next':'prev')];F.router=router||'jumpto';if(current.loop){if(index<0){index=current.group.length+(index%current.group.length);}
index=index%current.group.length;}
if(current.group[index]!==undefined){F.cancel();F._start(index);}},reposition:function(e,onlyAbsolute){var current=F.current,wrap=current?current.wrap:null,pos;if(wrap){pos=F._getPosition(onlyAbsolute);if(e&&e.type==='scroll'){delete pos.position;wrap.stop(true,true).animate(pos,200);}else{wrap.css(pos);current.pos=$.extend({},current.dim,pos);}}},update:function(e){var type=(e&&e.type),anyway=!type||type==='orientationchange';if(anyway){clearTimeout(didUpdate);didUpdate=null;}
if(!F.isOpen||didUpdate){return;}
didUpdate=setTimeout(function(){var current=F.current;if(!current||F.isClosing){return;}
F.wrap.removeClass('fancybox-tmp');if(anyway||type==='load'||(type==='resize'&&current.autoResize)){F._setDimension();}
if(!(type==='scroll'&&current.canShrink)){F.reposition(e);}
F.trigger('onUpdate');didUpdate=null;},(anyway&&!isTouch?0:300));},toggle:function(action){if(F.isOpen){F.current.fitToView=$.type(action)==="boolean"?action:!F.current.fitToView;if(isTouch){F.wrap.removeAttr('style').addClass('fancybox-tmp');F.trigger('onUpdate');}
F.update();}},hideLoading:function(){D.unbind('.loading');$('#fancybox-loading').remove();},showLoading:function(){var el,viewport;F.hideLoading();el=$('<div id="fancybox-loading"><div></div></div>').click(F.cancel).appendTo('body');D.bind('keydown.loading',function(e){if((e.which||e.keyCode)===27){e.preventDefault();F.cancel();}});if(!F.defaults.fixed){viewport=F.getViewport();el.css({position:'absolute',top:(viewport.h*0.5)+viewport.y,left:(viewport.w*0.5)+viewport.x});}},getViewport:function(){var locked=(F.current&&F.current.locked)||false,rez={x:W.scrollLeft(),y:W.scrollTop()};if(locked){rez.w=locked[0].clientWidth;rez.h=locked[0].clientHeight;}else{rez.w=isTouch&&window.innerWidth?window.innerWidth:W.width();rez.h=isTouch&&window.innerHeight?window.innerHeight:W.height();}
return rez;},unbindEvents:function(){if(F.wrap&&isQuery(F.wrap)){F.wrap.unbind('.fb');}
D.unbind('.fb');W.unbind('.fb');},bindEvents:function(){var current=F.current,keys;if(!current){return;}
W.bind('orientationchange.fb'+(isTouch?'':' resize.fb')+(current.autoCenter&&!current.locked?' scroll.fb':''),F.update);keys=current.keys;if(keys){D.bind('keydown.fb',function(e){var code=e.which||e.keyCode,target=e.target||e.srcElement;if(code===27&&F.coming){return false;}
if(!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!e.metaKey&&!(target&&(target.type||$(target).is('[contenteditable]')))){$.each(keys,function(i,val){if(current.group.length>1&&val[code]!==undefined){F[i](val[code]);e.preventDefault();return false;}
if($.inArray(code,val)>-1){F[i]();e.preventDefault();return false;}});}});}
if($.fn.mousewheel&&current.mouseWheel){F.wrap.bind('mousewheel.fb',function(e,delta,deltaX,deltaY){var target=e.target||null,parent=$(target),canScroll=false;while(parent.length){if(canScroll||parent.is('.fancybox-skin')||parent.is('.fancybox-wrap')){break;}
canScroll=isScrollable(parent[0]);parent=$(parent).parent();}
if(delta!==0&&!canScroll){if(F.group.length>1&&!current.canShrink){if(deltaY>0||deltaX>0){F.prev(deltaY>0?'down':'left');}else if(deltaY<0||deltaX<0){F.next(deltaY<0?'up':'right');}
e.preventDefault();}}});}},trigger:function(event,o){var ret,obj=o||F.coming||F.current;if(!obj){return;}
if($.isFunction(obj[event])){ret=obj[event].apply(obj,Array.prototype.slice.call(arguments,1));}
if(ret===false){return false;}
if(obj.helpers){$.each(obj.helpers,function(helper,opts){if(opts&&F.helpers[helper]&&$.isFunction(F.helpers[helper][event])){F.helpers[helper][event]($.extend(true,{},F.helpers[helper].defaults,opts),obj);}});}
D.trigger(event);},isImage:function(str){return isString(str)&&str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);},isSWF:function(str){return isString(str)&&str.match(/\.(swf)((\?|#).*)?$/i);},_start:function(index){var coming={},obj,href,type,margin,padding;index=getScalar(index);obj=F.group[index]||null;if(!obj){return false;}
coming=$.extend(true,{},F.opts,obj);margin=coming.margin;padding=coming.padding;if($.type(margin)==='number'){coming.margin=[margin,margin,margin,margin];}
if($.type(padding)==='number'){coming.padding=[padding,padding,padding,padding];}
if(coming.modal){$.extend(true,coming,{closeBtn:false,closeClick:false,nextClick:false,arrows:false,mouseWheel:false,keys:null,helpers:{overlay:{closeClick:false}}});}
if(coming.autoSize){coming.autoWidth=coming.autoHeight=true;}
if(coming.width==='auto'){coming.autoWidth=true;}
if(coming.height==='auto'){coming.autoHeight=true;}
coming.group=F.group;coming.index=index;F.coming=coming;if(false===F.trigger('beforeLoad')){F.coming=null;return;}
type=coming.type;href=coming.href;if(!type){F.coming=null;if(F.current&&F.router&&F.router!=='jumpto'){F.current.index=index;return F[F.router](F.direction);}
return false;}
F.isActive=true;if(type==='image'||type==='swf'){coming.autoHeight=coming.autoWidth=false;coming.scrolling='visible';}
if(type==='image'){coming.aspectRatio=true;}
if(type==='iframe'&&isTouch){coming.scrolling='scroll';}
coming.wrap=$(coming.tpl.wrap).addClass('fancybox-'+(isTouch?'mobile':'desktop')+' fancybox-type-'+type+' fancybox-tmp '+coming.wrapCSS).appendTo(coming.parent||'body');$.extend(coming,{skin:$('.fancybox-skin',coming.wrap),outer:$('.fancybox-outer',coming.wrap),inner:$('.fancybox-inner',coming.wrap)});$.each(["Top","Right","Bottom","Left"],function(i,v){coming.skin.css('padding'+v,getValue(coming.padding[i]));});F.trigger('onReady');if(type==='inline'||type==='html'){if(!coming.content||!coming.content.length){return F._error('content');}}else if(!href){return F._error('href');}
if(type==='image'){F._loadImage();}else if(type==='ajax'){F._loadAjax();}else if(type==='iframe'){F._loadIframe();}else{F._afterLoad();}},_error:function(type){$.extend(F.coming,{type:'html',autoWidth:true,autoHeight:true,minWidth:0,minHeight:0,scrolling:'no',hasError:type,content:F.coming.tpl.error});F._afterLoad();},_loadImage:function(){var img=F.imgPreload=new Image();img.onload=function(){this.onload=this.onerror=null;F.coming.width=this.width / F.opts.pixelRatio;F.coming.height=this.height / F.opts.pixelRatio;F._afterLoad();};img.onerror=function(){this.onload=this.onerror=null;F._error('image');};img.src=F.coming.href;if(img.complete!==true){F.showLoading();}},_loadAjax:function(){var coming=F.coming;F.showLoading();F.ajaxLoad=$.ajax($.extend({},coming.ajax,{url:coming.href,error:function(jqXHR,textStatus){if(F.coming&&textStatus!=='abort'){F._error('ajax',jqXHR);}else{F.hideLoading();}},success:function(data,textStatus){if(textStatus==='success'){coming.content=data;F._afterLoad();}}}));},_loadIframe:function(){var coming=F.coming,iframe=$(coming.tpl.iframe.replace(/\{rnd\}/g,new Date().getTime())).attr('scrolling',isTouch?'auto':coming.iframe.scrolling).attr('src',coming.href);$(coming.wrap).bind('onReset',function(){try{$(this).find('iframe').hide().attr('src','//about:blank').end().empty();}catch(e){}});if(coming.iframe.preload){F.showLoading();iframe.one('load',function(){$(this).data('ready',1);if(!isTouch){$(this).bind('load.fb',F.update);}
$(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show();F._afterLoad();});}
coming.content=iframe.appendTo(coming.inner);if(!coming.iframe.preload){F._afterLoad();}},_preloadImages:function(){var group=F.group,current=F.current,len=group.length,cnt=current.preload?Math.min(current.preload,len-1):0,item,i;for(i=1;i<=cnt;i+=1){item=group[(current.index+i)%len];if(item.type==='image'&&item.href){new Image().src=item.href;}}},_afterLoad:function(){var coming=F.coming,previous=F.current,placeholder='fancybox-placeholder',current,content,type,scrolling,href,embed;F.hideLoading();if(!coming||F.isActive===false){return;}
if(false===F.trigger('afterLoad',coming,previous)){coming.wrap.stop(true).trigger('onReset').remove();F.coming=null;return;}
if(previous){F.trigger('beforeChange',previous);previous.wrap.stop(true).removeClass('fancybox-opened').find('.fancybox-item, .fancybox-nav').remove();}
F.unbindEvents();current=coming;content=coming.content;type=coming.type;scrolling=coming.scrolling;$.extend(F,{wrap:current.wrap,skin:current.skin,outer:current.outer,inner:current.inner,current:current,previous:previous});href=current.href;switch(type){case'inline':case'ajax':case'html':if(current.selector){content=$('<div>').html(content).find(current.selector);}else if(isQuery(content)){if(!content.data(placeholder)){content.data(placeholder,$('<div class="'+placeholder+'"></div>').insertAfter(content).hide());}
content=content.show().detach();current.wrap.bind('onReset',function(){if($(this).find(content).length){content.hide().replaceAll(content.data(placeholder)).data(placeholder,false);}});}
break;case'image':content=current.tpl.image.replace('{href}',href);break;case'swf':content='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+href+'"></param>';embed='';$.each(current.swf,function(name,val){content+='<param name="'+name+'" value="'+val+'"></param>';embed+=' '+name+'="'+val+'"';});content+='<embed src="'+href+'" type="application/x-shockwave-flash" width="100%" height="100%"'+embed+'></embed></object>';break;}
if(!(isQuery(content)&&content.parent().is(current.inner))){current.inner.append(content);}
F.trigger('beforeShow');current.inner.css('overflow',scrolling==='yes'?'scroll':(scrolling==='no'?'hidden':scrolling));F._setDimension();F.reposition();F.isOpen=false;F.coming=null;F.bindEvents();if(!F.isOpened){$('.fancybox-wrap').not(current.wrap).stop(true).trigger('onReset').remove();}else if(previous.prevMethod){F.transitions[previous.prevMethod]();}
F.transitions[F.isOpened?current.nextMethod:current.openMethod]();F._preloadImages();},_setDimension:function(){var viewport=F.getViewport(),steps=0,canShrink=false,canExpand=false,wrap=F.wrap,skin=F.skin,inner=F.inner,current=F.current,width=current.width,height=current.height,minWidth=current.minWidth,minHeight=current.minHeight,maxWidth=current.maxWidth,maxHeight=current.maxHeight,scrolling=current.scrolling,scrollOut=current.scrollOutside?current.scrollbarWidth:0,margin=current.margin,wMargin=getScalar(margin[1]+margin[3]),hMargin=getScalar(margin[0]+margin[2]),wPadding,hPadding,wSpace,hSpace,origWidth,origHeight,origMaxWidth,origMaxHeight,ratio,width_,height_,maxWidth_,maxHeight_,iframe,body;wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp');wPadding=getScalar(skin.outerWidth(true)-skin.width());hPadding=getScalar(skin.outerHeight(true)-skin.height());wSpace=wMargin+wPadding;hSpace=hMargin+hPadding;origWidth=isPercentage(width)?(viewport.w-wSpace)*getScalar(width)/ 100:width;origHeight=isPercentage(height)?(viewport.h-hSpace)*getScalar(height)/ 100:height;if(current.type==='iframe'){iframe=current.content;if(current.autoHeight&&iframe.data('ready')===1){try{if(iframe[0].contentWindow.document.location){inner.width(origWidth).height(9999);body=iframe.contents().find('body');if(scrollOut){body.css('overflow-x','hidden');}
origHeight=body.outerHeight(true);}}catch(e){}}}else if(current.autoWidth||current.autoHeight){inner.addClass('fancybox-tmp');if(!current.autoWidth){inner.width(origWidth);}
if(!current.autoHeight){inner.height(origHeight);}
if(current.autoWidth){origWidth=inner.width();}
if(current.autoHeight){origHeight=inner.height();}
inner.removeClass('fancybox-tmp');}
width=getScalar(origWidth);height=getScalar(origHeight);ratio=origWidth / origHeight;minWidth=getScalar(isPercentage(minWidth)?getScalar(minWidth,'w')-wSpace:minWidth);maxWidth=getScalar(isPercentage(maxWidth)?getScalar(maxWidth,'w')-wSpace:maxWidth);minHeight=getScalar(isPercentage(minHeight)?getScalar(minHeight,'h')-hSpace:minHeight);maxHeight=getScalar(isPercentage(maxHeight)?getScalar(maxHeight,'h')-hSpace:maxHeight);origMaxWidth=maxWidth;origMaxHeight=maxHeight;if(current.fitToView){maxWidth=Math.min(viewport.w-wSpace,maxWidth);maxHeight=Math.min(viewport.h-hSpace,maxHeight);}
maxWidth_=viewport.w-wMargin;maxHeight_=viewport.h-hMargin;if(current.aspectRatio){if(width>maxWidth){width=maxWidth;height=getScalar(width / ratio);}
if(height>maxHeight){height=maxHeight;width=getScalar(height*ratio);}
if(width<minWidth){width=minWidth;height=getScalar(width / ratio);}
if(height<minHeight){height=minHeight;width=getScalar(height*ratio);}}else{width=Math.max(minWidth,Math.min(width,maxWidth));if(current.autoHeight&&current.type!=='iframe'){inner.width(width);height=inner.height();}
height=Math.max(minHeight,Math.min(height,maxHeight));}
if(current.fitToView){inner.width(width).height(height);wrap.width(width+wPadding);width_=wrap.width();height_=wrap.height();if(current.aspectRatio){while((width_>maxWidth_||height_>maxHeight_)&&width>minWidth&&height>minHeight){if(steps++>19){break;}
height=Math.max(minHeight,Math.min(maxHeight,height-10));width=getScalar(height*ratio);if(width<minWidth){width=minWidth;height=getScalar(width / ratio);}
if(width>maxWidth){width=maxWidth;height=getScalar(width / ratio);}
inner.width(width).height(height);wrap.width(width+wPadding);width_=wrap.width();height_=wrap.height();}}else{width=Math.max(minWidth,Math.min(width,width-(width_-maxWidth_)));height=Math.max(minHeight,Math.min(height,height-(height_-maxHeight_)));}}
if(scrollOut&&scrolling==='auto'&&height<origHeight&&(width+wPadding+scrollOut)<maxWidth_){width+=scrollOut;}
inner.width(width).height(height);wrap.width(width+wPadding);width_=wrap.width();height_=wrap.height();canShrink=(width_>maxWidth_||height_>maxHeight_)&&width>minWidth&&height>minHeight;canExpand=current.aspectRatio?(width<origMaxWidth&&height<origMaxHeight&&width<origWidth&&height<origHeight):((width<origMaxWidth||height<origMaxHeight)&&(width<origWidth||height<origHeight));$.extend(current,{dim:{width:getValue(width_),height:getValue(height_)},origWidth:origWidth,origHeight:origHeight,canShrink:canShrink,canExpand:canExpand,wPadding:wPadding,hPadding:hPadding,wrapSpace:height_-skin.outerHeight(true),skinSpace:skin.height()-height});if(!iframe&&current.autoHeight&&height>minHeight&&height<maxHeight&&!canExpand){inner.height('auto');}},_getPosition:function(onlyAbsolute){var current=F.current,viewport=F.getViewport(),margin=current.margin,width=F.wrap.width()+margin[1]+margin[3],height=F.wrap.height()+margin[0]+margin[2],rez={position:'absolute',top:margin[0],left:margin[3]};if(current.autoCenter&&current.fixed&&!onlyAbsolute&&height<=viewport.h&&width<=viewport.w){rez.position='fixed';}else if(!current.locked){rez.top+=viewport.y;rez.left+=viewport.x;}
rez.top=getValue(Math.max(rez.top,rez.top+((viewport.h-height)*current.topRatio)));rez.left=getValue(Math.max(rez.left,rez.left+((viewport.w-width)*current.leftRatio)));return rez;},_afterZoomIn:function(){var current=F.current;if(!current){return;}
F.isOpen=F.isOpened=true;F.wrap.css('overflow','visible').addClass('fancybox-opened');F.update();if(current.closeClick||(current.nextClick&&F.group.length>1)){F.inner.css('cursor','pointer').bind('click.fb',function(e){if(!$(e.target).is('a')&&!$(e.target).parent().is('a')){e.preventDefault();F[current.closeClick?'close':'next']();}});}
if(current.closeBtn){$(current.tpl.closeBtn).appendTo(F.skin).bind('click.fb',function(e){e.preventDefault();F.close();});}
if(current.arrows&&F.group.length>1){if(current.loop||current.index>0){$(current.tpl.prev).appendTo(F.outer).bind('click.fb',F.prev);}
if(current.loop||current.index<F.group.length-1){$(current.tpl.next).appendTo(F.outer).bind('click.fb',F.next);}}
F.trigger('afterShow');if(!current.loop&&current.index===current.group.length-1){F.play(false);}else if(F.opts.autoPlay&&!F.player.isActive){F.opts.autoPlay=false;F.play();}},_afterZoomOut:function(obj){obj=obj||F.current;$('.fancybox-wrap').trigger('onReset').remove();$.extend(F,{group:{},opts:{},router:false,current:null,isActive:false,isOpened:false,isOpen:false,isClosing:false,wrap:null,skin:null,outer:null,inner:null});F.trigger('afterClose',obj);}});F.transitions={getOrigPosition:function(){var current=F.current,element=current.element,orig=current.orig,pos={},width=50,height=50,hPadding=current.hPadding,wPadding=current.wPadding,viewport=F.getViewport();if(!orig&&current.isDom&&element.is(':visible')){orig=element.find('img:first');if(!orig.length){orig=element;}}
if(isQuery(orig)){pos=orig.offset();if(orig.is('img')){width=orig.outerWidth();height=orig.outerHeight();}}else{pos.top=viewport.y+(viewport.h-height)*current.topRatio;pos.left=viewport.x+(viewport.w-width)*current.leftRatio;}
if(F.wrap.css('position')==='fixed'||current.locked){pos.top-=viewport.y;pos.left-=viewport.x;}
pos={top:getValue(pos.top-hPadding*current.topRatio),left:getValue(pos.left-wPadding*current.leftRatio),width:getValue(width+wPadding),height:getValue(height+hPadding)};return pos;},step:function(now,fx){var ratio,padding,value,prop=fx.prop,current=F.current,wrapSpace=current.wrapSpace,skinSpace=current.skinSpace;if(prop==='width'||prop==='height'){ratio=fx.end===fx.start?1:(now-fx.start)/(fx.end-fx.start);if(F.isClosing){ratio=1-ratio;}
padding=prop==='width'?current.wPadding:current.hPadding;value=now-padding;F.skin[prop](getScalar(prop==='width'?value:value-(wrapSpace*ratio)));F.inner[prop](getScalar(prop==='width'?value:value-(wrapSpace*ratio)-(skinSpace*ratio)));}},zoomIn:function(){var current=F.current,startPos=current.pos,effect=current.openEffect,elastic=effect==='elastic',endPos=$.extend({opacity:1},startPos);delete endPos.position;if(elastic){startPos=this.getOrigPosition();if(current.openOpacity){startPos.opacity=0.1;}}else if(effect==='fade'){startPos.opacity=0.1;}
F.wrap.css(startPos).animate(endPos,{duration:effect==='none'?0:current.openSpeed,easing:current.openEasing,step:elastic?this.step:null,complete:F._afterZoomIn});},zoomOut:function(){var current=F.current,effect=current.closeEffect,elastic=effect==='elastic',endPos={opacity:0.1};if(elastic){endPos=this.getOrigPosition();if(current.closeOpacity){endPos.opacity=0.1;}}
F.wrap.animate(endPos,{duration:effect==='none'?0:current.closeSpeed,easing:current.closeEasing,step:elastic?this.step:null,complete:F._afterZoomOut});},changeIn:function(){var current=F.current,effect=current.nextEffect,startPos=current.pos,endPos={opacity:1},direction=F.direction,distance=200,field;startPos.opacity=0.1;if(effect==='elastic'){field=direction==='down'||direction==='up'?'top':'left';if(direction==='down'||direction==='right'){startPos[field]=getValue(getScalar(startPos[field])-distance);endPos[field]='+='+distance+'px';}else{startPos[field]=getValue(getScalar(startPos[field])+distance);endPos[field]='-='+distance+'px';}}
if(effect==='none'){F._afterZoomIn();}else{F.wrap.css(startPos).animate(endPos,{duration:current.nextSpeed,easing:current.nextEasing,complete:F._afterZoomIn});}},changeOut:function(){var previous=F.previous,effect=previous.prevEffect,endPos={opacity:0.1},direction=F.direction,distance=200;if(effect==='elastic'){endPos[direction==='down'||direction==='up'?'top':'left']=(direction==='up'||direction==='left'?'-':'+')+'='+distance+'px';}
previous.wrap.animate(endPos,{duration:effect==='none'?0:previous.prevSpeed,easing:previous.prevEasing,complete:function(){$(this).trigger('onReset').remove();}});}};F.helpers.overlay={defaults:{closeClick:true,speedOut:200,showEarly:true,css:{},locked:!isTouch,fixed:true},overlay:null,fixed:false,el:$('html'),create:function(opts){opts=$.extend({},this.defaults,opts);if(this.overlay){this.close();}
this.overlay=$('<div class="fancybox-overlay"></div>').appendTo(F.coming?F.coming.parent:opts.parent);this.fixed=false;if(opts.fixed&&F.defaults.fixed){this.overlay.addClass('fancybox-overlay-fixed');this.fixed=true;}},open:function(opts){var that=this;opts=$.extend({},this.defaults,opts);if(this.overlay){this.overlay.unbind('.overlay').width('auto').height('auto');}else{this.create(opts);}
if(!this.fixed){W.bind('resize.overlay',$.proxy(this.update,this));this.update();}
if(opts.closeClick){this.overlay.bind('click.overlay',function(e){if($(e.target).hasClass('fancybox-overlay')){if(F.isActive){F.close();}else{that.close();}
return false;}});}
this.overlay.css(opts.css).show();},close:function(){var scrollV,scrollH;W.unbind('resize.overlay');if(this.el.hasClass('fancybox-lock')){$('.fancybox-margin').removeClass('fancybox-margin');scrollV=W.scrollTop();scrollH=W.scrollLeft();this.el.removeClass('fancybox-lock');W.scrollTop(scrollV).scrollLeft(scrollH);}
$('.fancybox-overlay').remove().hide();$.extend(this,{overlay:null,fixed:false});},update:function(){var width='100%',offsetWidth;this.overlay.width(width).height('100%');if(IE){offsetWidth=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(D.width()>offsetWidth){width=D.width();}}else if(D.width()>W.width()){width=D.width();}
this.overlay.width(width).height(D.height());},onReady:function(opts,obj){var overlay=this.overlay;$('.fancybox-overlay').stop(true,true);if(!overlay){this.create(opts);}
if(opts.locked&&this.fixed&&obj.fixed){if(!overlay){this.margin=D.height()>W.height()?$('html').css('margin-right').replace("px",""):false;}
obj.locked=this.overlay.append(obj.wrap);obj.fixed=false;}
if(opts.showEarly===true){this.beforeShow.apply(this,arguments);}},beforeShow:function(opts,obj){var scrollV,scrollH;if(obj.locked){if(this.margin!==false){$('*').filter(function(){return($(this).css('position')==='fixed'&&!$(this).hasClass("fancybox-overlay")&&!$(this).hasClass("fancybox-wrap"));}).addClass('fancybox-margin');this.el.addClass('fancybox-margin');}
scrollV=W.scrollTop();scrollH=W.scrollLeft();this.el.addClass('fancybox-lock');W.scrollTop(scrollV).scrollLeft(scrollH);}
this.open(opts);},onUpdate:function(){if(!this.fixed){this.update();}},afterClose:function(opts){if(this.overlay&&!F.coming){this.overlay.fadeOut(opts.speedOut,$.proxy(this.close,this));}}};F.helpers.title={defaults:{type:'float',position:'bottom'},beforeShow:function(opts){var current=F.current,text=current.title,type=opts.type,title,target;if($.isFunction(text)){text=text.call(current.element,current);}
if(!isString(text)||$.trim(text)===''){return;}
title=$('<div class="fancybox-title fancybox-title-'+type+'-wrap">'+text+'</div>');switch(type){case'inside':target=F.skin;break;case'outside':target=F.wrap;break;case'over':target=F.inner;break;default:target=F.skin;title.appendTo('body');if(IE){title.width(title.width());}
title.wrapInner('<span class="child"></span>');F.current.margin[2]+=Math.abs(getScalar(title.css('margin-bottom')));break;}
title[(opts.position==='top'?'prependTo':'appendTo')](target);}};$.fn.fancybox=function(options){var index,that=$(this),selector=this.selector||'',run=function(e){var what=$(this).blur(),idx=index,relType,relVal;if(!(e.ctrlKey||e.altKey||e.shiftKey||e.metaKey)&&!what.is('.fancybox-wrap')){relType=options.groupAttr||'data-fancybox-group';relVal=what.attr(relType);if(!relVal){relType='rel';relVal=what.get(0)[relType];}
if(relVal&&relVal!==''&&relVal!=='nofollow'){what=selector.length?$(selector):that;what=what.filter('['+relType+'="'+relVal+'"]');idx=what.index(this);}
options.index=idx;if(F.open(what,options)!==false){e.preventDefault();}}};options=options||{};index=options.index||0;if(!selector||options.live===false){that.unbind('click.fb-start').bind('click.fb-start',run);}else{D.undelegate(selector,'click.fb-start').delegate(selector+":not('.fancybox-item, .fancybox-nav')",'click.fb-start',run);}
this.filter('[data-fancybox-start=1]').trigger('click');return this;};D.ready(function(){var w1,w2;if($.scrollbarWidth===undefined){$.scrollbarWidth=function(){var parent=$('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'),child=parent.children(),width=child.innerWidth()-child.height(99).innerWidth();parent.remove();return width;};}
if($.support.fixedPosition===undefined){$.support.fixedPosition=(function(){var elem=$('<div style="position:fixed;top:20px;"></div>').appendTo('body'),fixed=(elem[0].offsetTop===20||elem[0].offsetTop===15);elem.remove();return fixed;}());}
$.extend(F.defaults,{scrollbarWidth:$.scrollbarWidth(),fixed:$.support.fixedPosition,parent:$('body')});w1=$(window).width();H.addClass('fancybox-lock-test');w2=$(window).width();H.removeClass('fancybox-lock-test');$("<style type='text/css'>.fancybox-margin{margin-right:"+(w2-w1)+"px;}</style>").appendTo("head");});}(window,document,jQuery));
if(typeof module!=="undefined"&&typeof exports!=="undefined"&&module.exports===exports){module.exports='ui.router';}
(function(window,angular,undefined){'use strict';var isDefined=angular.isDefined,isFunction=angular.isFunction,isString=angular.isString,isObject=angular.isObject,isArray=angular.isArray,forEach=angular.forEach,extend=angular.extend,copy=angular.copy;function inherit(parent,extra){return extend(new(extend(function(){},{prototype:parent}))(),extra);}
function merge(dst){forEach(arguments,function(obj){if(obj!==dst){forEach(obj,function(value,key){if(!dst.hasOwnProperty(key))dst[key]=value;});}});return dst;}
function ancestors(first,second){var path=[];for(var n in first.path){if(first.path[n]!==second.path[n])break;path.push(first.path[n]);}
return path;}
function keys(object){if(Object.keys){return Object.keys(object);}
var result=[];angular.forEach(object,function(val,key){result.push(key);});return result;}
function arraySearch(array,value){if(Array.prototype.indexOf){return array.indexOf(value,Number(arguments[2])||0);}
var len=array.length>>>0,from=Number(arguments[2])||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0)from+=len;for(;from<len;from++){if(from in array&&array[from]===value)return from;}
return-1;}
function inheritParams(currentParams,newParams,$current,$to){var parents=ancestors($current,$to),parentParams,inherited={},inheritList=[];for(var i in parents){if(!parents[i].params||!parents[i].params.length)continue;parentParams=parents[i].params;for(var j in parentParams){if(arraySearch(inheritList,parentParams[j])>=0)continue;inheritList.push(parentParams[j]);inherited[parentParams[j]]=currentParams[parentParams[j]];}}
return extend({},inherited,newParams);}
function normalize(keys,values){var normalized={};forEach(keys,function(name){var value=values[name];normalized[name]=(value!=null)?String(value):null;});return normalized;}
function equalForKeys(a,b,keys){if(!keys){keys=[];for(var n in a)keys.push(n);}
for(var i=0;i<keys.length;i++){var k=keys[i];if(a[k]!=b[k])return false;}
return true;}
function filterByKeys(keys,values){var filtered={};forEach(keys,function(name){filtered[name]=values[name];});return filtered;}
angular.module('ui.router.util',['ng']);angular.module('ui.router.router',['ui.router.util']);angular.module('ui.router.state',['ui.router.router','ui.router.util']);angular.module('ui.router',['ui.router.state']);angular.module('ui.router.compat',['ui.router']);$Resolve.$inject=['$q','$injector'];function $Resolve($q,$injector){var VISIT_IN_PROGRESS=1,VISIT_DONE=2,NOTHING={},NO_DEPENDENCIES=[],NO_LOCALS=NOTHING,NO_PARENT=extend($q.when(NOTHING),{$$promises:NOTHING,$$values:NOTHING});this.study=function(invocables){if(!isObject(invocables))throw new Error("'invocables' must be an object");var plan=[],cycle=[],visited={};function visit(value,key){if(visited[key]===VISIT_DONE)return;cycle.push(key);if(visited[key]===VISIT_IN_PROGRESS){cycle.splice(0,cycle.indexOf(key));throw new Error("Cyclic dependency: "+cycle.join(" -> "));}
visited[key]=VISIT_IN_PROGRESS;if(isString(value)){plan.push(key,[function(){return $injector.get(value);}],NO_DEPENDENCIES);}else{var params=$injector.annotate(value);forEach(params,function(param){if(param!==key&&invocables.hasOwnProperty(param))visit(invocables[param],param);});plan.push(key,value,params);}
cycle.pop();visited[key]=VISIT_DONE;}
forEach(invocables,visit);invocables=cycle=visited=null;function isResolve(value){return isObject(value)&&value.then&&value.$$promises;}
return function(locals,parent,self){if(isResolve(locals)&&self===undefined){self=parent;parent=locals;locals=null;}
if(!locals)locals=NO_LOCALS;else if(!isObject(locals)){throw new Error("'locals' must be an object");}
if(!parent)parent=NO_PARENT;else if(!isResolve(parent)){throw new Error("'parent' must be a promise returned by $resolve.resolve()");}
var resolution=$q.defer(),result=resolution.promise,promises=result.$$promises={},values=extend({},locals),wait=1+plan.length/3,merged=false;function done(){if(!--wait){if(!merged)merge(values,parent.$$values);result.$$values=values;result.$$promises=true;resolution.resolve(values);}}
function fail(reason){result.$$failure=reason;resolution.reject(reason);}
if(isDefined(parent.$$failure)){fail(parent.$$failure);return result;}
if(parent.$$values){merged=merge(values,parent.$$values);done();}else{extend(promises,parent.$$promises);parent.then(done,fail);}
for(var i=0,ii=plan.length;i<ii;i+=3){if(locals.hasOwnProperty(plan[i]))done();else invoke(plan[i],plan[i+1],plan[i+2]);}
function invoke(key,invocable,params){var invocation=$q.defer(),waitParams=0;function onfailure(reason){invocation.reject(reason);fail(reason);}
forEach(params,function(dep){if(promises.hasOwnProperty(dep)&&!locals.hasOwnProperty(dep)){waitParams++;promises[dep].then(function(result){values[dep]=result;if(!(--waitParams))proceed();},onfailure);}});if(!waitParams)proceed();function proceed(){if(isDefined(result.$$failure))return;try{invocation.resolve($injector.invoke(invocable,self,values));invocation.promise.then(function(result){values[key]=result;done();},onfailure);}catch(e){onfailure(e);}}
promises[key]=invocation.promise;}
return result;};};this.resolve=function(invocables,locals,parent,self){return this.study(invocables)(locals,parent,self);};}
angular.module('ui.router.util').service('$resolve',$Resolve);$TemplateFactory.$inject=['$http','$templateCache','$injector'];function $TemplateFactory($http,$templateCache,$injector){this.fromConfig=function(config,params,locals){return(isDefined(config.template)?this.fromString(config.template,params):isDefined(config.templateUrl)?this.fromUrl(config.templateUrl,params):isDefined(config.templateProvider)?this.fromProvider(config.templateProvider,params,locals):null);};this.fromString=function(template,params){return isFunction(template)?template(params):template;};this.fromUrl=function(url,params){if(isFunction(url))url=url(params);if(url==null)return null;else return $http.get(url,{cache:$templateCache}).then(function(response){return response.data;});};this.fromProvider=function(provider,params,locals){return $injector.invoke(provider,null,locals||{params:params});};}
angular.module('ui.router.util').service('$templateFactory',$TemplateFactory);function UrlMatcher(pattern){var placeholder=/([:*])(\w+)\??|\{(\w+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}\??/g,names={},compiled='^',last=0,m,segments=this.segments=[],params=this.params=[],optional=this.optional={};function addParameter(id){if(!/^\w+(-+\w+)*$/.test(id))throw new Error("Invalid parameter name '"+id+"' in pattern '"+pattern+"'");if(names[id])throw new Error("Duplicate parameter name '"+id+"' in pattern '"+pattern+"'");names[id]=true;params.push(id);}
function quoteRegExp(string){return string.replace(/[\\\[\]\^$*+?.()|{}]/g,"\\$&");}
this.source=pattern;var id,regexp,segment;while((m=placeholder.exec(pattern))){id=m[2]||m[3];regexp=m[4]||(m[1]=='*'?'.*':'[^/]*');segment=pattern.substring(last,m.index);if(segment.indexOf('?')>=0)break;if(m[0].slice(-1)==='?')optional[id]=true;if(optional[id]&&segment.slice(-1)==='/')
{compiled+=quoteRegExp(segment.slice(0,-1))+'(?:\/('+regexp+'))?';}
else
{compiled+=quoteRegExp(segment)+'('+regexp+')';}
addParameter(id);segments.push(segment);last=placeholder.lastIndex;}
segment=pattern.substring(last);var i=segment.indexOf('?');if(i>=0){var search=this.sourceSearch=segment.substring(i);segment=segment.substring(0,i);this.sourcePath=pattern.substring(0,last+i);forEach(search.substring(1).split(/[&?]/),addParameter);}else{this.sourcePath=pattern;this.sourceSearch='';}
compiled+=quoteRegExp(segment)+'$';segments.push(segment);this.regexp=new RegExp(compiled);this.prefix=segments[0];}
UrlMatcher.prototype.concat=function(pattern){return new UrlMatcher(this.sourcePath+pattern+this.sourceSearch);};UrlMatcher.prototype.toString=function(){return this.source;};UrlMatcher.prototype.exec=function(path,searchParams){var m=this.regexp.exec(path);if(!m)return null;var params=this.params,nTotal=params.length,nPath=this.segments.length-1,values={},i;if(nPath!==m.length-1)throw new Error("Unbalanced capture group in route '"+this.source+"'");for(i=0;i<nPath;i++)values[params[i]]=m[i+1]||'';for(;i<nTotal;i++)values[params[i]]=searchParams[params[i]];return values;};UrlMatcher.prototype.parameters=function(){return this.params;};UrlMatcher.prototype.format=function(values){var segments=this.segments,params=this.params,optional=this.optional;if(!values)return segments.join('');var nPath=segments.length-1,nTotal=params.length,result=segments[0],i,search,value;for(i=0;i<nPath;i++){value=values[params[i]];if(value!=null)result+=encodeURIComponent(value);if(optional[params[i]]&&result.slice(-1)=='/'&&segments[i+1].slice(0,1)=='/')
{result+=segments[i+1].slice(1);}
else
{result+=segments[i+1];}}
for(;i<nTotal;i++){value=values[params[i]];if(value!=null){result+=(search?'&':'?')+params[i]+'='+encodeURIComponent(value);search=true;}}
return result;};function $UrlMatcherFactory(){this.compile=function(pattern){return new UrlMatcher(pattern);};this.isMatcher=function(o){return isObject(o)&&isFunction(o.exec)&&isFunction(o.format)&&isFunction(o.concat);};this.$get=function(){return this;};}
angular.module('ui.router.util').provider('$urlMatcherFactory',$UrlMatcherFactory);$UrlRouterProvider.$inject=['$urlMatcherFactoryProvider'];function $UrlRouterProvider($urlMatcherFactory){var rules=[],otherwise=null;function regExpPrefix(re){var prefix=/^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);return(prefix!=null)?prefix[1].replace(/\\(.)/g,"$1"):'';}
function interpolate(pattern,match){return pattern.replace(/\$(\$|\d{1,2})/,function(m,what){return match[what==='$'?0:Number(what)];});}
this.rule=function(rule){if(!isFunction(rule))throw new Error("'rule' must be a function");rules.push(rule);return this;};this.otherwise=function(rule){if(isString(rule)){var redirect=rule;rule=function(){return redirect;};}
else if(!isFunction(rule))throw new Error("'rule' must be a function");otherwise=rule;return this;};function handleIfMatch($injector,handler,match){if(!match)return false;var result=$injector.invoke(handler,handler,{$match:match});return isDefined(result)?result:true;}
this.when=function(what,handler){var redirect,handlerIsString=isString(handler);if(isString(what))what=$urlMatcherFactory.compile(what);if(!handlerIsString&&!isFunction(handler)&&!isArray(handler))
throw new Error("invalid 'handler' in when()");var strategies={matcher:function(what,handler){if(handlerIsString){redirect=$urlMatcherFactory.compile(handler);handler=['$match',function($match){return redirect.format($match);}];}
return extend(function($injector,$location){return handleIfMatch($injector,handler,what.exec($location.path(),$location.search()));},{prefix:isString(what.prefix)?what.prefix:''});},regex:function(what,handler){if(what.global||what.sticky)throw new Error("when() RegExp must not be global or sticky");if(handlerIsString){redirect=handler;handler=['$match',function($match){return interpolate(redirect,$match);}];}
return extend(function($injector,$location){return handleIfMatch($injector,handler,what.exec($location.path()));},{prefix:regExpPrefix(what)});}};var check={matcher:$urlMatcherFactory.isMatcher(what),regex:what instanceof RegExp};for(var n in check){if(check[n]){return this.rule(strategies[n](what,handler));}}
throw new Error("invalid 'what' in when()");};this.$get=['$location','$rootScope','$injector',function($location,$rootScope,$injector){function update(evt){if(evt&&evt.defaultPrevented)return;function check(rule){var handled=rule($injector,$location);if(handled){if(isString(handled))$location.replace().url(handled);return true;}
return false;}
var n=rules.length,i;for(i=0;i<n;i++){if(check(rules[i]))return;}
if(otherwise)check(otherwise);}
$rootScope.$on('$locationChangeSuccess',update);return{sync:function(){update();}};}];}
angular.module('ui.router.router').provider('$urlRouter',$UrlRouterProvider);$StateProvider.$inject=['$urlRouterProvider','$urlMatcherFactoryProvider','$locationProvider'];function $StateProvider($urlRouterProvider,$urlMatcherFactory,$locationProvider){var root,states={},$state,queue={},abstractKey='abstract';var stateBuilder={parent:function(state){if(isDefined(state.parent)&&state.parent)return findState(state.parent);var compositeName=/^(.+)\.[^.]+$/.exec(state.name);return compositeName?findState(compositeName[1]):root;},data:function(state){if(state.parent&&state.parent.data){state.data=state.self.data=extend({},state.parent.data,state.data);}
return state.data;},url:function(state){var url=state.url;if(isString(url)){if(url.charAt(0)=='^'){return $urlMatcherFactory.compile(url.substring(1));}
return(state.parent.navigable||root).url.concat(url);}
if($urlMatcherFactory.isMatcher(url)||url==null){return url;}
throw new Error("Invalid url '"+url+"' in state '"+state+"'");},navigable:function(state){return state.url?state:(state.parent?state.parent.navigable:null);},params:function(state){if(!state.params){return state.url?state.url.parameters():state.parent.params;}
if(!isArray(state.params))throw new Error("Invalid params in state '"+state+"'");if(state.url)throw new Error("Both params and url specicified in state '"+state+"'");return state.params;},views:function(state){var views={};forEach(isDefined(state.views)?state.views:{'':state},function(view,name){if(name.indexOf('@')<0)name+='@'+state.parent.name;views[name]=view;});return views;},ownParams:function(state){if(!state.parent){return state.params;}
var paramNames={};forEach(state.params,function(p){paramNames[p]=true;});forEach(state.parent.params,function(p){if(!paramNames[p]){throw new Error("Missing required parameter '"+p+"' in state '"+state.name+"'");}
paramNames[p]=false;});var ownParams=[];forEach(paramNames,function(own,p){if(own)ownParams.push(p);});return ownParams;},path:function(state){return state.parent?state.parent.path.concat(state):[];},includes:function(state){var includes=state.parent?extend({},state.parent.includes):{};includes[state.name]=true;return includes;},$delegates:{}};function isRelative(stateName){return stateName.indexOf(".")===0||stateName.indexOf("^")===0;}
function findState(stateOrName,base){var isStr=isString(stateOrName),name=isStr?stateOrName:stateOrName.name,path=isRelative(name);if(path){if(!base)throw new Error("No reference point given for path '"+name+"'");var rel=name.split("."),i=0,pathLength=rel.length,current=base;for(;i<pathLength;i++){if(rel[i]===""&&i===0){current=base;continue;}
if(rel[i]==="^"){if(!current.parent)throw new Error("Path '"+name+"' not valid for state '"+base.name+"'");current=current.parent;continue;}
break;}
rel=rel.slice(i).join(".");name=current.name+(current.name&&rel?".":"")+rel;}
var state=states[name];if(state&&(isStr||(!isStr&&(state===stateOrName||state.self===stateOrName)))){return state;}
return undefined;}
function queueState(parentName,state){if(!queue[parentName]){queue[parentName]=[];}
queue[parentName].push(state);}
function registerState(state){state=inherit(state,{self:state,resolve:state.resolve||{},toString:function(){return this.name;}});var name=state.name;if(!isString(name)||name.indexOf('@')>=0)throw new Error("State must have a valid name");if(states.hasOwnProperty(name))throw new Error("State '"+name+"'' is already defined");var parentName=(name.indexOf('.')!==-1)?name.substring(0,name.lastIndexOf('.')):(isString(state.parent))?state.parent:'';if(parentName&&!states[parentName]){return queueState(parentName,state.self);}
for(var key in stateBuilder){if(isFunction(stateBuilder[key]))state[key]=stateBuilder[key](state,stateBuilder.$delegates[key]);}
states[name]=state;if(!state[abstractKey]&&state.url){$urlRouterProvider.when(state.url,['$match','$stateParams',function($match,$stateParams){if($state.$current.navigable!=state||!equalForKeys($match,$stateParams)){$state.transitionTo(state,$match,{location:false});}}]);}
if(queue[name]){for(var i=0;i<queue[name].length;i++){registerState(queue[name][i]);}}
return state;}
root=registerState({name:'',url:'^',views:null,'abstract':true});root.navigable=null;this.decorator=decorator;function decorator(name,func){if(isString(name)&&!isDefined(func)){return stateBuilder[name];}
if(!isFunction(func)||!isString(name)){return this;}
if(stateBuilder[name]&&!stateBuilder.$delegates[name]){stateBuilder.$delegates[name]=stateBuilder[name];}
stateBuilder[name]=func;return this;}
this.state=state;function state(name,definition){if(isObject(name))definition=name;else definition.name=name;registerState(definition);return this;}
this.$get=$get;$get.$inject=['$rootScope','$q','$view','$injector','$resolve','$stateParams','$location','$urlRouter'];function $get($rootScope,$q,$view,$injector,$resolve,$stateParams,$location,$urlRouter){var TransitionSuperseded=$q.reject(new Error('transition superseded'));var TransitionPrevented=$q.reject(new Error('transition prevented'));var TransitionAborted=$q.reject(new Error('transition aborted'));var TransitionFailed=$q.reject(new Error('transition failed'));var currentLocation=$location.url();function syncUrl(){if($location.url()!==currentLocation){$location.url(currentLocation);$location.replace();}}
root.locals={resolve:null,globals:{$stateParams:{}}};$state={params:{},current:root.self,$current:root,transition:null};$state.reload=function reload(){$state.transitionTo($state.current,$stateParams,{reload:true,inherit:false,notify:false});};$state.go=function go(to,params,options){return this.transitionTo(to,params,extend({inherit:true,relative:$state.$current},options));};$state.transitionTo=function transitionTo(to,toParams,options){toParams=toParams||{};options=extend({location:true,inherit:false,relative:null,notify:true,reload:false,$retry:false},options||{});var from=$state.$current,fromParams=$state.params,fromPath=from.path;var evt,toState=findState(to,options.relative);if(!isDefined(toState)){var redirect={to:to,toParams:toParams,options:options};evt=$rootScope.$broadcast('$stateNotFound',redirect,from.self,fromParams);if(evt.defaultPrevented){syncUrl();return TransitionAborted;}
if(evt.retry){if(options.$retry){syncUrl();return TransitionFailed;}
var retryTransition=$state.transition=$q.when(evt.retry);retryTransition.then(function(){if(retryTransition!==$state.transition)return TransitionSuperseded;redirect.options.$retry=true;return $state.transitionTo(redirect.to,redirect.toParams,redirect.options);},function(){return TransitionAborted;});syncUrl();return retryTransition;}
to=redirect.to;toParams=redirect.toParams;options=redirect.options;toState=findState(to,options.relative);if(!isDefined(toState)){if(options.relative)throw new Error("Could not resolve '"+to+"' from state '"+options.relative+"'");throw new Error("No such state '"+to+"'");}}
if(toState[abstractKey])throw new Error("Cannot transition to abstract state '"+to+"'");if(options.inherit)toParams=inheritParams($stateParams,toParams||{},$state.$current,toState);to=toState;var toPath=to.path;var keep,state,locals=root.locals,toLocals=[];for(keep=0,state=toPath[keep];state&&state===fromPath[keep]&&equalForKeys(toParams,fromParams,state.ownParams)&&!options.reload;keep++,state=toPath[keep]){locals=toLocals[keep]=state.locals;}
if(shouldTriggerReload(to,from,locals,options)){if(to.self.reloadOnSearch!==false)
syncUrl();$state.transition=null;return $q.when($state.current);}
toParams=normalize(to.params,toParams||{});if(options.notify){evt=$rootScope.$broadcast('$stateChangeStart',to.self,toParams,from.self,fromParams);if(evt.defaultPrevented){syncUrl();return TransitionPrevented;}}
var resolved=$q.when(locals);for(var l=keep;l<toPath.length;l++,state=toPath[l]){locals=toLocals[l]=inherit(locals);resolved=resolveState(state,toParams,state===to,resolved,locals);}
var transition=$state.transition=resolved.then(function(){var l,entering,exiting;if($state.transition!==transition)return TransitionSuperseded;for(l=fromPath.length-1;l>=keep;l--){exiting=fromPath[l];if(exiting.self.onExit){$injector.invoke(exiting.self.onExit,exiting.self,exiting.locals?exiting.locals.globals:null);}
exiting.locals=null;}
for(l=keep;l<toPath.length;l++){entering=toPath[l];entering.locals=toLocals[l];if(entering.self.onEnter){$injector.invoke(entering.self.onEnter,entering.self,entering.locals.globals);}}
if($state.transition!==transition)return TransitionSuperseded;$state.$current=to;$state.current=to.self;$state.params=toParams;copy($state.params,$stateParams);$state.transition=null;var toNav=to.navigable;if(options.location&&toNav){$location.url(toNav.url.format(toNav.locals.globals.$stateParams));if(options.location==='replace'){$location.replace();}}
if(options.notify){$rootScope.$broadcast('$stateChangeSuccess',to.self,toParams,from.self,fromParams);}
currentLocation=$location.url();return $state.current;},function(error){if($state.transition!==transition)return TransitionSuperseded;$state.transition=null;$rootScope.$broadcast('$stateChangeError',to.self,toParams,from.self,fromParams,error);syncUrl();return $q.reject(error);});return transition;};$state.is=function is(stateOrName,params){var state=findState(stateOrName);if(!isDefined(state)){return undefined;}
if($state.$current!==state){return false;}
return isDefined(params)&&params!==null?angular.equals($stateParams,params):true;};$state.includes=function includes(stateOrName,params){var state=findState(stateOrName);if(!isDefined(state)){return undefined;}
if(!isDefined($state.$current.includes[state.name])){return false;}
var validParams=true;angular.forEach(params,function(value,key){if(!isDefined($stateParams[key])||$stateParams[key]!==value){validParams=false;}});return validParams;};$state.href=function href(stateOrName,params,options){options=extend({lossy:true,inherit:false,absolute:false,relative:$state.$current},options||{});var state=findState(stateOrName,options.relative);if(!isDefined(state))return null;params=inheritParams($stateParams,params||{},$state.$current,state);var nav=(state&&options.lossy)?state.navigable:state;var url=(nav&&nav.url)?nav.url.format(normalize(state.params,params||{})):null;if(!$locationProvider.html5Mode()&&url){url="#"+$locationProvider.hashPrefix()+url;}
if(options.absolute&&url){url=$location.protocol()+'://'+
$location.host()+
($location.port()==80||$location.port()==443?'':':'+$location.port())+
(!$locationProvider.html5Mode()&&url?'/':'')+
url;}
return url;};$state.get=function(stateOrName,context){if(!isDefined(stateOrName)){var list=[];forEach(states,function(state){list.push(state.self);});return list;}
var state=findState(stateOrName,context);return(state&&state.self)?state.self:null;};function resolveState(state,params,paramsAreFiltered,inherited,dst){var $stateParams=(paramsAreFiltered)?params:filterByKeys(state.params,params);var locals={$stateParams:$stateParams};dst.resolve=$resolve.resolve(state.resolve,locals,dst.resolve,state);var promises=[dst.resolve.then(function(globals){dst.globals=globals;})];if(inherited)promises.push(inherited);forEach(state.views,function(view,name){var injectables=(view.resolve&&view.resolve!==state.resolve?view.resolve:{});injectables.$template=[function(){return $view.load(name,{view:view,locals:locals,params:$stateParams,notify:false})||'';}];promises.push($resolve.resolve(injectables,locals,dst.resolve,state).then(function(result){if(isFunction(view.controllerProvider)||isArray(view.controllerProvider)){var injectLocals=angular.extend({},injectables,locals);result.$$controller=$injector.invoke(view.controllerProvider,null,injectLocals);}else{result.$$controller=view.controller;}
result.$$state=state;dst[name]=result;}));});return $q.all(promises).then(function(values){return dst;});}
return $state;}
function shouldTriggerReload(to,from,locals,options){if(to===from&&((locals===from.locals&&!options.reload)||(to.self.reloadOnSearch===false))){return true;}}}
angular.module('ui.router.state').value('$stateParams',{}).provider('$state',$StateProvider);$ViewProvider.$inject=[];function $ViewProvider(){this.$get=$get;$get.$inject=['$rootScope','$templateFactory'];function $get($rootScope,$templateFactory){return{load:function load(name,options){var result,defaults={template:null,controller:null,view:null,locals:null,notify:true,async:true,params:{}};options=extend(defaults,options);if(options.view){result=$templateFactory.fromConfig(options.view,options.params,options.locals);}
if(result&&options.notify){$rootScope.$broadcast('$viewContentLoading',options);}
return result;}};}}
angular.module('ui.router.state').provider('$view',$ViewProvider);function $ViewScrollProvider(){var useAnchorScroll=false;this.useAnchorScroll=function(){useAnchorScroll=true;};this.$get=['$anchorScroll','$timeout',function($anchorScroll,$timeout){if(useAnchorScroll){return $anchorScroll;}
return function($element){$timeout(function(){$element[0].scrollIntoView();},0,false);};}];}
angular.module('ui.router.state').provider('$uiViewScroll',$ViewScrollProvider);$ViewDirective.$inject=['$state','$compile','$controller','$injector','$uiViewScroll','$document'];function $ViewDirective($state,$compile,$controller,$injector,$uiViewScroll,$document){function getService(){return($injector.has)?function(service){return $injector.has(service)?$injector.get(service):null;}:function(service){try{return $injector.get(service);}catch(e){return null;}};}
var viewIsUpdating=false,service=getService(),$animator=service('$animator'),$animate=service('$animate');function getRenderer(element,attrs,scope){var statics=function(){return{leave:function(element){element.remove();},enter:function(element,parent,anchor){anchor.after(element);}};};if($animate){return function(shouldAnimate){return!shouldAnimate?statics():{enter:function(element,parent,anchor){$animate.enter(element,null,anchor);},leave:function(element){$animate.leave(element,function(){element.remove();});}};};}
if($animator){var animate=$animator&&$animator(scope,attrs);return function(shouldAnimate){return!shouldAnimate?statics():{enter:function(element,parent,anchor){animate.enter(element,parent);},leave:function(element){animate.leave(element.contents(),element);}};};}
return statics;}
var directive={restrict:'ECA',compile:function(element,attrs){var initial=element.html(),isDefault=true,anchor=angular.element($document[0].createComment(' ui-view-anchor ')),parentEl=element.parent();element.prepend(anchor);return function($scope){var inherited=parentEl.inheritedData('$uiView');var currentScope,currentEl,viewLocals,name=attrs[directive.name]||attrs.name||'',onloadExp=attrs.onload||'',autoscrollExp=attrs.autoscroll,renderer=getRenderer(element,attrs,$scope);if(name.indexOf('@')<0)name=name+'@'+(inherited?inherited.state.name:'');var view={name:name,state:null};var eventHook=function(){if(viewIsUpdating)return;viewIsUpdating=true;try{updateView(true);}catch(e){viewIsUpdating=false;throw e;}
viewIsUpdating=false;};$scope.$on('$stateChangeSuccess',eventHook);$scope.$on('$viewContentLoading',eventHook);updateView(false);function cleanupLastView(){if(currentEl){renderer(true).leave(currentEl);currentEl=null;}
if(currentScope){currentScope.$destroy();currentScope=null;}}
function updateView(shouldAnimate){var locals=$state.$current&&$state.$current.locals[name];if(isDefault){isDefault=false;element.replaceWith(anchor);}
if(!locals){cleanupLastView();currentEl=element.clone();currentEl.html(initial);renderer(shouldAnimate).enter(currentEl,parentEl,anchor);currentScope=$scope.$new();$compile(currentEl.contents())(currentScope);return;}
if(locals===viewLocals)return;cleanupLastView();currentEl=element.clone();currentEl.html(locals.$template?locals.$template:initial);renderer(true).enter(currentEl,parentEl,anchor);currentEl.data('$uiView',view);viewLocals=locals;view.state=locals.$$state;var link=$compile(currentEl.contents());currentScope=$scope.$new();if(locals.$$controller){locals.$scope=currentScope;var controller=$controller(locals.$$controller,locals);currentEl.children().data('$ngControllerController',controller);}
link(currentScope);currentScope.$emit('$viewContentLoaded');if(onloadExp)currentScope.$eval(onloadExp);if(!angular.isDefined(autoscrollExp)||!autoscrollExp||$scope.$eval(autoscrollExp)){$uiViewScroll(currentEl);}}};}};return directive;}
angular.module('ui.router.state').directive('uiView',$ViewDirective);function parseStateRef(ref){var parsed=ref.replace(/\n/g," ").match(/^([^(]+?)\s*(\((.*)\))?$/);if(!parsed||parsed.length!==4)throw new Error("Invalid state ref '"+ref+"'");return{state:parsed[1],paramExpr:parsed[3]||null};}
function stateContext(el){var stateData=el.parent().inheritedData('$uiView');if(stateData&&stateData.state&&stateData.state.name){return stateData.state;}}
$StateRefDirective.$inject=['$state','$timeout'];function $StateRefDirective($state,$timeout){return{restrict:'A',require:'?^uiSrefActive',link:function(scope,element,attrs,uiSrefActive){var ref=parseStateRef(attrs.uiSref);var params=null,url=null,base=stateContext(element)||$state.$current;var isForm=element[0].nodeName==="FORM";var attr=isForm?"action":"href",nav=true;var update=function(newVal){var base=stateContext(element)||$state.$current;if(newVal)params=newVal;if(!nav)return;var newHref=$state.href(ref.state,params,{relative:base});if(uiSrefActive){uiSrefActive.$$setStateInfo(ref.state,params);}
if(!newHref){nav=false;return false;}
element[0][attr]=newHref;};if(ref.paramExpr){scope.$watch(ref.paramExpr,function(newVal,oldVal){if(newVal!==params)update(newVal);},true);params=scope.$eval(ref.paramExpr);}
update();if(isForm)return;element.bind("click",function(e){var button=e.which||e.button;if((button===0||button==1)&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&!element.attr('target')){$timeout(function(){$state.go(ref.state,params,{relative:base});});e.preventDefault();}});}};}
$StateActiveDirective.$inject=['$state','$stateParams','$interpolate'];function $StateActiveDirective($state,$stateParams,$interpolate){return{restrict:"A",controller:['$scope','$element','$attrs',function($scope,$element,$attrs){var state,params,activeClass;activeClass=$interpolate($attrs.uiSrefActive||'',false)($scope);this.$$setStateInfo=function(newState,newParams){state=$state.get(newState,stateContext($element));params=newParams;update();};$scope.$on('$stateChangeSuccess',update);function update(){if($state.$current.self===state&&matchesParams()){$element.addClass(activeClass);}else{$element.removeClass(activeClass);}}
function matchesParams(){return!params||equalForKeys(params,$stateParams);}}]};}
angular.module('ui.router.state').directive('uiSref',$StateRefDirective).directive('uiSrefActive',$StateActiveDirective);$IsStateFilter.$inject=['$state'];function $IsStateFilter($state){return function(state){return $state.is(state);};}
$IncludedByStateFilter.$inject=['$state'];function $IncludedByStateFilter($state){return function(state){return $state.includes(state);};}
angular.module('ui.router.state').filter('isState',$IsStateFilter).filter('includedByState',$IncludedByStateFilter);$RouteProvider.$inject=['$stateProvider','$urlRouterProvider'];function $RouteProvider($stateProvider,$urlRouterProvider){var routes=[];onEnterRoute.$inject=['$$state'];function onEnterRoute($$state){this.locals=$$state.locals.globals;this.params=this.locals.$stateParams;}
function onExitRoute(){this.locals=null;this.params=null;}
this.when=when;function when(url,route){if(route.redirectTo!=null){var redirect=route.redirectTo,handler;if(isString(redirect)){handler=redirect;}else if(isFunction(redirect)){handler=function(params,$location){return redirect(params,$location.path(),$location.search());};}else{throw new Error("Invalid 'redirectTo' in when()");}
$urlRouterProvider.when(url,handler);}else{$stateProvider.state(inherit(route,{parent:null,name:'route:'+encodeURIComponent(url),url:url,onEnter:onEnterRoute,onExit:onExitRoute}));}
routes.push(route);return this;}
this.$get=$get;$get.$inject=['$state','$rootScope','$routeParams'];function $get($state,$rootScope,$routeParams){var $route={routes:routes,params:$routeParams,current:undefined};function stateAsRoute(state){return(state.name!=='')?state:undefined;}
$rootScope.$on('$stateChangeStart',function(ev,to,toParams,from,fromParams){$rootScope.$broadcast('$routeChangeStart',stateAsRoute(to),stateAsRoute(from));});$rootScope.$on('$stateChangeSuccess',function(ev,to,toParams,from,fromParams){$route.current=stateAsRoute(to);$rootScope.$broadcast('$routeChangeSuccess',stateAsRoute(to),stateAsRoute(from));copy(toParams,$route.params);});$rootScope.$on('$stateChangeError',function(ev,to,toParams,from,fromParams,error){$rootScope.$broadcast('$routeChangeError',stateAsRoute(to),stateAsRoute(from),error);});return $route;}}
angular.module('ui.router.compat').provider('$route',$RouteProvider).directive('ngView',$ViewDirective);})(window,window.angular);
(function(){'use strict';angular.module('wu.masonry',[]).controller('MasonryCtrl',['$scope','$element','$timeout',function controller($scope,$element,$timeout){var bricks={};var schedule=[];var destroyed=false;var self=this;var timeout=null;this.scheduleMasonryOnce=function scheduleMasonryOnce(){var args=arguments;var found=schedule.filter(function filterFn(item){return item[0]===args[0];}).length>0;if(!found){this.scheduleMasonry.apply(null,arguments);}};this.scheduleMasonry=function scheduleMasonry(){if(timeout){$timeout.cancel(timeout);}
schedule.push([].slice.call(arguments));timeout=$timeout(function runMasonry(){if(destroyed){return;}
schedule.forEach(function scheduleForEach(args){$element.masonry.apply($element,args);});schedule=[];},30);};function defaultLoaded($element){$element.addClass('loaded');}
this.appendBrick=function appendBrick(element,id){if(destroyed){return;}
function _append(){if(Object.keys(bricks).length===0){$element.masonry('resize');}
if(bricks[id]===undefined){defaultLoaded(element);bricks[id]=true;$element.masonry('appended',element,true);self.scheduleMasonryOnce('reloadItems');self.scheduleMasonryOnce('layout');}}
_append();};this.removeBrick=function removeBrick(id,element){if(destroyed){return;}
delete bricks[id];$element.masonry('remove',element);this.scheduleMasonryOnce('layout');};this.destroy=function destroy(){destroyed=true;if($element.data('masonry')){$element.masonry('destroy');}
$scope.$emit('masonry.destroyed');bricks=[];};this.reload=function reload(){$element.masonry();$scope.$emit('masonry.reloaded');};}]).directive('masonry',function masonryDirective(){return{restrict:'AE',controller:'MasonryCtrl',link:{pre:function preLink(scope,element,attrs,ctrl){var attrOptions=scope.$eval(attrs.masonry||attrs.masonryOptions);var options=angular.extend(attrOptions||{},{itemSelector:attrs.itemSelector||'.masonry-brick',columnWidth:parseInt(attrs.columnWidth,10)});element.masonry(options);scope.$emit('masonry.created',element);scope.$on('$destroy',ctrl.destroy);}}};}).directive('masonryBrick',function masonryBrickDirective(){return{restrict:'AC',require:'^masonry',scope:true,link:{pre:function preLink(scope,element,attrs,ctrl){var id=scope.$id,index;ctrl.appendBrick(element,id);element.on('$destroy',function(){ctrl.removeBrick(id,element);});scope.$on('masonry.reload',function(){ctrl.reload();});scope.$watch('$index',function(){if(index!==undefined&&index!==scope.$index){ctrl.scheduleMasonryOnce('reloadItems');ctrl.scheduleMasonryOnce('layout');}
index=scope.$index;});}}};});}());
(function(){var angularFileUpload=angular.module('angularFileUpload',[]);angularFileUpload.service('$upload',['$http','$q','$timeout',function($http,$q,$timeout){function sendHttp(config){config.method=config.method||'POST';config.headers=config.headers||{};config.transformRequest=config.transformRequest||function(data,headersGetter){if(window.ArrayBuffer&&data instanceof window.ArrayBuffer){return data;}
return $http.defaults.transformRequest[0](data,headersGetter);};var deferred=$q.defer();if(window.XMLHttpRequest.__isShim){config.headers['__setXHR_']=function(){return function(xhr){if(!xhr)return;config.__XHR=xhr;config.xhrFn&&config.xhrFn(xhr);xhr.upload.addEventListener('progress',function(e){deferred.notify(e);},false);xhr.upload.addEventListener('load',function(e){if(e.lengthComputable){deferred.notify(e);}},false);};};}
$http(config).then(function(r){deferred.resolve(r)},function(e){deferred.reject(e)},function(n){deferred.notify(n)});var promise=deferred.promise;promise.success=function(fn){promise.then(function(response){fn(response.data,response.status,response.headers,config);});return promise;};promise.error=function(fn){promise.then(null,function(response){fn(response.data,response.status,response.headers,config);});return promise;};promise.progress=function(fn){promise.then(null,null,function(update){fn(update);});return promise;};promise.abort=function(){if(config.__XHR){$timeout(function(){config.__XHR.abort();});}
return promise;};promise.xhr=function(fn){config.xhrFn=(function(origXhrFn){return function(){origXhrFn&&origXhrFn.apply(promise,arguments);fn.apply(promise,arguments);}})(config.xhrFn);return promise;};return promise;}
this.upload=function(config){config.headers=config.headers||{};config.headers['Content-Type']=undefined;config.transformRequest=config.transformRequest||$http.defaults.transformRequest;var formData=new FormData();var origTransformRequest=config.transformRequest;var origData=config.data;config.transformRequest=function(formData,headerGetter){if(origData){if(config.formDataAppender){for(var key in origData){var val=origData[key];config.formDataAppender(formData,key,val);}}else{for(var key in origData){var val=origData[key];if(typeof origTransformRequest=='function'){val=origTransformRequest(val,headerGetter);}else{for(var i=0;i<origTransformRequest.length;i++){var transformFn=origTransformRequest[i];if(typeof transformFn=='function'){val=transformFn(val,headerGetter);}}}
formData.append(key,val);}}}
if(config.file!=null){var fileFormName=config.fileFormDataName||'file';if(Object.prototype.toString.call(config.file)==='[object Array]'){var isFileFormNameString=Object.prototype.toString.call(fileFormName)==='[object String]';for(var i=0;i<config.file.length;i++){formData.append(isFileFormNameString?fileFormName:fileFormName[i],config.file[i],(config.fileName&&config.fileName[i])||config.file[i].name);}}else{formData.append(fileFormName,config.file,config.fileName||config.file.name);}}
return formData;};config.data=formData;return sendHttp(config);};this.http=function(config){return sendHttp(config);}}]);angularFileUpload.directive('ngFileSelect',['$parse','$timeout',function($parse,$timeout){return function(scope,elem,attr){var fn=$parse(attr['ngFileSelect']);if(elem[0].tagName.toLowerCase()!=='input'||(elem.attr('type')&&elem.attr('type').toLowerCase())!=='file'){var fileElem=angular.element('<input type="file">')
for(var i=0;i<elem[0].attributes.length;i++){fileElem.attr(elem[0].attributes[i].name,elem[0].attributes[i].value);}
if(elem.attr("data-multiple"))fileElem.attr("multiple","true");fileElem.css("top",0).css("bottom",0).css("left",0).css("right",0).css("width","100%").css("opacity",0).css("position","absolute").css('filter','alpha(opacity=0)');elem.append(fileElem);if(elem.css("position")===''||elem.css("position")==='static'){elem.css("position","relative");}
elem=fileElem;}
elem.bind('change',function(evt){var files=[],fileList,i;fileList=evt.__files_||evt.target.files;if(fileList!=null){for(i=0;i<fileList.length;i++){files.push(fileList.item(i));}}
$timeout(function(){fn(scope,{$files:files,$event:evt});});});};}]);angularFileUpload.directive('ngFileDropAvailable',['$parse','$timeout',function($parse,$timeout){return function(scope,elem,attr){if('draggable'in document.createElement('span')){var fn=$parse(attr['ngFileDropAvailable']);$timeout(function(){fn(scope);});}};}]);angularFileUpload.directive('ngFileDrop',['$parse','$timeout','$location',function($parse,$timeout,$location){return function(scope,elem,attr){if('draggable'in document.createElement('span')){var leaveTimeout=null;elem[0].addEventListener("dragover",function(evt){evt.stopPropagation();evt.preventDefault();$timeout.cancel(leaveTimeout);if(!elem[0].__drag_over_class_){if(attr['ngFileDragOverClass'].search(/\) *$/)>-1){dragOverClassFn=$parse(attr['ngFileDragOverClass']);var dragOverClass=dragOverClassFn(scope,{$event:evt});elem[0].__drag_over_class_=dragOverClass;}else{elem[0].__drag_over_class_=attr['ngFileDragOverClass']||"dragover";}}
elem.addClass(elem[0].__drag_over_class_);},false);elem[0].addEventListener("dragenter",function(evt){evt.stopPropagation();evt.preventDefault();},false);elem[0].addEventListener("dragleave",function(evt){leaveTimeout=$timeout(function(){elem.removeClass(elem[0].__drag_over_class_);elem[0].__drag_over_class_=null;},attr['ngFileDragOverDelay']||1);},false);var fn=$parse(attr['ngFileDrop']);elem[0].addEventListener("drop",function(evt){evt.stopPropagation();evt.preventDefault();elem.removeClass(elem[0].__drag_over_class_);elem[0].__drag_over_class_=null;extractFiles(evt,function(files){fn(scope,{$files:files,$event:evt});});},false);function isASCII(str){return /^[\000-\177]*$/.test(str);}
function extractFiles(evt,callback){var files=[],items=evt.dataTransfer.items;if(items&&items.length>0&&items[0].webkitGetAsEntry&&$location.protocol()!='file'){for(var i=0;i<items.length;i++){var entry=items[i].webkitGetAsEntry();if(entry!=null){if(isASCII(entry.name)){traverseFileTree(files,entry);}else if(!items[i].webkitGetAsEntry().isDirectory){files.push(items[i].getAsFile());}}}}else{var fileList=evt.dataTransfer.files;if(fileList!=null){for(var i=0;i<fileList.length;i++){files.push(fileList.item(i));}}}
(function waitForProcess(delay){$timeout(function(){if(!processing){callback(files);}else{waitForProcess(10);}},delay||0)})();}
var processing=0;function traverseFileTree(files,entry,path){if(entry!=null){if(entry.isDirectory){var dirReader=entry.createReader();processing++;dirReader.readEntries(function(entries){for(var i=0;i<entries.length;i++){traverseFileTree(files,entries[i],(path?path:"")+entry.name+"/");}
processing--;});}else{processing++;entry.file(function(file){processing--;file._relativePath=(path?path:"")+file.name;files.push(file);});}}}}};}]);})();
/*!
 * Cropper v2.2.4
 * https://github.com/fengyuanchen/cropper
 *
 * Copyright (c) 2014-2016 Fengyuan Chen and contributors
 * Released under the MIT license
 *
 * Date: 2016-01-01T08:20:32.820Z
 */!function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){"use strict";function i(t){return"number"==typeof t&&!isNaN(t)}function e(t){return"undefined"==typeof t}function s(t,e){var s=[];return i(e)&&s.push(e),s.slice.apply(t,s)}function a(t,i){var e=s(arguments,2);return function(){return t.apply(i,e.concat(s(arguments)))}}function o(t){var i=t.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i);return i&&(i[1]!==C.protocol||i[2]!==C.hostname||i[3]!==C.port)}function h(t){var i="timestamp="+(new Date).getTime();return t+(-1===t.indexOf("?")?"?":"&")+i}function n(t){return t?' crossOrigin="'+t+'"':""}function r(t,i){var e;return t.naturalWidth?i(t.naturalWidth,t.naturalHeight):(e=document.createElement("img"),e.onload=function(){i(this.width,this.height)},void(e.src=t.src))}function p(t){var e=[],s=t.rotate,a=t.scaleX,o=t.scaleY;return i(s)&&e.push("rotate("+s+"deg)"),i(a)&&i(o)&&e.push("scale("+a+","+o+")"),e.length?e.join(" "):"none"}function l(t,i){var e,s,a=wt(t.degree)%180,o=(a>90?180-a:a)*Math.PI/180,h=xt(o),n=Ct(o),r=t.width,p=t.height,l=t.aspectRatio;return i?(e=r/(n+h/l),s=e/l):(e=r*n+p*h,s=r*h+p*n),{width:e,height:s}}function c(e,s){var a,o,h,n=t("<canvas>")[0],r=n.getContext("2d"),p=0,c=0,d=s.naturalWidth,g=s.naturalHeight,u=s.rotate,f=s.scaleX,m=s.scaleY,v=i(f)&&i(m)&&(1!==f||1!==m),w=i(u)&&0!==u,x=w||v,C=d,b=g;return v&&(a=d/2,o=g/2),w&&(h=l({width:d,height:g,degree:u}),C=h.width,b=h.height,a=h.width/2,o=h.height/2),n.width=C,n.height=b,x&&(p=-d/2,c=-g/2,r.save(),r.translate(a,o)),w&&r.rotate(u*Math.PI/180),v&&r.scale(f,m),r.drawImage(e,yt(p),yt(c),yt(d),yt(g)),x&&r.restore(),n}function d(i){var e=i.length,s=0,a=0;return e&&(t.each(i,function(t,i){s+=i.pageX,a+=i.pageY}),s/=e,a/=e),{pageX:s,pageY:a}}function g(t,i,e){var s,a="";for(s=i,e+=i;e>s;s++)a+=Dt(t.getUint8(s));return a}function u(t){var i,e,s,a,o,h,n,r,p,l,c=new y(t),d=c.byteLength;if(255===c.getUint8(0)&&216===c.getUint8(1))for(p=2;d>p;){if(255===c.getUint8(p)&&225===c.getUint8(p+1)){n=p;break}p++}if(n&&(e=n+4,s=n+10,"Exif"===g(c,e,4)&&(h=c.getUint16(s),o=18761===h,(o||19789===h)&&42===c.getUint16(s+2,o)&&(a=c.getUint32(s+4,o),a>=8&&(r=s+a)))),r)for(d=c.getUint16(r,o),l=0;d>l;l++)if(p=r+12*l+2,274===c.getUint16(p,o)){p+=8,i=c.getUint16(p,o),c.setUint16(p,1,o);break}return i}function f(t){var i,e=t.replace(V,""),s=atob(e),a=s.length,o=new b(a),h=new B(o);for(i=0;a>i;i++)h[i]=s.charCodeAt(i);return o}function m(t){var i,e=new B(t),s=e.length,a="";for(i=0;s>i;i++)a+=Dt(e[i]);return"data:image/jpeg;base64,"+D(a)}function v(i,e){this.$element=t(i),this.options=t.extend({},v.DEFAULTS,t.isPlainObject(e)&&e),this.isLoaded=!1,this.isBuilt=!1,this.isCompleted=!1,this.isRotated=!1,this.isCropped=!1,this.isDisabled=!1,this.isReplaced=!1,this.isLimited=!1,this.wheeling=!1,this.isImg=!1,this.originalUrl="",this.canvas=null,this.cropBox=null,this.init()}var w=t(window),x=t(document),C=window.location,b=window.ArrayBuffer,B=window.Uint8Array,y=window.DataView,D=window.btoa,$="cropper",L="cropper-modal",T="cropper-hide",X="cropper-hidden",Y="cropper-invisible",k="cropper-move",M="cropper-crop",W="cropper-disabled",R="cropper-bg",H="mousedown touchstart pointerdown MSPointerDown",z="mousemove touchmove pointermove MSPointerMove",O="mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel",E="wheel mousewheel DOMMouseScroll",P="dblclick",U="load."+$,I="error."+$,F="resize."+$,j="build."+$,S="built."+$,A="cropstart."+$,N="cropmove."+$,_="cropend."+$,q="crop."+$,Z="zoom."+$,K=/e|w|s|n|se|sw|ne|nw|all|crop|move|zoom/,Q=/^data\:/,V=/^data\:([^\;]+)\;base64,/,G=/^data\:image\/jpeg.*;base64,/,J="preview",tt="action",it="e",et="w",st="s",at="n",ot="se",ht="sw",nt="ne",rt="nw",pt="all",lt="crop",ct="move",dt="zoom",gt="none",ut=t.isFunction(t("<canvas>")[0].getContext),ft=Number,mt=Math.min,vt=Math.max,wt=Math.abs,xt=Math.sin,Ct=Math.cos,bt=Math.sqrt,Bt=Math.round,yt=Math.floor,Dt=String.fromCharCode;v.prototype={constructor:v,init:function(){var t,i=this.$element;if(i.is("img")){if(this.isImg=!0,this.originalUrl=t=i.attr("src"),!t)return;t=i.prop("src")}else i.is("canvas")&&ut&&(t=i[0].toDataURL());this.load(t)},trigger:function(i,e){var s=t.Event(i,e);return this.$element.trigger(s),s},load:function(i){var e,s,a=this.options,o=this.$element;if(i&&(o.one(j,a.build),!this.trigger(j).isDefaultPrevented())){if(this.url=i,this.image={},!a.checkOrientation||!b)return this.clone();if(e=t.proxy(this.read,this),Q.test(i))return G.test(i)?e(f(i)):this.clone();s=new XMLHttpRequest,s.onerror=s.onabort=t.proxy(function(){this.clone()},this),s.onload=function(){e(this.response)},s.open("get",i),s.responseType="arraybuffer",s.send()}},read:function(t){var i,e,s,a=this.options,o=u(t),h=this.image;if(o>1)switch(this.url=m(t),o){case 2:e=-1;break;case 3:i=-180;break;case 4:s=-1;break;case 5:i=90,s=-1;break;case 6:i=90;break;case 7:i=90,e=-1;break;case 8:i=-90}a.rotatable&&(h.rotate=i),a.scalable&&(h.scaleX=e,h.scaleY=s),this.clone()},clone:function(){var i,e,s=this.options,a=this.$element,r=this.url,p="";s.checkCrossOrigin&&o(r)&&(p=a.prop("crossOrigin"),p||(p="anonymous",i=h(r))),this.crossOrigin=p,this.crossOriginUrl=i,this.$clone=e=t("<img"+n(p)+' src="'+(i||r)+'">'),this.isImg?a[0].complete?this.start():a.one(U,t.proxy(this.start,this)):e.one(U,t.proxy(this.start,this)).one(I,t.proxy(this.stop,this)).addClass(T).insertAfter(a)},start:function(){var i=this.$element,e=this.$clone;this.isImg||(e.off(I,this.stop),i=e),r(i[0],t.proxy(function(i,e){t.extend(this.image,{naturalWidth:i,naturalHeight:e,aspectRatio:i/e}),this.isLoaded=!0,this.build()},this))},stop:function(){this.$clone.remove(),this.$clone=null},build:function(){var i,e,s,a=this.options,o=this.$element,h=this.$clone;this.isLoaded&&(this.isBuilt&&this.unbuild(),this.$container=o.parent(),this.$cropper=i=t(v.TEMPLATE),this.$canvas=i.find(".cropper-canvas").append(h),this.$dragBox=i.find(".cropper-drag-box"),this.$cropBox=e=i.find(".cropper-crop-box"),this.$viewBox=i.find(".cropper-view-box"),this.$face=s=e.find(".cropper-face"),o.addClass(X).after(i),this.isImg||h.removeClass(T),this.initPreview(),this.bind(),a.aspectRatio=vt(0,a.aspectRatio)||NaN,a.viewMode=vt(0,mt(3,Bt(a.viewMode)))||0,a.autoCrop?(this.isCropped=!0,a.modal&&this.$dragBox.addClass(L)):e.addClass(X),a.guides||e.find(".cropper-dashed").addClass(X),a.center||e.find(".cropper-center").addClass(X),a.cropBoxMovable&&s.addClass(k).data(tt,pt),a.highlight||s.addClass(Y),a.background&&i.addClass(R),a.cropBoxResizable||e.find(".cropper-line, .cropper-point").addClass(X),this.setDragMode(a.dragMode),this.render(),this.isBuilt=!0,this.setData(a.data),o.one(S,a.built),setTimeout(t.proxy(function(){this.trigger(S),this.isCompleted=!0},this),0))},unbuild:function(){this.isBuilt&&(this.isBuilt=!1,this.isCompleted=!1,this.initialImage=null,this.initialCanvas=null,this.initialCropBox=null,this.container=null,this.canvas=null,this.cropBox=null,this.unbind(),this.resetPreview(),this.$preview=null,this.$viewBox=null,this.$cropBox=null,this.$dragBox=null,this.$canvas=null,this.$container=null,this.$cropper.remove(),this.$cropper=null)},render:function(){this.initContainer(),this.initCanvas(),this.initCropBox(),this.renderCanvas(),this.isCropped&&this.renderCropBox()},initContainer:function(){var t=this.options,i=this.$element,e=this.$container,s=this.$cropper;s.addClass(X),i.removeClass(X),s.css(this.container={width:vt(e.width(),ft(t.minContainerWidth)||200),height:vt(e.height(),ft(t.minContainerHeight)||100)}),i.addClass(X),s.removeClass(X)},initCanvas:function(){var i,e=this.options.viewMode,s=this.container,a=s.width,o=s.height,h=this.image,n=h.naturalWidth,r=h.naturalHeight,p=90===wt(h.rotate),l=p?r:n,c=p?n:r,d=l/c,g=a,u=o;o*d>a?3===e?g=o*d:u=a/d:3===e?u=a/d:g=o*d,i={naturalWidth:l,naturalHeight:c,aspectRatio:d,width:g,height:u},i.oldLeft=i.left=(a-g)/2,i.oldTop=i.top=(o-u)/2,this.canvas=i,this.isLimited=1===e||2===e,this.limitCanvas(!0,!0),this.initialImage=t.extend({},h),this.initialCanvas=t.extend({},i)},limitCanvas:function(t,i){var e,s,a,o,h=this.options,n=h.viewMode,r=this.container,p=r.width,l=r.height,c=this.canvas,d=c.aspectRatio,g=this.cropBox,u=this.isCropped&&g;t&&(e=ft(h.minCanvasWidth)||0,s=ft(h.minCanvasHeight)||0,n&&(n>1?(e=vt(e,p),s=vt(s,l),3===n&&(s*d>e?e=s*d:s=e/d)):e?e=vt(e,u?g.width:0):s?s=vt(s,u?g.height:0):u&&(e=g.width,s=g.height,s*d>e?e=s*d:s=e/d)),e&&s?s*d>e?s=e/d:e=s*d:e?s=e/d:s&&(e=s*d),c.minWidth=e,c.minHeight=s,c.maxWidth=1/0,c.maxHeight=1/0),i&&(n?(a=p-c.width,o=l-c.height,c.minLeft=mt(0,a),c.minTop=mt(0,o),c.maxLeft=vt(0,a),c.maxTop=vt(0,o),u&&this.isLimited&&(c.minLeft=mt(g.left,g.left+g.width-c.width),c.minTop=mt(g.top,g.top+g.height-c.height),c.maxLeft=g.left,c.maxTop=g.top,2===n&&(c.width>=p&&(c.minLeft=mt(0,a),c.maxLeft=vt(0,a)),c.height>=l&&(c.minTop=mt(0,o),c.maxTop=vt(0,o))))):(c.minLeft=-c.width,c.minTop=-c.height,c.maxLeft=p,c.maxTop=l))},renderCanvas:function(t){var i,e,s=this.canvas,a=this.image,o=a.rotate,h=a.naturalWidth,n=a.naturalHeight;this.isRotated&&(this.isRotated=!1,e=l({width:a.width,height:a.height,degree:o}),i=e.width/e.height,i!==s.aspectRatio&&(s.left-=(e.width-s.width)/2,s.top-=(e.height-s.height)/2,s.width=e.width,s.height=e.height,s.aspectRatio=i,s.naturalWidth=h,s.naturalHeight=n,o%180&&(e=l({width:h,height:n,degree:o}),s.naturalWidth=e.width,s.naturalHeight=e.height),this.limitCanvas(!0,!1))),(s.width>s.maxWidth||s.width<s.minWidth)&&(s.left=s.oldLeft),(s.height>s.maxHeight||s.height<s.minHeight)&&(s.top=s.oldTop),s.width=mt(vt(s.width,s.minWidth),s.maxWidth),s.height=mt(vt(s.height,s.minHeight),s.maxHeight),this.limitCanvas(!1,!0),s.oldLeft=s.left=mt(vt(s.left,s.minLeft),s.maxLeft),s.oldTop=s.top=mt(vt(s.top,s.minTop),s.maxTop),this.$canvas.css({width:s.width,height:s.height,left:s.left,top:s.top}),this.renderImage(),this.isCropped&&this.isLimited&&this.limitCropBox(!0,!0),t&&this.output()},renderImage:function(i){var e,s=this.canvas,a=this.image;a.rotate&&(e=l({width:s.width,height:s.height,degree:a.rotate,aspectRatio:a.aspectRatio},!0)),t.extend(a,e?{width:e.width,height:e.height,left:(s.width-e.width)/2,top:(s.height-e.height)/2}:{width:s.width,height:s.height,left:0,top:0}),this.$clone.css({width:a.width,height:a.height,marginLeft:a.left,marginTop:a.top,transform:p(a)}),i&&this.output()},initCropBox:function(){var i=this.options,e=this.canvas,s=i.aspectRatio,a=ft(i.autoCropArea)||.8,o={width:e.width,height:e.height};s&&(e.height*s>e.width?o.height=o.width/s:o.width=o.height*s),this.cropBox=o,this.limitCropBox(!0,!0),o.width=mt(vt(o.width,o.minWidth),o.maxWidth),o.height=mt(vt(o.height,o.minHeight),o.maxHeight),o.width=vt(o.minWidth,o.width*a),o.height=vt(o.minHeight,o.height*a),o.oldLeft=o.left=e.left+(e.width-o.width)/2,o.oldTop=o.top=e.top+(e.height-o.height)/2,this.initialCropBox=t.extend({},o)},limitCropBox:function(t,i){var e,s,a,o,h=this.options,n=h.aspectRatio,r=this.container,p=r.width,l=r.height,c=this.canvas,d=this.cropBox,g=this.isLimited;t&&(e=ft(h.minCropBoxWidth)||0,s=ft(h.minCropBoxHeight)||0,e=mt(e,p),s=mt(s,l),a=mt(p,g?c.width:p),o=mt(l,g?c.height:l),n&&(e&&s?s*n>e?s=e/n:e=s*n:e?s=e/n:s&&(e=s*n),o*n>a?o=a/n:a=o*n),d.minWidth=mt(e,a),d.minHeight=mt(s,o),d.maxWidth=a,d.maxHeight=o),i&&(g?(d.minLeft=vt(0,c.left),d.minTop=vt(0,c.top),d.maxLeft=mt(p,c.left+c.width)-d.width,d.maxTop=mt(l,c.top+c.height)-d.height):(d.minLeft=0,d.minTop=0,d.maxLeft=p-d.width,d.maxTop=l-d.height))},renderCropBox:function(){var t=this.options,i=this.container,e=i.width,s=i.height,a=this.cropBox;(a.width>a.maxWidth||a.width<a.minWidth)&&(a.left=a.oldLeft),(a.height>a.maxHeight||a.height<a.minHeight)&&(a.top=a.oldTop),a.width=mt(vt(a.width,a.minWidth),a.maxWidth),a.height=mt(vt(a.height,a.minHeight),a.maxHeight),this.limitCropBox(!1,!0),a.oldLeft=a.left=mt(vt(a.left,a.minLeft),a.maxLeft),a.oldTop=a.top=mt(vt(a.top,a.minTop),a.maxTop),t.movable&&t.cropBoxMovable&&this.$face.data(tt,a.width===e&&a.height===s?ct:pt),this.$cropBox.css({width:a.width,height:a.height,left:a.left,top:a.top}),this.isCropped&&this.isLimited&&this.limitCanvas(!0,!0),this.isDisabled||this.output()},output:function(){this.preview(),this.isCompleted?this.trigger(q,this.getData()):this.isBuilt||this.$element.one(S,t.proxy(function(){this.trigger(q,this.getData())},this))},initPreview:function(){var i=n(this.crossOrigin),e=i?this.crossOriginUrl:this.url;this.$preview=t(this.options.preview),this.$viewBox.html("<img"+i+' src="'+e+'">'),this.$preview.each(function(){var s=t(this);s.data(J,{width:s.width(),height:s.height(),html:s.html()}),s.html("<img"+i+' src="'+e+'" style="display:block;width:100%;height:auto;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation:0deg!important;">')})},resetPreview:function(){this.$preview.each(function(){var i=t(this),e=i.data(J);i.css({width:e.width,height:e.height}).html(e.html).removeData(J)})},preview:function(){var i=this.image,e=this.canvas,s=this.cropBox,a=s.width,o=s.height,h=i.width,n=i.height,r=s.left-e.left-i.left,l=s.top-e.top-i.top;this.isCropped&&!this.isDisabled&&(this.$viewBox.find("img").css({width:h,height:n,marginLeft:-r,marginTop:-l,transform:p(i)}),this.$preview.each(function(){var e=t(this),s=e.data(J),c=s.width,d=s.height,g=c,u=d,f=1;a&&(f=c/a,u=o*f),o&&u>d&&(f=d/o,g=a*f,u=d),e.css({width:g,height:u}).find("img").css({width:h*f,height:n*f,marginLeft:-r*f,marginTop:-l*f,transform:p(i)})}))},bind:function(){var i=this.options,e=this.$element,s=this.$cropper;t.isFunction(i.cropstart)&&e.on(A,i.cropstart),t.isFunction(i.cropmove)&&e.on(N,i.cropmove),t.isFunction(i.cropend)&&e.on(_,i.cropend),t.isFunction(i.crop)&&e.on(q,i.crop),t.isFunction(i.zoom)&&e.on(Z,i.zoom),s.on(H,t.proxy(this.cropStart,this)),i.zoomable&&i.zoomOnWheel&&s.on(E,t.proxy(this.wheel,this)),i.toggleDragModeOnDblclick&&s.on(P,t.proxy(this.dblclick,this)),x.on(z,this._cropMove=a(this.cropMove,this)).on(O,this._cropEnd=a(this.cropEnd,this)),i.responsive&&w.on(F,this._resize=a(this.resize,this))},unbind:function(){var i=this.options,e=this.$element,s=this.$cropper;t.isFunction(i.cropstart)&&e.off(A,i.cropstart),t.isFunction(i.cropmove)&&e.off(N,i.cropmove),t.isFunction(i.cropend)&&e.off(_,i.cropend),t.isFunction(i.crop)&&e.off(q,i.crop),t.isFunction(i.zoom)&&e.off(Z,i.zoom),s.off(H,this.cropStart),i.zoomable&&i.zoomOnWheel&&s.off(E,this.wheel),i.toggleDragModeOnDblclick&&s.off(P,this.dblclick),x.off(z,this._cropMove).off(O,this._cropEnd),i.responsive&&w.off(F,this._resize)},resize:function(){var i,e,s,a=this.options.restore,o=this.$container,h=this.container;!this.isDisabled&&h&&(s=o.width()/h.width,(1!==s||o.height()!==h.height)&&(a&&(i=this.getCanvasData(),e=this.getCropBoxData()),this.render(),a&&(this.setCanvasData(t.each(i,function(t,e){i[t]=e*s})),this.setCropBoxData(t.each(e,function(t,i){e[t]=i*s})))))},dblclick:function(){this.isDisabled||(this.$dragBox.hasClass(M)?this.setDragMode(ct):this.setDragMode(lt))},wheel:function(i){var e=i.originalEvent||i,s=ft(this.options.wheelZoomRatio)||.1,a=1;this.isDisabled||(i.preventDefault(),this.wheeling||(this.wheeling=!0,setTimeout(t.proxy(function(){this.wheeling=!1},this),50),e.deltaY?a=e.deltaY>0?1:-1:e.wheelDelta?a=-e.wheelDelta/120:e.detail&&(a=e.detail>0?1:-1),this.zoom(-a*s,i)))},cropStart:function(i){var e,s,a=this.options,o=i.originalEvent,h=o&&o.touches,n=i;if(!this.isDisabled){if(h){if(e=h.length,e>1){if(!a.zoomable||!a.zoomOnTouch||2!==e)return;n=h[1],this.startX2=n.pageX,this.startY2=n.pageY,s=dt}n=h[0]}if(s=s||t(n.target).data(tt),K.test(s)){if(this.trigger(A,{originalEvent:o,action:s}).isDefaultPrevented())return;i.preventDefault(),this.action=s,this.cropping=!1,this.startX=n.pageX||o&&o.pageX,this.startY=n.pageY||o&&o.pageY,s===lt&&(this.cropping=!0,this.$dragBox.addClass(L))}}},cropMove:function(t){var i,e=this.options,s=t.originalEvent,a=s&&s.touches,o=t,h=this.action;if(!this.isDisabled){if(a){if(i=a.length,i>1){if(!e.zoomable||!e.zoomOnTouch||2!==i)return;o=a[1],this.endX2=o.pageX,this.endY2=o.pageY}o=a[0]}if(h){if(this.trigger(N,{originalEvent:s,action:h}).isDefaultPrevented())return;t.preventDefault(),this.endX=o.pageX||s&&s.pageX,this.endY=o.pageY||s&&s.pageY,this.change(o.shiftKey,h===dt?t:null)}}},cropEnd:function(t){var i=t.originalEvent,e=this.action;this.isDisabled||e&&(t.preventDefault(),this.cropping&&(this.cropping=!1,this.$dragBox.toggleClass(L,this.isCropped&&this.options.modal)),this.action="",this.trigger(_,{originalEvent:i,action:e}))},change:function(t,i){var e,s,a=this.options,o=a.aspectRatio,h=this.action,n=this.container,r=this.canvas,p=this.cropBox,l=p.width,c=p.height,d=p.left,g=p.top,u=d+l,f=g+c,m=0,v=0,w=n.width,x=n.height,C=!0;switch(!o&&t&&(o=l&&c?l/c:1),this.limited&&(m=p.minLeft,v=p.minTop,w=m+mt(n.width,r.width),x=v+mt(n.height,r.height)),s={x:this.endX-this.startX,y:this.endY-this.startY},o&&(s.X=s.y*o,s.Y=s.x/o),h){case pt:d+=s.x,g+=s.y;break;case it:if(s.x>=0&&(u>=w||o&&(v>=g||f>=x))){C=!1;break}l+=s.x,o&&(c=l/o,g-=s.Y/2),0>l&&(h=et,l=0);break;case at:if(s.y<=0&&(v>=g||o&&(m>=d||u>=w))){C=!1;break}c-=s.y,g+=s.y,o&&(l=c*o,d+=s.X/2),0>c&&(h=st,c=0);break;case et:if(s.x<=0&&(m>=d||o&&(v>=g||f>=x))){C=!1;break}l-=s.x,d+=s.x,o&&(c=l/o,g+=s.Y/2),0>l&&(h=it,l=0);break;case st:if(s.y>=0&&(f>=x||o&&(m>=d||u>=w))){C=!1;break}c+=s.y,o&&(l=c*o,d-=s.X/2),0>c&&(h=at,c=0);break;case nt:if(o){if(s.y<=0&&(v>=g||u>=w)){C=!1;break}c-=s.y,g+=s.y,l=c*o}else s.x>=0?w>u?l+=s.x:s.y<=0&&v>=g&&(C=!1):l+=s.x,s.y<=0?g>v&&(c-=s.y,g+=s.y):(c-=s.y,g+=s.y);0>l&&0>c?(h=ht,c=0,l=0):0>l?(h=rt,l=0):0>c&&(h=ot,c=0);break;case rt:if(o){if(s.y<=0&&(v>=g||m>=d)){C=!1;break}c-=s.y,g+=s.y,l=c*o,d+=s.X}else s.x<=0?d>m?(l-=s.x,d+=s.x):s.y<=0&&v>=g&&(C=!1):(l-=s.x,d+=s.x),s.y<=0?g>v&&(c-=s.y,g+=s.y):(c-=s.y,g+=s.y);0>l&&0>c?(h=ot,c=0,l=0):0>l?(h=nt,l=0):0>c&&(h=ht,c=0);break;case ht:if(o){if(s.x<=0&&(m>=d||f>=x)){C=!1;break}l-=s.x,d+=s.x,c=l/o}else s.x<=0?d>m?(l-=s.x,d+=s.x):s.y>=0&&f>=x&&(C=!1):(l-=s.x,d+=s.x),s.y>=0?x>f&&(c+=s.y):c+=s.y;0>l&&0>c?(h=nt,c=0,l=0):0>l?(h=ot,l=0):0>c&&(h=rt,c=0);break;case ot:if(o){if(s.x>=0&&(u>=w||f>=x)){C=!1;break}l+=s.x,c=l/o}else s.x>=0?w>u?l+=s.x:s.y>=0&&f>=x&&(C=!1):l+=s.x,s.y>=0?x>f&&(c+=s.y):c+=s.y;0>l&&0>c?(h=rt,c=0,l=0):0>l?(h=ht,l=0):0>c&&(h=nt,c=0);break;case ct:this.move(s.x,s.y),C=!1;break;case dt:this.zoom(function(t,i,e,s){var a=bt(t*t+i*i),o=bt(e*e+s*s);return(o-a)/a}(wt(this.startX-this.startX2),wt(this.startY-this.startY2),wt(this.endX-this.endX2),wt(this.endY-this.endY2)),i),this.startX2=this.endX2,this.startY2=this.endY2,C=!1;break;case lt:if(!s.x||!s.y){C=!1;break}e=this.$cropper.offset(),d=this.startX-e.left,g=this.startY-e.top,l=p.minWidth,c=p.minHeight,s.x>0?h=s.y>0?ot:nt:s.x<0&&(d-=l,h=s.y>0?ht:rt),s.y<0&&(g-=c),this.isCropped||(this.$cropBox.removeClass(X),this.isCropped=!0,this.limited&&this.limitCropBox(!0,!0))}C&&(p.width=l,p.height=c,p.left=d,p.top=g,this.action=h,this.renderCropBox()),this.startX=this.endX,this.startY=this.endY},crop:function(){this.isBuilt&&!this.isDisabled&&(this.isCropped||(this.isCropped=!0,this.limitCropBox(!0,!0),this.options.modal&&this.$dragBox.addClass(L),this.$cropBox.removeClass(X)),this.setCropBoxData(this.initialCropBox))},reset:function(){this.isBuilt&&!this.isDisabled&&(this.image=t.extend({},this.initialImage),this.canvas=t.extend({},this.initialCanvas),this.cropBox=t.extend({},this.initialCropBox),this.renderCanvas(),this.isCropped&&this.renderCropBox())},clear:function(){this.isCropped&&!this.isDisabled&&(t.extend(this.cropBox,{left:0,top:0,width:0,height:0}),this.isCropped=!1,this.renderCropBox(),this.limitCanvas(!0,!0),this.renderCanvas(),this.$dragBox.removeClass(L),this.$cropBox.addClass(X))},replace:function(t){!this.isDisabled&&t&&(this.isImg&&(this.isReplaced=!0,this.$element.attr("src",t)),this.options.data=null,this.load(t))},enable:function(){this.isBuilt&&(this.isDisabled=!1,this.$cropper.removeClass(W))},disable:function(){this.isBuilt&&(this.isDisabled=!0,this.$cropper.addClass(W))},destroy:function(){var t=this.$element;this.isLoaded?(this.isImg&&this.isReplaced&&t.attr("src",this.originalUrl),this.unbuild(),t.removeClass(X)):this.isImg?t.off(U,this.start):this.$clone&&this.$clone.remove(),t.removeData($)},move:function(t,i){var s=this.canvas;this.moveTo(e(t)?t:s.left+ft(t),e(i)?i:s.top+ft(i))},moveTo:function(t,s){var a=this.canvas,o=!1;e(s)&&(s=t),t=ft(t),s=ft(s),this.isBuilt&&!this.isDisabled&&this.options.movable&&(i(t)&&(a.left=t,o=!0),i(s)&&(a.top=s,o=!0),o&&this.renderCanvas(!0))},zoom:function(t,i){var e=this.canvas;t=ft(t),t=0>t?1/(1-t):1+t,this.zoomTo(e.width*t/e.naturalWidth,i)},zoomTo:function(t,i){var e,s,a,o,h,n=this.options,r=this.canvas,p=r.width,l=r.height,c=r.naturalWidth,g=r.naturalHeight;if(t=ft(t),t>=0&&this.isBuilt&&!this.isDisabled&&n.zoomable){if(s=c*t,a=g*t,i&&(e=i.originalEvent),this.trigger(Z,{originalEvent:e,oldRatio:p/c,ratio:s/c}).isDefaultPrevented())return;e?(o=this.$cropper.offset(),h=e.touches?d(e.touches):{pageX:i.pageX||e.pageX||0,pageY:i.pageY||e.pageY||0},r.left-=(s-p)*((h.pageX-o.left-r.left)/p),r.top-=(a-l)*((h.pageY-o.top-r.top)/l)):(r.left-=(s-p)/2,r.top-=(a-l)/2),r.width=s,r.height=a,this.renderCanvas(!0)}},rotate:function(t){this.rotateTo((this.image.rotate||0)+ft(t))},rotateTo:function(t){t=ft(t),i(t)&&this.isBuilt&&!this.isDisabled&&this.options.rotatable&&(this.image.rotate=t%360,this.isRotated=!0,this.renderCanvas(!0))},scale:function(t,s){var a=this.image,o=!1;e(s)&&(s=t),t=ft(t),s=ft(s),this.isBuilt&&!this.isDisabled&&this.options.scalable&&(i(t)&&(a.scaleX=t,o=!0),i(s)&&(a.scaleY=s,o=!0),o&&this.renderImage(!0))},scaleX:function(t){var e=this.image.scaleY;this.scale(t,i(e)?e:1)},scaleY:function(t){var e=this.image.scaleX;this.scale(i(e)?e:1,t)},getData:function(i){var e,s,a=this.options,o=this.image,h=this.canvas,n=this.cropBox;return this.isBuilt&&this.isCropped?(s={x:n.left-h.left,y:n.top-h.top,width:n.width,height:n.height},e=o.width/o.naturalWidth,t.each(s,function(t,a){a/=e,s[t]=i?Bt(a):a})):s={x:0,y:0,width:0,height:0},a.rotatable&&(s.rotate=o.rotate||0),a.scalable&&(s.scaleX=o.scaleX||1,s.scaleY=o.scaleY||1),s},setData:function(e){var s,a,o,h=this.options,n=this.image,r=this.canvas,p={};t.isFunction(e)&&(e=e.call(this.element)),this.isBuilt&&!this.isDisabled&&t.isPlainObject(e)&&(h.rotatable&&i(e.rotate)&&e.rotate!==n.rotate&&(n.rotate=e.rotate,this.isRotated=s=!0),h.scalable&&(i(e.scaleX)&&e.scaleX!==n.scaleX&&(n.scaleX=e.scaleX,a=!0),i(e.scaleY)&&e.scaleY!==n.scaleY&&(n.scaleY=e.scaleY,a=!0)),s?this.renderCanvas():a&&this.renderImage(),o=n.width/n.naturalWidth,i(e.x)&&(p.left=e.x*o+r.left),i(e.y)&&(p.top=e.y*o+r.top),i(e.width)&&(p.width=e.width*o),i(e.height)&&(p.height=e.height*o),this.setCropBoxData(p))},getContainerData:function(){return this.isBuilt?this.container:{}},getImageData:function(){return this.isLoaded?this.image:{}},getCanvasData:function(){var i=this.canvas,e={};return this.isBuilt&&t.each(["left","top","width","height","naturalWidth","naturalHeight"],function(t,s){e[s]=i[s]}),e},setCanvasData:function(e){var s=this.canvas,a=s.aspectRatio;t.isFunction(e)&&(e=e.call(this.$element)),this.isBuilt&&!this.isDisabled&&t.isPlainObject(e)&&(i(e.left)&&(s.left=e.left),i(e.top)&&(s.top=e.top),i(e.width)?(s.width=e.width,s.height=e.width/a):i(e.height)&&(s.height=e.height,s.width=e.height*a),this.renderCanvas(!0))},getCropBoxData:function(){var t,i=this.cropBox;return this.isBuilt&&this.isCropped&&(t={left:i.left,top:i.top,width:i.width,height:i.height}),t||{}},setCropBoxData:function(e){var s,a,o=this.cropBox,h=this.options.aspectRatio;t.isFunction(e)&&(e=e.call(this.$element)),this.isBuilt&&this.isCropped&&!this.isDisabled&&t.isPlainObject(e)&&(i(e.left)&&(o.left=e.left),i(e.top)&&(o.top=e.top),i(e.width)&&(s=!0,o.width=e.width),i(e.height)&&(a=!0,o.height=e.height),h&&(s?o.height=o.width/h:a&&(o.width=o.height*h)),this.renderCropBox())},getCroppedCanvas:function(i){var e,s,a,o,h,n,r,p,l,d,g;return this.isBuilt&&this.isCropped&&ut?(t.isPlainObject(i)||(i={}),g=this.getData(),e=g.width,s=g.height,p=e/s,t.isPlainObject(i)&&(h=i.width,n=i.height,h?(n=h/p,r=h/e):n&&(h=n*p,r=n/s)),a=yt(h||e),o=yt(n||s),l=t("<canvas>")[0],l.width=a,l.height=o,d=l.getContext("2d"),i.fillColor&&(d.fillStyle=i.fillColor,d.fillRect(0,0,a,o)),d.drawImage.apply(d,function(){var t,i,a,o,h,n,p=c(this.$clone[0],this.image),l=p.width,d=p.height,u=[p],f=g.x,m=g.y;return-e>=f||f>l?f=t=a=h=0:0>=f?(a=-f,f=0,t=h=mt(l,e+f)):l>=f&&(a=0,t=h=mt(e,l-f)),0>=t||-s>=m||m>d?m=i=o=n=0:0>=m?(o=-m,m=0,i=n=mt(d,s+m)):d>=m&&(o=0,i=n=mt(s,d-m)),u.push(yt(f),yt(m),yt(t),yt(i)),r&&(a*=r,o*=r,h*=r,n*=r),h>0&&n>0&&u.push(yt(a),yt(o),yt(h),yt(n)),u}.call(this)),l):void 0},setAspectRatio:function(t){var i=this.options;this.isDisabled||e(t)||(i.aspectRatio=vt(0,t)||NaN,this.isBuilt&&(this.initCropBox(),this.isCropped&&this.renderCropBox()))},setDragMode:function(t){var i,e,s=this.options;this.isLoaded&&!this.isDisabled&&(i=t===lt,e=s.movable&&t===ct,t=i||e?t:gt,this.$dragBox.data(tt,t).toggleClass(M,i).toggleClass(k,e),s.cropBoxMovable||this.$face.data(tt,t).toggleClass(M,i).toggleClass(k,e))}},v.DEFAULTS={viewMode:0,dragMode:"crop",aspectRatio:NaN,data:null,preview:"",responsive:!0,restore:!0,checkCrossOrigin:!0,checkOrientation:!0,modal:!0,guides:!0,center:!0,highlight:!0,background:!0,autoCrop:!0,autoCropArea:.8,movable:!0,rotatable:!0,scalable:!0,zoomable:!0,zoomOnTouch:!0,zoomOnWheel:!0,wheelZoomRatio:.1,cropBoxMovable:!0,cropBoxResizable:!0,toggleDragModeOnDblclick:!0,minCanvasWidth:0,minCanvasHeight:0,minCropBoxWidth:0,minCropBoxHeight:0,minContainerWidth:200,minContainerHeight:100,build:null,built:null,cropstart:null,cropmove:null,cropend:null,crop:null,zoom:null},v.setDefaults=function(i){t.extend(v.DEFAULTS,i)},v.TEMPLATE='<div class="cropper-container"><div class="cropper-wrap-box"><div class="cropper-canvas"></div></div><div class="cropper-drag-box"></div><div class="cropper-crop-box"><span class="cropper-view-box"></span><span class="cropper-dashed dashed-h"></span><span class="cropper-dashed dashed-v"></span><span class="cropper-center"></span><span class="cropper-face"></span><span class="cropper-line line-e" data-action="e"></span><span class="cropper-line line-n" data-action="n"></span><span class="cropper-line line-w" data-action="w"></span><span class="cropper-line line-s" data-action="s"></span><span class="cropper-point point-e" data-action="e"></span><span class="cropper-point point-n" data-action="n"></span><span class="cropper-point point-w" data-action="w"></span><span class="cropper-point point-s" data-action="s"></span><span class="cropper-point point-ne" data-action="ne"></span><span class="cropper-point point-nw" data-action="nw"></span><span class="cropper-point point-sw" data-action="sw"></span><span class="cropper-point point-se" data-action="se"></span></div></div>',v.other=t.fn.cropper,t.fn.cropper=function(i){var a,o=s(arguments,1);return this.each(function(){var e,s,h=t(this),n=h.data($);if(!n){if(/destroy/.test(i))return;e=t.extend({},h.data(),t.isPlainObject(i)&&i),h.data($,n=new v(this,e))}"string"==typeof i&&t.isFunction(s=n[i])&&(a=s.apply(n,o))}),e(a)?this:a},t.fn.cropper.Constructor=v,t.fn.cropper.setDefaults=v.setDefaults,t.fn.cropper.noConflict=function(){return t.fn.cropper=v.other,this}});
if(!String.prototype.trim){String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,'');};}
angular.module('ngImgLoad',[]).directive('ngImgLoad',['$parse',function($parse){return{link:function(scope,elem,attrs){var fn=$parse(attrs.ngImgLoad);elem.on('load',function(event){scope.$apply(function(){fn(scope,{$event:event});});});}};}]);var app=angular.module('remembr',['ngResource','ngAnimate','wu.masonry','ui.router','angularFileUpload','remembrConfig','LocalStorageModule','ngImgLoad']);app.config(function($locationProvider){$locationProvider.html5Mode(true).hashPrefix('!');});app.run(function($FB){window.twttr=(function(d,s,id)
{var js;var fjs=d.getElementsByTagName(s)[0];var t=window.twttr||{};if(d.getElementById(id))
return;js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f)
{t._e.push(f);};return t;}(document,"script","twitter-wjs"));});app.config(['$interpolateProvider','$compileProvider',function($interpolateProvider,$compileProvider){$interpolateProvider.startSymbol('{[{').endSymbol('}]}');$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|javascript):/);}]);app.factory('vimeoService',['$rootScope',function($rootScope){var vimeoService={};vimeoService.play=function(){$('#remembrvid').css('display','block').css('background-position','top center');vimeoService.post('play');};vimeoService.pause=function(){vimeoService.post('pause');};vimeoService.post=function(action,value){var player=$('iframe');var url=window.location.protocol+player.attr('src').split('?')[0];var data={method:action};if(value){data.value=value;}
var message=JSON.stringify(data);player[0].contentWindow.postMessage(message,url);};return vimeoService;}]);app.controller('MemoryDetailCtrl',['$scope','$stateParams','$state','$timeout','Content','Comment','msgService',function($scope,$stateParams,$state,$timeout,Content,Comment,msgService){var m=Content.get({id:$stateParams.id},function(memory){if(memory.pageurl!=$stateParams.page)
{$state.go('root.page',{page:memory.pageurl});$timeout(function(){$state.go('root.page.fancybox.memory',{page:memory.pageurl,id:memory.id})},2000);}
else
{$scope.memory=m;}},function(error){$state.go('.^.^');msgService.inform("An error occurred retrieving this memory",'error');});var comments=Comment.list({id:$stateParams.id},function(){$scope.comments=comments});$scope.comment='';$scope.create=function(){var cmt=new Comment({memory:$scope.memory.id,text:$scope.comment});cmt.$create(function(c){$scope.comments.unshift(c);$scope.comment='';angular.forEach($scope.$root.page.memories,function(m){if(m.id==$scope.memory.id)
{m.numbercomments++;}});});};}]);app.factory('httpRequestInterceptor',['$q','$location','$injector','$timeout','$stateParams',function($q,$location,$injector,$timeout,$stateParams){return{'responseError':function(rejection){if(rejection.status===401)
{var fromState=$injector.get('$state');$timeout(function(){switch(fromState['current']['name']){case'root.messages':$injector.get('$state').go('root.messages.fancybox.login',$stateParams,{location:false});break;case'root.page':case'root.page.error':$injector.get('$state').go('root.page.fancybox.login',$stateParams,{location:false});break;}},2000);}
return $q.reject(rejection);}};}]);app.factory('User',['$resource',function($resource){return $resource(null,{},{get:{method:'GET',url:'/json/user/get'}});}]);app.factory('SearchPages',['$resource',function($resource){return $resource(null,{},{get:{method:'GET',url:'/json/search/get/searchterm/:searchterm',params:{searchterm:'@searchterm'}},getType:{method:'GET',url:'/json/search/get/searchterm/:searchterm/searchtype/:searchtype',params:{searchterm:'@searchterm',searchtype:'@searchtype'}},getRecent:{method:'GET',url:'/json/search/recent'},getRandom:{method:'GET',url:'/json/search/random'},getRotators:{method:'GET',url:'/json/search/rotators'}});}]);app.factory('Facebook',['$resource',function($resource){return $resource(null,{},{getFriends:{method:'GET',url:'/json/user/facebook-friends',isArray:true}});}]);app.factory('SocialMedia',['$resource',function($resource){return $resource(null,{},{get:{method:'GET',url:'/json/dashboard/social-media'}});}]);app.factory('SharedMemories',['$resource','$rootScope',function($resource,$rootScope){return $resource(null,{},{get:{method:'GET',url:'/json/dashboard/get-shared-memories'}});}]);app.factory('MessagesInbox',['$resource','$rootScope',function($resource,$rootScope){return $resource(null,{},{get:{method:'GET',url:'/json/messages/get-inbox'},getUnreadMessagesNumber:{method:'GET',url:'/json/messages/get-unread-messages-number'},getNewMessages:{method:'GET',url:'/json/messages/get-new-messages'}});}]);app.factory('Notifications',['$resource','$rootScope',function($resource,$rootScope){return $resource(null,{},{get:{method:'GET',url:'/json/notifications/get-notifications'},getNewNotifications:{method:'GET',url:'/json/notifications/get-new-notifications'},getNotificationsHistory:{method:'GET',url:'/json/notifications/get-notifications-history'}});}]);app.factory('MessagesOutbox',['$resource','$rootScope',function($resource,$rootScope){return $resource(null,{},{get:{method:'GET',url:'/json/messages/get-outbox'},setReadDate:{method:'POST',url:'/json/messages/set-read-date/id/:id',params:{id:'@id'},transformResponse:function(data){return data;}}});}]);app.factory('UserSettings',['$q','$http',function($q,$http){var deferred=$q.defer();$http.get('/json/dashboard/get-settings').then(function(resp){deferred.resolve(resp.data);});return deferred.promise;}]);app.factory('Page',['$resource','$stateParams',function($resource,$stateParams){var defparams={url:'@url',lang:function(){return $stateParams.lang||null;}};return $resource(null,{},{get:{method:'GET',url:'/json/:url',params:{url:'@url'}},update:{method:'POST',url:'/json/:lang/:url/update:part',params:defparams},create:{method:'POST',url:'/json/create-page/create'},updateDraft:{method:'POST',url:'/json/user/update-draft-page'},deleteDraft:{method:'GET',url:'/json/user/delete-draft-page'},getDraft:{method:'GET',url:'/json/user/get-draft-page'},invite:{method:'POST',url:'/json/:url/invite',params:{url:'@url'}},requestAccess:{method:'POST',url:'/json/:lang/:url/request-access',params:defparams},grantAccess:{method:'POST',url:'/json/:lang/:url/grant-access',params:{url:'@url',params:defparams}},urlSuggestions:{isArray:true,method:'POST',url:'/json/create-page/get-url-suggestions',transformResponse:function(data){return angular.fromJson(data).suggestions;}},checkAvailable:{method:'GET',url:'/json/create-page/check-url-available/url/:url',params:{url:'@url'}}});}]);app.factory('Comment',['$resource',function($resource){return $resource(null,{},{list:{method:'GET',isArray:true,url:'/json/comment/list/id/:id'},create:{method:'POST',url:'/comment/create'}});}]);app.factory('Content',['$resource',function($resource){return $resource(null,{},{get:{method:'GET',url:'/json/content/get/id/:id'},getAnonymous:{method:'GET',url:'/json/:url/get-anonymous-condolence/:editkey'},saveAnonymous:{method:'POST',url:'/json/:url/save-anonymous-condolence/:editkey',isArray:false},deleteAnonymous:{method:'GET',url:'/json/:url/delete-anonymous-condolence/:editkey',isArray:false},save:{method:'POST',url:'/json/:lang/:url/content/save'},list:{method:'GET',isArray:true,url:'/json/:url/content/index/:max/:from/:to',transformResponse:function(data){return angular.fromJson(data).memories;}}});}]);app.factory('translatorService',['$rootScope','$stateParams','$http','$locale',function($rootScope,$stateParams,$http,$locale){var translatorService={};angular.forEach(['nl','nl-be','en'],function(lang){$http.get('/language/'+lang+'/l10n.js').then(function(res){translatorService[lang]=res.data;});});var getlang=function($stateParams,$rootScope){return($stateParams.lang||$rootScope.$eval('user.language')||navigator.language||navigator.userLanguage||'en').substring(0,2);}.bind(undefined,$stateParams,$rootScope);translatorService.getLang=getlang;var lang=getlang();$rootScope.$watch(getlang,function(val){lang=val;});translatorService.translate=function(key){lang=getlang();if(translatorService[lang]&&translatorService[lang][key])
{return translatorService[lang][key];}
return key;};return translatorService;}]);app.factory('msgTabService',['$rootScope','MessagesInbox','MessagesOutbox',function($rootScope,MessagesInbox,MessagesOutbox){var msgTabService={};var tab="inbox";var newto="";msgTabService.set=function(value){tab=value;};msgTabService.get=function(){return tab;};msgTabService.openTab=function(value){if($rootScope.currenttab!==value)
{$rootScope.currenttab=value;msgTabService.set(value);}};msgTabService.setNewto=function(value){newto=value;};msgTabService.getNewto=function(){return newto;};return msgTabService;}]);app.factory('pollingService',['$timeout','MessagesInbox','$rootScope','msgTabService','$state','Notifications','POLLING_INTERVAL',function($timeout,MessagesInbox,$rootScope,msgTabService,$state,Notifications,POLLING_INTERVAL){var pollingService={};var running=false;var timer;pollingService.start=function(){var self=this;if(!running){running=true;self.run();}};pollingService.stop=function(){running=false;$timeout.cancel(timer);};pollingService.run=function(){if(angular.isObject($rootScope.inbox)){MessagesInbox.getNewMessages({},function(result){for(index=0;index<result.messages.length;++index){$rootScope.inbox.messages=$rootScope.inbox.messages.filter(function(new_id,existing_message){return existing_message.id!==new_id;}.bind(null,result.messages[index].id));$rootScope.inbox.messages.push(result.messages[index]);console.log(result.messages[index]);}});}
MessagesInbox.getUnreadMessagesNumber({},function(model){$rootScope.newmessagescounter=model.number;});Notifications.getNewNotifications({},function(result){if(result.notifications.length>0){for(index=0;index<result.notifications.length;++index){$rootScope.notifications.notifications.push(result.notifications[index]);}}});timer=$timeout(pollingService.run,POLLING_INTERVAL);};return pollingService;}]);app.factory('logoutService',['$rootScope','User','$http','$state','pollingService',function($rootScope,User,$http,$state,pollingService){var logoutService={};logoutService.logout=function(){var logout_url='/provider/logout-provider/default';$http({url:logout_url,method:"POST"}).success(function(data,status,headers,config){if(data==='done')
{pollingService.stop();var pages=['root.dashboard','root.usersettings','root.landingpage','root.password','root.usersettings.email','root.newmsg','root.messages','root.notifications','root.usersettings.password'];if(pages.indexOf($state.current.name)!==-1){$state.transitionTo('root.home');}
else
{$state.go($state.current.name,{},{reload:true});}
$rootScope.$root.user=User.get();}
else
{}}).error(function(data,status,headers,config){$rootScope.status=status;});};return logoutService;}]);function setCookie(cname,cvalue,exdays){var d=new Date();d.setTime(d.getTime()+(exdays*24*60*60*1000));var expires="expires="+d.toGMTString();document.cookie=cname+"="+cvalue+"; "+expires;}
function getCookie(cname){var name=cname+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i].trim();if(c.indexOf(name)===0)
return c.substring(name.length,c.length);}
return"";}
app.controller('commentsCtrl',['$scope','$http','msgService',function($scope,$http,msgService){$scope.deletecmt=function(comment){msgService.inform("Are you sure?","confirm",function(confirm){if(confirm)
{var formdata={'id':comment.id};$http({url:'/comment/delete-comment',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'ok':var index=$scope.comments.indexOf(comment);$scope.comments.splice(index,1);msgService.inform("The comment is deleted.","success");break;case'error':msgService.inform("Sorry, something went wrong.","warning");break;}}).error(function(data,status,headers,config){$scope.status=status;msgService.inform("Sorry, something went wrong.","warning");});}});};}]);app.controller('cookieCtrl',['$scope','msgService',function($scope,msgService){var acceptCookies=getCookie("acceptCookies");if(!acceptCookies){$scope.showCookieMsg=true;}
$scope.removeCookieMsg=function(){setCookie('acceptCookies','true',20*365);$scope.showCookieMsg=false;};if(document.all&&!window.atob){msgService.inform("Your internet browser is outdated en is not supported by Remembr. For a better experience we recommend you to update your browser to a newer version.","error");}}]);app.controller('messagesCtrl',['$scope','$http','msgService','$state','$rootScope','Page','MessagesInbox','MessagesOutbox','$timeout','$filter','msgTabService','orderByFilter',function($scope,$http,msgService,$state,$rootScope,Page,MessagesInbox,MessagesOutbox,$timeout,$filter,msgTabService,orderByFilter){$scope.openTab=function(tab)
{msgTabService.openTab(tab);};$scope.openTab(msgTabService.get());if(msgTabService.get()==='new'){$scope.newto=msgTabService.getNewto();}
$scope.$watch('user',function(newValue,oldValue){if(newValue===oldValue){return;}
$scope.updated++;});$scope.openInboxFirst=function(){$rootScope.inbox.messages=orderByFilter($rootScope.inbox.messages,'senddate','reverse');msgTabService.openTab('inbox');if($scope.inbox.messages.length)
{markAsRead($scope.inbox.messages[0]);$state.go('root.messages',{'msgid':$scope.inbox.messages[0].id});}
else
{$state.go('root.messages');}};$scope.openInbox=function(msg){msgTabService.openTab('inbox');markAsRead(msg);$state.go('root.messages',{'msgid':msg.id});};$scope.mailUser=function(user){msgTabService.setNewto(user);msgTabService.openTab('new');$state.go('root.newmsg');};$scope.setSelected=function(msg){$scope.selected=msg.id;markAsRead(msg);};markAsRead=function(msg){if(typeof msg!=='undefined'&&msg.readdate==='')
{msg.newmsg=false;msg.readdate=MessagesOutbox.setReadDate({'id':msg.id});$rootScope.newmessagescounter--;$rootScope.inbox.messages.forEach(function(new_id,msg){if(msg.id===new_id)
msg.new=false;}.bind(null,msg.id));}};$scope.deleteMsg=function(msg,box){var formdata={'id':msg.id,'box':box};$http({url:'/json/messages/delete',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'done':msg.deleted=true;switch(box){case'in':var index=$scope.inbox.messages.indexOf(msg);$scope.inbox.messages.splice(index,1);break;case'out':var index=$scope.outbox.messages.indexOf(msg);$scope.outbox.messages.splice(index,1);break;}
break;default:msgService.inform("We could not delete this e-mail.","error");break;}}).error(function(data,status,headers,config){msgService.inform("We could not delete this e-mail.","error");$scope.status=status;});};$scope.replyMsg=function(msg){$scope.reply=angular.copy(msg);$scope.reply.title='Re: '+$scope.reply.title;$scope.reply.content='<br />--------------------------------------------------<br />'+$scope.reply.content;msgTabService.openTab('reply');};$scope.cancelReplyForm=function(){msgTabService.openTab('inbox');};$scope.submitNewMsgForm=function(){var formdata={'id':$scope.newto.id,'title':$scope.newto.title,'content':$scope.newto.content};$http({url:'/json/messages/new',data:formdata,method:"POST"}).success(function(result,status,headers,config){msgService.inform("Your message has been sent.","info");$rootScope.outbox=MessagesOutbox.get();msgTabService.openTab('inbox');}).error(function(data,status,headers,config){msgService.inform("We could not send your message.","error");msgTabService.openTab('inbox');$scope.status=status;});};$scope.submitReplyForm=function(){var formdata={'id':$scope.reply.id,'message_id':$scope.reply.message_id,'title':$scope.reply.title,'content':$scope.reply.content};$http({url:'/json/messages/reply',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'done':msgService.inform("Your message has been sent.","info");$rootScope.outbox=MessagesOutbox.get();msgTabService.openTab('inbox');break;default:msgService.inform("We could not send this message.","error");msgTabService.openTab('inbox');break;}}).error(function(data,status,headers,config){$scope.status=status;});};$scope.grantaccess=function(msg)
{Page.grantAccess({url:msg.extra.pageurl},{msgid:msg.message_id},function(resp){msg.extra.granted=true;msgService.inform('The invation has been granted','info');},function(resp){msgService.inform('An error occured trying to grant the invitation','error');console.log(resp);});}}]);app.controller('sharedMemoriesCtrl',['$scope','$timeout','$state',function($scope,$timeout,$state){$scope.popMemory=function(memory,popup){if(popup){$timeout(function(){$state.go('root.page.fancybox.memory',{'id':memory.id});},2000);}};}]);
/*! bzSlider v0.1.0 by Vitalii Savchuk(esvit666@gmail.com) - https://github.com/esvit/bz-slider - New BSD License */
var sliderController=['$scope','$timeout','$parse','$element',function($scope,$timeout,$parse,$element){var timeOut=null;$scope.slides=$scope.slides||$scope.$root.slides||[];$scope.delay=$scope.delay||5000;$scope.$play=false;$scope.$slideIndex=0;$scope.slides_found=null;$scope.html_slides=$('.slide',$element);$scope.refresh=function(){$scope.html_slides.each(function(i,slide){if(i!==$scope.$slideIndex)
$(slide).addClass('ng-hide');else
$(slide).removeClass('ng-hide');});};if($scope.html_slides.length>0){$scope.slides_found=$scope.html_slides.length;$scope.refresh();}
$scope.length=function(){return $scope.slides_found||$scope.slides.pages.length;};$scope.play=function(){timeOut=$timeout(function(){$scope.next();$scope.play();},$scope.delay);$scope.$play=true;};$scope.stop=function(){$timeout.cancel(timeOut);timeOut=null;$scope.$play=false;};$scope.next=function(){var total=$scope.length();if(total>0){$scope.$slideIndex=($scope.$slideIndex===total-1)?0:$scope.$slideIndex+1;}
$scope.refresh();};$scope.prev=function(){var total=$scope.length();if(total>0){$scope.$slideIndex=($scope.$slideIndex===0)?total-1:$scope.$slideIndex-1;}
$scope.refresh();};$scope.setIndex=function(index){$scope.$slideIndex=index;$scope.refresh();};}];app.controller('notificationsCtrl',['$http','$scope','$state','$timeout','$rootScope','Notifications',function($http,$scope,$state,$timeout,$rootScope,Notifications){$scope.readNotification=function(notification,popup){var formdata={'id':notification.id};if(popup){$timeout(function(){$state.go('root.page.fancybox.memory',{'id':notification.memory_id});},2000);}
$http({url:'/json/notifications/set-read',data:formdata,method:"POST"}).success(function(result,status,headers,config){var index=$scope.notifications.notifications.indexOf(notification);$scope.notifications.notifications.splice(index,1);$scope.newnotificationscounter--;}).error(function(data,status,headers,config){$scope.status=status;});};$scope.markNotifications=function(){$http({url:'/json/notifications/set-read-all',method:"POST"}).success(function(result,status,headers,config){$rootScope.notifications=Notifications.get();}).error(function(data,status,headers,config){$scope.status=status;});};}]);app.controller('CreateContentCtrl',['$scope','Content','$upload','imagePreview','msgService','$state','uploadService','translatorService',function($scope,Content,$upload,imagePreview,msgService,$state,uploadService,translatorService){$scope.newContent={labels:{},type:'memory',anonymousEmail:undefined,lang:translatorService.getLang()};$scope.currenttab='memory';$scope.currentform='memory';$scope.openTab=function($scope,tab)
{if($scope.currenttab!==tab)
{$scope.currenttab=tab;$scope.currentform=tab;$scope.newContent.type=tab;$scope.showAll(tab);}}.bind(undefined,$scope);if($scope.$root!=$scope)
$scope.$root.openTab=$scope.openTab;$scope.canocialUrl=function(){return'https://remembr.com/'+$scope.page.url;};$scope.canocialImageUrl=function(){return'https://remembr.com/minify?files='+$scope.page.photo+'&resize=w[640]h[640]e[true]';};$scope.openForm=function(form)
{if(form!='condolence'&&!$scope.user.loggedin)
{$state.go('root.page.fancybox.login');}
else if($scope.currentform!==form)
{$scope.currentform=form;$scope.newContent.type=form;}};$scope.submit=function()
{if(($scope.newContent.type==='media'||$scope.newContent.type==='photo')&&!$scope.selectedFile)
{msgService.inform("Please select an image.",'warning');return;}
if(!$scope.user.loggedin&&!$scope.newContent.username)
{msgService.inform("Please enter a username.",'warning');return;}
form_email=$('.condolance form[name=content] input[name=email]').val();form_email=form_email!==''?form_email:undefined;if(!$scope.user.loggedin&&!$scope.newContent.anonymousEmail||$scope.newContent.anonymousEmail==='')
{var form_email=$('.condolance form[name=content] input[name=email]').val();if(form_email===''||form_email===undefined)
msgService.inform("Please enter your email address so you can edit or remove your condolence message.",'warning');else
msgService.inform("Please enter a valid email address.",'warning');return;}
$scope.ui.active='body';$scope.ui.readmore=false;$scope.saving=true;var callback=function(){Content.save({url:$scope.page.url,lang:translatorService.getLang()},$scope.newContent,function(data){$scope.saving=false;$scope.page.memories.unshift(data);$scope.newContent={labels:{},type:$scope.newContent.type,anonymousEmail:undefined,lang:translatorService.getLang()};$scope.dataUrl='';$scope.selectedFile=null;},function(data){$scope.saving=false;});};$scope.startupload(callback);};$scope.onFileSelect=function($files){if(document.documentElement.scrollWidth<640)
{window.location.hash="";window.location.hash="mediaupload";}
uploadService.process($files,$scope,false);};$scope.startupload=function(callback){if(!$scope.selectedFile||($scope.newContent.type!=='media'&&$scope.newContent.type!=='photo'))
{callback();return;}
$scope.newContent.type='photo';$scope.progress=0;$scope.upload=$upload.upload({url:'/json/'+$scope.page.url+'/file-upload',method:'POST',file:$scope.selectedFile,fileFormDataName:'file'}).success(function(response){$scope.newContent.photoid=response.photo;if(angular.isFunction(callback))
callback();}).error(function(response){msgService.inform("There was an error while uploading the image.",'error');$scope.saving=false;}).progress(function(evt){$scope.progress=parseInt(Math.min(100.0,100.0*evt.loaded / evt.total));});};}]);app.controller('mainCtrl',['$scope','$window','$location','translatorService','Page','User','$injector',function($scope,$window,$location,translatorService,Page,User,$injector){$scope.$root.ui={active:'body','readmore':false};$scope.$root.$on('$stateChangeSuccess',function(event,toState,toParams,fromState,fromParams){if($window.ga)
{$window.ga('send','pageview',{page:$location.path()});}
if(toState.title)
{var title=angular.isArray(toState.title)?$injector.invoke(toState.title):toState.title;document.title=title;}});$scope.$root.getUsername=function(user,deflt)
{if(!user)
{return deflt;}
else if(user.firstname&&user.lastname)
{return user.firstname+' '+user.lastname;}
else
{return user.firstname||user.lastname||deflt;}};$scope.$root.translate=function(key)
{return translatorService.translate(key);};$scope.$root.imgresize=function(file,width,height)
{console.log(file);if(!file)
{return file;}
if(file.match(/^(?:https?:)?\/\//))
{return file;}
return'/minify?files='+file+'&resize=w['+width+']h['+height+']f[true]';};$scope.$root.logvar=function(x){console.log(x);return'';};$scope.$root.imgcrop=function(file,roi,width,height)
{if(!file)
{return file;}
if(file.match(/^(?:https?:)?\/\//))
{return file;}
if(roi===undefined||roi===null||roi.x===null||roi.y===null||roi.width===null||roi.height===null)
{return'/minify?files='+file+'&resize=w['+width+']h['+height+']f[true]';}
return'/minify?files='+file+'&crop=width['+roi.width+']height['+roi.height+']x['+roi.x+']y['+roi.y+']&resize=w['+width+']h['+height+']';};}]);app.animation('.slide',function(){return{enter:function(element,done){element.hide().slideDown('fast',done);},leave:function(element,done){element.slideUp('fast',done);}};});app.factory('imagePreview',['$timeout',function($timeout){if(!window.FileReader)
{return function(){};}
return function(file,callback){if(file.type.indexOf('image')===-1){return;}
var fileReader=new FileReader();fileReader.onload=function(e){$timeout(function(){callback(e.target.result);});};fileReader.readAsDataURL(file);};}]);app.filter('encodeURIComponent',function(){return window.encodeURIComponent;});function stringifyCompare(x,y){return JSON.stringify(x)===JSON.stringify(y);}
app.filter('unsafe',function($sce){return $sce.trustAsHtml;});app.filter('dateforlang',['translatorService',function(translatorService){return function(date,format){if(typeof(date)==='string'){var values=date.split("-").map(function(x){return parseInt(x);});date=new Date(values[0],values[1]-1,values[2]);}else if(!date){date=new Date();}
var lang=translatorService.getLang();if(lang==="nl-be")
lang="nl";return moment(date).lang(lang).format(format[lang]);};}]);app.filter('unsafe',function($sce){return function(val){return $sce.trustAsHtml(val);};});app.filter('htmlToPlaintext',function(){return function(text){return String(text).replace(/<[^>]+>/gm,'').replace('&nbsp;',' ');};});app.filter('bytypeandlabel',function(){var checktype=function(stypes,vtype)
{return stypes[vtype]===true;}
var checklabels=function(slabels,vlabels)
{for(var i=0;i<vlabels.length;i++)
{if(slabels[vlabels[i].id]===true){return true;}}
return false;}
return function(memories,types,labels){var items={types:types||{},labels:labels||{},anylabel:true,out:[]};angular.forEach(items.labels,function(value){this.anylabel&=!value;},items);angular.forEach(memories,function(value,key){if(checktype(this.types,value.type)&&(this.anylabel||checklabels(this.labels,value.labels)))
{this.out.push(value);}},items);return items.out;};});app.filter('dateplaceholder',['$rootScope','$stateParams',function($scope,$stateParams)
{return function(dateformat){if(typeof dateformat!=="undefined"){dateformat=dateformat.toUpperCase().replace('YY','YYYY');if(($scope.user.lang||$stateParams.lang)==='nl')
{dateformat=dateformat.replace('YYYY','JJJJ');}
return dateformat;}};}]);app.filter('dpToNg',function()
{return function(dateformat){if(typeof dateformat!=="undefined"){return dateformat.replace('mm','MM').replace('yy','yyyy');}};});app.filter('startFrom',function(){return function(input,start){if(typeof input!=='undefined'){start=+start;return input.slice(start);}};});app.filter('groupBy',function(){return function(list,group_by){var filtered=[];var prev_item=null;var group_changed=false;var new_field=group_by+'_CHANGED';angular.forEach(list,function(item){group_changed=false;if(prev_item!==null){if(prev_item[group_by]!==item[group_by]){group_changed=true;}}else{group_changed=true;}
if(group_changed){item[new_field]=true;}else{item[new_field]=false;}
filtered.push(item);prev_item=item;});return filtered;};});app.controller('UploadCtrl',['$scope','$upload','imagePreview',function($scope,$upload,imagePreview){$scope.onFileSelect=function($files){$scope.progress=-1;if($scope.upload){$scope.upload.abort();}
$scope.upload=null;$scope.uploadResult=null;$scope.dataUrl='';if($files.length)
{imagePreview($files[0],function(url){$scope.dataUrl=url;});$scope.progress=-1;$scope.selectedFile=$files[0];$scope.start();}};$scope.start=function(){$scope.progress=0;$scope.upload=$upload.upload({url:'/json/'+$scope.page.url+'/file-upload',method:'POST',file:$scope.selectedFile,fileFormDataName:'file'}).success(function(response){$scope.uploadResult=response.data;}).error(function(response){$scope.uploadResult=response.data;}).progress(function(evt){$scope.progress=parseInt(Math.min(100.0,100.0*evt.loaded / evt.total));});};}]);app.factory('msgService',['$rootScope','$http',function($rootScope,$http){var messages=[];var msgService={};var translationcache={};var conf;var cb_function;var l10n;msgService.setTranslation=function(lang){var self=this;if(lang!==''&&lang!==null){self.loadLanguage(lang);}
else
{$http.get('/ajax/grab-language').then(function(res){lang=res['data'];self.loadLanguage(lang);});}};msgService.loadLanguage=function(lang)
{if(translationcache[lang])
{l10n=translationcache[lang];}
else
{$http.get('/language/'+lang+'/l10n.js').then(function(res){translationcache[lang]=l10n=res.data;});}};msgService.inform=function(msg,type,callback,links){if(links==undefined)links=[];conf=false;if(typeof callback!=="undefined"){cb_function=callback;}
msgService.hideAll();if(angular.isObject(l10n)){infomsg=l10n[msg]?l10n[msg]:msg;}
else
{infomsg=msg;}
messages.push({msg:infomsg,type:type,conf:type==="confirm",links:links});if(!$rootScope.$$phase){$rootScope.$apply();}};msgService.confirm=function(info,userinput){this.remove(info);cb_function(userinput);};msgService.allInfos=function(){return messages;};msgService.hideAll=function(){messages=[];};msgService.remove=function(info){if(idx=$.inArray(info,messages)!=-1){messages.splice(messages[idx],1);}};return msgService;}]);app.factory('dashboardVisibility',['$rootScope',function($rootScope){return{set:function(bool){$rootScope.user.$get(function(){$rootScope.editdashboard=bool;var checkuserdata=!/^(\d{4})\-(\d{2})\-(\d{2})$/.test($rootScope.user.dateofbirth)||!/^[a-zA-Z\u0080-\u024F\s\/\-\)\(\`\.,\"\']+$/.test($rootScope.user.residence)||!/^[a-zA-Z\u0080-\u024F\s\/\-\)\(\`\.,\"\']+$/.test($rootScope.user.country)||$rootScope.user.gender===''||$rootScope.user.language===''||$rootScope.user.dateofbirth===null||$rootScope.user.residence===null||$rootScope.user.country===null||$rootScope.user.gender===null||$rootScope.user.language===null;if(checkuserdata){$rootScope.editdashboard=true;}});}};}]);app.controller('searchCtrl',['$scope','msgService','$state','$http',function($scope,msgService,$state,$http){$scope.submitPageSearchForm=function(){if(angular.isObject($scope.search)&&$scope.search.searchterm.length>0){$state.go('root.search',{'searchterm':$scope.search.searchterm,search:'search'});$scope.pageSearchForm.$setPristine();$scope.search.searchterm='';}
else
{$state.go('root.search',{'searchterm':'',search:'search'});}};$scope.submitExtendedSearch=function(){if(typeof $scope.search!=='undefined')
{var formdata={'firstname':$scope.search.firstname,'lastname':$scope.search.lastname,'dateofbirth':$scope.search.yearofbirth,'dateofdeath':$scope.search.yearofdeath,'open':$scope.search.open,'private':$scope.search.prive,'type':$scope.search.type,'residence':$scope.search.residence,'country':$scope.search.country,'gender':$scope.search.gender};}
else
{var formdata={'type':'all'};}
$http({url:'/json/search/extended',data:formdata,method:"POST"}).success(function(result,status,headers,config){$scope.searchpages.pages=result;}).error(function(data,status,headers,config){$scope.status=status;});};$scope.open=function(page,$event)
{if(!page.private||$.inArray(page.url,$scope.user.pageaccess)>-1)
{$state.go('root.page',{page:page.url});}
else
{$state.go('root.search.fancybox.private',{page:page.url});}};$scope.resetFilters=function()
{$scope.search=null;};}]);app.controller('footerCtrl',['$scope','$http','msgService','$stateParams',function($scope,$http,msgService,$stateParams){$scope.totop=function(){$("html, body").animate({scrollTop:0},200);};$scope.submitNewsletterForm=function(isValid){if(isValid)
{var formdata={'email':$scope.newsletter.email,'lang':$stateParams.lang};$http({url:($stateParams.lang?'/'+$stateParams.lang:'')+'/ajax/sign-newsletter',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'done':msgService.inform("Thank you for subscribing to our newsletter. Please check your e-mail to confirm your subscription.","info");break;case'exists':msgService.inform("This e-mail address is already registered.","warning");break;default:msgService.inform("We could not add your e-mail address.","error");break;}}).error(function(data,status,headers,config){$scope.status=status;});$scope.newsletterForm.$setPristine();$scope.newsletter.email='';}};}]);app.controller('managementCtrl',['$scope','logoutService',function($scope,logoutService){$scope.someSelected=function(object){return Object.keys(object).some(function(key){return object[key];});};$scope.sign_out=function($event){logoutService.logout();};$scope.management=function($event){$event.preventDefault();};}]);app.factory('uploadService',['msgService','imagePreview',function(msgService,imagePreview){var uploadService={};var mainCanvas;var decodedData;uploadService.size=function($file){if($file['size']<5242880){return true;}
msgService.inform("Sorry, this file is to big, it must be smaller then 5Mb","error");return false;};uploadService.process=function($files,$scope,startUpload){$scope.progress=-1;if($scope.upload){$scope.upload.abort();}
$scope.upload=null;$scope.uploadResult=null;$scope.dataUrl='';if($files.length)
{if(uploadService.size($files[0]))
{imagePreview($files[0],function(url){$scope.dataUrl=url;});$scope.progress=-1;$scope.selectedFile=$files[0];if(startUpload){$scope.startupload();}}
else
{$scope.file='';}}};return uploadService;}]);app.controller('dashboardCtrl',['$scope','User','$http','msgService','$state','dashboardVisibility','$rootScope','SocialMedia','imagePreview','$upload','MessagesInbox','MessagesOutbox','logoutService','uploadService',function($scope,User,$http,msgService,$state,dashboardVisibility,$rootScope,SocialMedia,imagePreview,$upload,MessagesInbox,MessagesOutbox,logoutService,uploadService){$scope.editDashboard=function(){dashboardVisibility.set(true);};$scope.cancelEditDashboard=function(){dashboardVisibility.set(false);};$scope.reloadSocialMedia=function(){$rootScope.socialmedia=SocialMedia.get();};$scope.cancelDeleteAccount=function(){$scope.user.deleted=false;};$scope.someSelected=function(object){return Object.keys(object).some(function(key){return object[key];});};$scope.submitDeleteForm=function(isValid){if(isValid)
{msgService.inform("Are you sure you want to delete your account?","confirm",function(confirm){if(confirm){msgService.inform("One moment please, your details are being updated...",'info');$http({url:'/json/dashboard/delete-account',method:"POST"}).success(function(result,status,headers,config){$http({url:'/provider/logout-provider/default',method:"POST"}).success(function(result,status,headers,config){$state.transitionTo('root.home');msgService.inform("Your account will be removed when removal is confirmed.",'info');$scope.$root.user=User.get();}).error(function(data,status,headers,config){$scope.status=status;});}).error(function(data,status,headers,config){$scope.status=status;});}
else
{$scope.user.deleted=false;}});}};$scope.submitEditPwdForm=function(isValid){if(isValid){var formdata={'password':$scope.user.pw1,'password2':$scope.user.pw2};msgService.inform("One moment please, your details are being updated...",'info');$http({url:'/account/update-password',data:formdata,method:"POST"}).success(function(result,status,headers,config){$('#pwdForm').slideUp('fast');msgService.inform("Your new password has been saved; please log in again.",'warning');logoutService.logout();}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("Please make sure all fields are filled out.","warning");}};$scope.submitEditEmailForm=function(isValid){if(isValid){var formdata={'email':$scope.user.email1,'email2':$scope.user.email2};$http({url:'/account/update-email',data:formdata,method:"POST"}).success(function(result,status,headers,config){msgService.inform("One moment please, your data is being updated...",'info');switch(result){case"done":$('#emailForm').slideUp('fast');msgService.inform("Your new e-mail address has been saved; please log in again.",'warning');logoutService.logout();break;case"error":msgService.inform("This e-mail is already in use.",'error');break;}}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("Please make sure all fields are filled out.","warning");}};$scope.submitEditAccountForm=function(isValid,gotostate){if(isValid){var formdata={'name':$scope.user.name,'residence':$scope.user.residence,'dateofbirth':$scope.user.dateofbirth,'country':$scope.user.country,'gender':$scope.user.gender,'language':$scope.user.language};msgService.setTranslation($scope.user.language);$http({url:'/account/update-user',data:formdata,method:"POST"}).success(function(result,status,headers,config){msgService.inform("Your personal details have been saved.",'success');dashboardVisibility.set(false);$state.go(gotostate||'root.dashboard',{'lang':$scope.user.language});}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("Please make sure all fields are filled out.","warning");}};$scope.submitSettingsForm=function(){var formdata={'receivePageMessages':$scope.usersettings.receivePageMessages?$scope.usersettings.receivePageMessages:false,'receiveCommentMessages':$scope.usersettings.receiveCommentMessages?$scope.usersettings.receiveCommentMessages:false,'receivePrivateMessages':$scope.usersettings.receivePrivateMessages?$scope.usersettings.receivePrivateMessages:false,'receiveUpdates':$scope.usersettings.receiveUpdates?$scope.usersettings.receiveUpdates:false,'receiveTips':$scope.usersettings.receiveTips?$scope.usersettings.receiveTips:false,'mailFrequency':$scope.usersettings.mailFrequency?$scope.usersettings.mailFrequency:'weekly'};$http({url:'/json/dashboard/save-settings',data:formdata,method:"POST"}).success(function(result,status,headers,config){$scope.settingsForm.$setPristine();msgService.inform("Your settings have been updated.",'info');}).error(function(data,status,headers,config){$scope.status=status;});};$scope.submitProfilePhoto=function()
{$scope.ui.active='body';$scope.ui.readmore=false;$scope.saving=true;$scope.startupload();};$scope.onFileSelect=function($files){uploadService.process($files,$scope,true);};$scope.startupload=function(){$scope.uploading=true;$scope.progress=0;$scope.upload=$upload.upload({url:'/json/dashboard/file-upload',method:'POST',file:$scope.selectedFile,fileFormDataName:'file'}).success(function(response){$scope.uploading=false;$scope.user.profilephoto=response.photo;$scope.file='';$rootScope.inbox=MessagesInbox.get();$rootScope.outbox=MessagesOutbox.get();}).error(function(response){}).progress(function(evt){$scope.progress=parseInt(Math.min(100.0,100.0*evt.loaded / evt.total));});};}]);app.controller('pagingCtrl',['$scope',function($scope){$scope.range=function(n){return new Array(n);};$scope.toPage=function(nr){$scope.currentPage=nr;};}]);app.controller('ContactCtrl',['$scope','$http','msgService','$state','$stateParams',function($scope,$http,msgService,$state,$stateParams){$scope.submitContactForm=function(isValid){if(isValid){var formdata={'name':$scope.contact.name,'email':$scope.contact.email,'comment':$scope.contact.comment};$http({url:'/ajax/contact',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'done':var lang=$stateParams.lang?$stateParams.lang:'';$state.transitionTo('root.contact_ok',{'lang':lang});break;default:msgService.hideAll();break;}}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("Please fill out all required fields.","warning");}};}]);app.controller('LoginCtrl',['$scope','User','$http','msgService','$rootScope','$compile','$state','dashboardVisibility','$stateParams','$location',function($scope,User,$http,msgService,$rootScope,$compile,$state,dashboardVisibility,$stateParams,$location){$scope.remembrmecheckbox=true;$scope.getLang=function(){return $stateParams.lang||$rootScope.$eval('user.language')||(navigator.language||navigator.userLanguage||'en').substring(0,2);};$scope.postLoginRedirect=function()
{$scope.$root.user=User.get(function(){$('.slide').hide();msgService.hideAll();if(!$scope.$root.user.loggedin){msgService.inform("Unfortunately we could not find your account with these details.","error");return;}
if($stateParams['redirect'])
{document.location=$stateParams['redirect'].replace(/\|/g,'/');return;}
if($state&&$state.current&&!$state.current.name.match(/root\.home/))
{var parentstate=$state.current.name.replace(/\.fancybox\.login.*/,'');if(parentstate)
{$state.go(parentstate,{},{reload:true});return;}}
$state.transitionTo('root.landingpage',{'lang':$scope.$root.user.language||$stateParams.lang},{reload:true});});};$scope.remembrtoggle=function(){$scope.remembrmecheckbox=!$scope.remembrmecheckbox;};$scope.providerlogin=function($idp){msgService.inform("One moment please, we process your data...","info");start_auth("?provider="+$idp);};$scope.submitResetForm=function(isValid,email){if(isValid){msgService.inform("One moment please, we process your data...","info");var formdata={'email':email===undefined?$scope.user.email:email,'lang':$stateParams.lang};$http({url:($stateParams.lang?'/'+$stateParams.lang:'')+'/account/forgotpassword',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'done':$('.slide').slideUp('fast');$.fancybox.close();msgService.inform("We have sent you an e-mail with a link to reset your password.","success");break;case'no-user':msgService.inform("This e-mail address is not yet registered.","warning");break;case'not-valid':msgService.inform("Enter a valid e-mail address.","warning");break;default:msgService.hideAll();break;}}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("A valid e-mail address is required.","warning");}};$scope.resendConfirmationMail=function(isValid,email){if(isValid){lang=this.getLang();$http({url:(lang===undefined?"":"/"+lang)+"/account/resend-confirmation-mail",method:"POST",data:{'email':email===undefined?$scope.user.email:email}}).success(function(result,status,headers,config){switch(result){case'done':msgService.inform("Please confirm your registration by clicking the link in the e-mail.","success");break;case"user-not-found":msgService.inform("Sorry, the e-mail address was not found in our database, this is probably our fault. Please register again or ","error",undefined,[{lab:"contact us and provide the e-mail address.",handler:function(){document.location='/cmscontent/contact';}}]);break;case"already-confirmed":msgService.inform("Your registration has already been confirmed and you are able to log in now.","success");break;default:msgService.inform("Sorry, some unknown error occured.","error",undefined,[{lab:"Please contact us.",handler:function(){document.location='/cmscontent/contact';}}]);break;}});}
else
{msgService.inform("Please make sure all fields are filled out.","warning");}};$scope.submitSignUpForm=function(isValid){var defaultForm={firstname:"",lastname:"",email:"",password:"",password2:""};if(isValid){if(typeof $scope.user.terms==='undefined'||$scope.user.terms===false){msgService.inform("To register at Remembr. you need to accept the terms and conditions and privacy and cookie policy.","warning");return;}
if($scope.user.pw1===$scope.user.pw2)
{msgService.inform("One moment please, we process your data...","info");var formdata={'firstname':typeof $scope.user.firstname!=="undefined"?$scope.user.firstname:'','lastname':typeof $scope.user.lastname!=="undefined"?$scope.user.lastname:'','email':$scope.user.email,'password':$scope.user.pw1,'password2':$scope.user.pw2,'terms':$scope.user.terms};$http({url:($stateParams.lang?'/'+$stateParams.lang:'')+'/account/signup',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'duplicate-unconfirmed':case'duplicate-confirmed':$('.pwmeter').hide();msgService.inform("This e-mail address is already in use"+
(result==="duplicate-unconfirmed"?", but it was not yet confirmed. Check your e-mail's inbox and spam or ":"."),"error",undefined,[(result==="duplicate-unconfirmed"?{lab:"click here to resend the confirmation e-mail.",handler:function($scope,email){return function(){$scope.resendConfirmationMail(true,email);};}($scope,$scope.user.email)}:{lab:"Forgot your password?",handler:function($scope,$email){return function(){$scope.submitResetForm(true,$email);};}($scope,$scope.user.email)})]);$scope.user=defaultForm;break;case'done':$('.slide').slideUp('fast');$('#signup-form').slideUp('fast');$('.register').hide();$.fancybox.close();msgService.inform("Please check your e-mail to confirm your registration.","info");$scope.user=defaultForm;break;case'not-valid':$('.pwmeter').hide();msgService.inform("These details are not correct.","warning");$scope.user=defaultForm;break;}}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("Passwords do not match.","warning");$scope.user.pw1='';$scope.user.pw2='';$('.pwmeter').hide();}}
else
{msgService.inform("Please make sure all required fields are filled out.","warning");}};$scope.submitLoginForm=function(isValid){if(isValid){var formdata={'email':$scope.user.email,'password':$scope.user.password,'rememberme':typeof $scope.user.rememberme!=="undefined"?$scope.user.rememberme:false};$http({url:"/account/login",method:"POST",data:formdata}).success(function(result,status,headers,config){switch(result){case'done':$scope.postLoginRedirect();break;case'not-verified':msgService.inform("Please confirm your registration by clicking the link in the e-mail.","error",undefined,[{lab:"Click here to resend the confirmation e-mail.",handler:function($scope,email){return function(){$scope.resendConfirmationMail(true,email);};}($scope,$scope.user.email)}]);break;default:msgService.inform("You have entered an incorrect e-mail address or password.","error");break;}}).error(function(data,status,headers,config){$scope.status=status;});}
else
{msgService.inform("Please make sure all fields are filled out.","warning");}};}]);app.controller('flashCtrl',['$scope','msgService','$rootScope',function($scope,msgService,$rootScope){$scope.search=function(){if($('#flasherror').html().length)
{var message=$('#flasherror').html();msgService.inform(message,'info');};};$scope.search();}]);app.controller('AnonymousEditCtrl',['$scope','User','$http','msgService','$rootScope','$compile','$state','dashboardVisibility','$stateParams','$location',function($scope,User,$http,msgService,$rootScope,$compile,$state,dashboardVisibility,$stateParams,$location){$scope.submit=function(){console.log('submitting');};}]);$('html').removeClass('no-js');
var app=angular.module('remembr');app.directive('slideshow',['$timeout','$parse',function($timeout,$parse){return{restrict:'C',replace:false,link:function(scope,element,attrs){element.addClass('bz-slider');scope.$slideIndex=0;scope.$slides=[];scope.$watch(attrs.bzSlider,function(value){var arr=[];angular.forEach(element.children(),function(item){if(angular.element(item).hasClass('bz-slide')){arr.push(item);}});scope.$slides=arr;});if(angular.isDefined(attrs.delay)){scope.$watch(attrs.delay,function(value){scope.$delay=value;});}
if(angular.isDefined(attrs.autoplay)){scope.$autoplay=$parse(attrs.autoplay)(scope);if(scope.$autoplay){scope.play();}}}};}]);app.directive('shorten',['$timeout',function($timeout){return{restrict:'A',replace:false,link:function($scope,element,attrs){onVisibilityOrExpressionChange=function(e){$timeout(function(){if(element.css('display')==='none'){element.next().hide();return;}
element.height('auto');var h=parseInt(element.css('line-height'))*attrs.shorten;if(element.height()>h||+element.height()===0)
{element.height(h).css({overflow:'hidden'});element.next().show();}
else
{element.next().hide();}});}.bind(element,attrs);$scope.$watch(function(){return element.is(':visible');},onVisibilityOrExpressionChange);$scope.$watch(attrs.ngBind,onVisibilityOrExpressionChange);}};}]);app.directive('collapse',['$compile','$timeout','$rootScope',function($compile,$timeout,$rootScope){return{restrict:'A',replace:false,link:function(scope,element,attrs){$rootScope.moreless=false;var collapsed=true;var h=parseInt(element.css('line-height'))*attrs.collapse;element.height(h).css({overflow:'hidden'});$timeout(function(){if(parseInt(element['context'].scrollHeight / parseInt(element.css('line-height')))>attrs.collapse){$rootScope.moreless=true;}
element.next().on('click',function(){if(collapsed){element.height(element[0].scrollHeight);collapsed=false;}
else
{element.height(h).css({overflow:'hidden'});collapsed=true;}});},5000);}};}]);app.directive('letters',['$compile','$timeout',function($compile,$timeout){return{restrict:'A',replace:true,template:'<span>{{text}}</span>',transclude:true,scope:{text:'='},link:function(scope,element,attrs){$timeout(function(){if(scope.text)
{var reg=new RegExp('.{0,'+attrs.letters+'}(\\b|$)');scope.text=scope.text.match(reg)[0];}});}};}]);app.directive('inverted',function(){return{require:'ngModel',link:function(scope,element,attrs,ngModel){ngModel.$parsers.push(function(val){return!val;});ngModel.$formatters.push(function(val){return!val;});}};});app.directive('initdata',function(){return{restrict:'A',link:function($scope,element,attrs){if(attrs.ngBind!==undefined)
{var propspath=attrs.ngBind.split('.');var curprop=propspath.shift();while(propspath.length)
{if($scope[curprop]===undefined){$scope[curprop]={};}
$scope=$scope[curprop];curprop=propspath.shift();}
if(!$scope[curprop])
{$scope[curprop]=attrs.initdata?attrs.initdata:$.trim(element.text());}}}};});app.directive('checkboxGroup',function(){return{restrict:'A',scope:true,link:function($scope,element,attrs){$scope.state='inactive';$scope.somechecked=false;$scope.allchecked=false;}};});app.directive('master',['$compile',function($compile){return{restrict:'A',replace:true,require:'?^form',link:function($scope,element,attrs,ctrl){var slavs=element.parents('[checkbox-group]').find('input[type=checkbox]:not([master])');var model=[];slavs.each(function()
{model.push($(this).attr('ng-model'));});var ormodel=model.join(' || ');var andmodel=model.join(' && ');var assignmodels=model.join(' = !allchecked;')+' = !allchecked';$scope.$watch(ormodel,function(newval){$scope.somechecked=newval;$scope.setstate();});$scope.$watch(andmodel,function(newval){$scope.allchecked=newval;$scope.setstate();});$scope.setstate=function(){$scope.state=$scope.somechecked!==$scope.allchecked?'indeterminate':($scope.somechecked?'active':'inactive');};$scope.toggle=function(){ctrl.$setDirty(true);$scope.$eval(assignmodels);};}};}]);app.directive("styled",function(){return{restrict:'CA',link:function(scope,elm,attrs){var t=attrs.inverted==undefined;if(attrs.ngModel||attrs.ngChecked)
{scope.$watch(attrs.ngModel||attrs.ngChecked,function(val){elm.parent().toggleClass('active',val===t);});}}};});app.directive('userMsg',['msgTabService','$state',function(msgTabService,$state){return{restrict:'C',replace:true,template:'<div ng-if="user.id!=$root.user.id" class="contact_icon">'+'<div>'+'<img class="user_photo" width="65" height="65" alt="" ng-src="/minify?files={[{user.photoid}]}&resize=w[65]h[65]f[true]">'+'<a ng-click="mailUser(user)">{[{user.firstname}]} {[{user.lastname}]}</a>'+'<button class="med_blue_but" ng-click="mailUser(user)">{{ text }}</button>'+'</div>'+'</div>',transclude:true,scope:{user:'=',text:'='},controller:function($scope,$element){$scope.mailUser=function(user){msgTabService.setNewto(user);msgTabService.openTab('new');$state.go('root.newmsg');};}};}]);app.directive('deleteContent',['$rootScope','$http','msgService',function($rootScope,$http,msgService){return{restrict:'C',replace:true,template:'<div>'+'<a ng-click="deletecnt(mem)"></a>'+'</div>',transclude:true,scope:{mem:'='},controller:function($scope,$element){$scope.deletecnt=function(mem){msgService.inform("Are you sure?","confirm",function(confirm){if(confirm)
{var formdata={'id':mem.id};$http({url:'/content/delete-memory',data:formdata,method:"POST"}).success(function(result,status,headers,config){switch(result){case'ok':var index=$rootScope.page.memories.indexOf(mem);$rootScope.page.memories.splice(index,1);msgService.inform("The message is deleted.","success");break;case'error':msgService.inform("Sorry, something went wrong.","warning");break;}}).error(function(data,status,headers,config){$scope.status=status;msgService.inform("Sorry, something went wrong.","warning");});}});};}};}]);app.directive('editContent',['$rootScope','$http','msgService',function($rootScope,$http,msgService){return{restrict:'C',replace:true,template:'<div><a ng-click="editcnt(mem)"></a></div>',transclude:true,scope:{mem:'='},controller:function($scope,$element){$scope.editcnt=function(mem){$element.next().addClass('editing').removeClass('not-editing');$element.next().find('.edit-content-text-field').focus();mem.editing=true;};}};}]).directive('saveEditContent',['$rootScope','$http','msgService',function($rootScope,$http,msgService){return{restrict:'C',controller:function($scope,$element){$scope.saveContent=function(context,mem){var formdata={id:mem.id,text:mem.text};$http({url:'/json/content/edit',data:formdata,method:"POST"}).success(function($element,result,status,headers,config){if(result['changed']){msgService.inform("The altered message is saved.","success");$element.parent().parent().parent().parent().removeClass('editing').addClass('not-editing');mem.editing=false;mem.text.$dirty=true;}else{msgService.inform("Sorry, something went wrong, "+result['errors'][0],"warning");}}.bind(undefined,$element)).error(function($element,data,status,headers,config){$scope.status=status;msgService.inform("Sorry, something went wrong.","warning");});}.bind(undefined,$element);}};}]);app.directive('space2semicolon',function(){return{restrict:'A',require:'ngModel',link:function(scope,element,attrs,ngModelCtrl){element.bind('change',function(){var newAddresses=scope.invite.recipients.trim().replace(/[,\s]+/g,';');scope.invite.recipients=newAddresses;});}};});app.directive('datepicker',function(){return{restrict:'A',require:'ngModel',link:function(scope,element,attrs,ngModelCtrl){var format=attrs.datepicker||$.datepicker.ISO_8601;var lock=false;attrs.$observe('datepicker',function(val){format=val||$.datepicker.ISO_8601;element.datepicker('option',{dateFormat:format});});element.datepicker({showOn:"both",buttonImage:"/images/cal_img.jpg",buttonImageOnly:true,dateFormat:format,changeYear:true,yearRange:"1900:+1",maxDate:new Date(),onSelect:function(date){scope.$apply(function(){ngModelCtrl.$setViewValue(date);});},onChangeMonthYear:function(year,month,dp){if(!lock)
{lock=true;var date=new Date(year,month-1,dp.selectedDay);$('#'+dp.id).datepicker('setDate',date);setTimeout(function(){lock=false;},50);}}});ngModelCtrl.$parsers.push(function(val)
{if(!val){return val;}
try
{var date=$.datepicker.parseDate(format,val);ngModelCtrl.$setValidity('date',true);return $.datepicker.formatDate($.datepicker.ISO_8601,date);}
catch(e)
{ngModelCtrl.$setValidity('date',false);return undefined;}});ngModelCtrl.$formatters.push(function(val)
{if(!val){return val;}
var date=$.datepicker.parseDate($.datepicker.ISO_8601,val);return $.datepicker.formatDate(format,date);});}};});app.directive('regFilter',['$parse',function($parse){return{require:'ngModel',link:function(scope,element,attrs,modelCtrl)
{var params=$parse(attrs.regFilter)();var reg=params&&params.reg?new RegExp(params.reg,'ig'):/\s+/ig;var rep=params&&params.rep?params.rep:'';modelCtrl.$parsers.push(function(inputValue)
{if(!inputValue){return inputValue;}
var transformedInput=inputValue.toLowerCase().replace(reg,rep);if(transformedInput!==inputValue)
{modelCtrl.$setViewValue(transformedInput);modelCtrl.$render();}
return transformedInput;});}};}]);app.directive('condolence',function(){return{restrict:'A',replace:true,scope:{condolence:'=',idx:'='},templateUrl:'/tpl/content/condolence-small'};});app.directive('memory',function(){return{restrict:'A',replace:true,scope:{memory:'=',idx:'='},templateUrl:'/tpl/content/memory-small'};});app.directive('photo',function(){return{restrict:'A',replace:true,scope:{photo:'=',idx:'='},templateUrl:'/tpl/content/photo-small'};});app.directive('video',function(){return{restrict:'A',replace:true,scope:{video:'=',idx:'='},templateUrl:'/tpl/content/video-small'};});app.directive('youtubevideo',['$sce',function($sce){return{restrict:'A',replace:true,scope:{video:'='},templateUrl:'/tpl/content/youtube-video',link:function(scope,elm,attrs){var videoid=attrs.youtubevideo;var videourl='https://www.youtube.com/embed/'+videoid+'?enablejsapi=1&amp;fs=1&amp;border=0&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;autohide=2'+'&amp;iv_load_policy=3&amp;autoplay=1&amp;wmode=transparent&amp;nologo=1"'+' frameborder="0" allowfullscreen="" wmode="Opaque"';scope.videourl=$sce.trustAsResourceUrl(videourl);}};}]);app.directive('simplepaging',['$timeout',function($timeout){return{restrict:'A',replace:true,templateUrl:'/tpl/content/simplepaging',link:function(scope,elm,attrs){scope.currentPage=scope.$eval(attrs.currentPage)||0;scope.pageSize=scope.$eval(attrs.pageSize)||8;scope.nrItems=+attrs.nritems;scope.numberOfPages=Math.ceil(scope.nrItems / scope.pageSize);attrs.$observe('nritems',function(value){scope.nrItems=+value;scope.numberOfPages=Math.ceil(value / scope.pageSize);if(scope.numberOfPages<=scope.currentPage){scope.currentPage=(scope.numberOfPages-1)>=0?scope.numberOfPages-1:0;}},true);}};}]);app.directive('scrollOnClick',function(){return{restrict:'A',link:function(scope,elm,attrs){var idToScroll=attrs.href;elm.on('click',function(){var $target;if(idToScroll){$target=$(idToScroll);}else{$target=$elm;}
$("body").animate({scrollTop:$target.offset().top},"slow");});}};});app.directive('infomessages',['msgService',function(msgService){return{restrict:'A',replace:true,scope:{infomessages:'='},templateUrl:'/tpl/content/infomessages',link:function(scope,elm,attrs){scope.allMessages=msgService.allInfos;scope.remove=msgService.remove;scope.confirm=msgService.confirm;}};}]);app.directive('msgPostRender',['$timeout','msgService',function($timeout,msgService){return{restrict:'A',link:function(scope,element,attrs){if(scope.alert.type!=='error'&&scope.alert.type!=='confirm'){$timeout(function(){msgService.remove(scope.alert);},5000);}}};}]);app.directive('slide',['$rootScope',function($rootScope){return{restrict:'C',link:function(scope,elem,attrs){if(!elem.hasClass('noclose')){elem.bind('click',function(){$rootScope.ui.active='';$rootScope.ui.readmore=false;});}}};}]);app.directive('accordion',['$timeout',function($timeout){return{restrict:'C',replace:true,template:'<div><i ng-class="{nonActiveIcon:!open, activeIcon:open}"></i><h4>{{title}}</h4>'+'<div class="accordion-content" ng-show="open" ng-transclude></div></div>',transclude:true,scope:{title:'='},link:function(scope,elm){scope.open=false;angular.element(elm.children()[1]).bind('click',function(){scope.$apply('open = !open');});}};}]);app.animation('.slide-animation',['$window',function($window){return{enter:function(element,done){var startPoint=$window.innerWidth*0.5,tl=new TimelineLite();tl.fromTo(element.find('.slide'),1,{alpha:0},{alpha:1});},leave:function(element,done){var tl=new TimelineLite();tl.to(element,1,{alpha:0,onComplete:done});}};}]);app.directive('uiTinymce',[function(){uiTinymceConfig={};var generatedIds=0;return{priority:10,require:'ngModel',link:function(scope,elm,attrs,ngModel){var expression,options,tinyInstance,updateView=function(){ngModel.$setViewValue(elm.val());if(!scope.$root.$$phase){scope.$apply();}};if(!attrs.id){attrs.$set('id','uiTinymce'+generatedIds++);}
if(attrs.uiTinymce){expression=scope.$eval(attrs.uiTinymce);}else{expression={};}
if(expression.setup){var configSetup=expression.setup;delete expression.setup;}
options={setup:function(ed){var args;ed.on('init',function(args){ngModel.$render();ngModel.$setPristine();});ed.on('ExecCommand',function(e){ed.save();updateView();});ed.on('KeyUp',function(e){ed.save();updateView();});ed.on('SetContent',function(e){if(!e.initial&&ngModel.$viewValue!==e.content){ed.save();updateView();}});ed.on('blur',function(e){elm.blur();});ed.on('ObjectResized',function(e){ed.save();updateView();});if(configSetup){configSetup(ed);}},mode:'exact',elements:attrs.id};angular.extend(options,uiTinymceConfig,expression);setTimeout(function(){tinymce.init(options);});ngModel.$render=function(){if(!tinyInstance){tinyInstance=tinymce.get(attrs.id);}
if(tinyInstance){tinyInstance.setContent(ngModel.$viewValue||'');}};scope.$on('$destroy',function(){if(!tinyInstance){tinyInstance=tinymce.get(attrs.id);}
if(tinyInstance){tinyInstance.remove();tinyInstance=null;}});}};}]);app.directive("uiSrefParams",['$state',function($state){return{link:function(scope,elm,attrs){var params;params=scope.$eval(attrs.uiSrefParams);return elm.bind("click",function(e){var button;if(!angular.equals($state.params,params)){button=e.which||e.button;if((button===0||button===1)&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){scope.$evalAsync(function(){return $state.go(".",params);});return e.preventDefault();}}});}};}]);function parseStateRef(ref){var parsed=ref.replace(/\n/g," ").match(/^([^(]+?)\s*(\((.*)\))?$/);if(!parsed||parsed.length!==4)
throw new Error("Invalid state ref '"+ref+"'");return{state:parsed[1],paramExpr:parsed[3]||null};}
app.directive("uiRelSref",['$state','$timeout',function($state,$timeout){return{restrict:'A',require:'?^uiSrefActive',link:function(scope,element,attrs,uiSrefActive){var ref=parseStateRef(attrs.uiRelSref);var params=null,url=null;var update=function(newVal){if(newVal){params=newVal;}
var newHref=$state.href(ref.state,params,{relative:$state.$current});if(uiSrefActive){uiSrefActive.$$setStateInfo(ref.state,params);}
if(!newHref){return false;}
element[0].href=newHref;};if(ref.paramExpr){scope.$watch(ref.paramExpr,function(newVal,oldVal){if(newVal!==params){update(newVal);}},true);params=scope.$eval(ref.paramExpr);}
scope.$root.$on('$stateChangeSuccess',function(){update();});update();element.bind("click",function(e){var button=e.which||e.button;if((button===0||button==1)&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&!element.attr('target')){$timeout(function(){$state.go(ref.state,params,{relative:$state.$current});});e.preventDefault();}});}};}]);app.directive('ngEnter',function(){return function(scope,element,attrs){element.bind("keydown keypress",function(event){if(event.which===13){scope.$apply(function(){scope.$eval(attrs.ngEnter);});event.preventDefault();}});};});app.directive('pwCheck',['$stateParams','$rootScope','$injector',function($stateParams,$rootScope,$injector){var alpha_lower='abcdefghijklmnopqrstuvwxyz';var alpha_upper='ABCDEFGHIJKLMNOPQRSTUVWXYZ';var digits='1234567890';var shift_digit='!@#$%^&*()';var punctuation='`~,<.>/?;:\'"[{]}-_=+\\|';var calculateEntropy=function()
{if($injector.has('translatorService'))
{var translatorService=$injector.get('translatorService');}
var elem=$(this);var value=elem.val();var pwmeter=elem.next('.pwmeter');pwmeter.toggle(!!value);var count_al=0;var count_au=0;var count_d=0;var count_sd=0;var count_p=0;var count_o=0;for(var i=0;i<value.length;i++)
{var c=value.charAt(i);if(alpha_lower.indexOf(c)>=0)
{count_al++;}
else if(alpha_upper.indexOf(c)>=0)
{count_au++;}
else if(digits.indexOf(c)>=0)
{count_d++;}
else if(shift_digit.indexOf(c)>=0)
{count_sd++;}
else if(punctuation.indexOf(c)>=0)
{count_p++;}
else
{count_o++;}}
var approx_entropy=0;for(i=0;i<Math.max(count_al,count_au,count_d,count_sd,count_p,count_o);i++)
{var range=0;c=0;if(i<count_al)
{c++;range+=26;}
if(i<count_au)
{c++;range+=26;}
if(i<count_d)
{c++;range+=10;}
if(i<count_sd)
{c++;range+=10;}
if(i<count_p)
{c++;range+=22;}
if(i<count_o)
{c++;range+=128;}
approx_entropy+=c*Math.log(range);}
approx_entropy /=Math.log(2);if(approx_entropy>120)
{pwmeter.find('.pwrating').html(translatorService?translatorService.translate('very strong'):'very strong');pwmeter.find('.pwgauge').css('background-color','green');}
else if(approx_entropy>60)
{pwmeter.find('.pwrating').html(translatorService?translatorService.translate('strong'):'strong');pwmeter.find('.pwgauge').css('background-color','#5a0');}
else if(approx_entropy>45)
{pwmeter.find('.pwrating').html(translatorService?translatorService.translate('good'):'good');pwmeter.find('.pwgauge').css('background-color','#8d0');}
else if(approx_entropy>20)
{pwmeter.find('.pwrating').html(translatorService?translatorService.translate('weak'):'weak');pwmeter.find('.pwgauge').css('background-color','orange');}
else
{pwmeter.find('.pwrating').html(translatorService?translatorService.translate('very weak'):'very weak');pwmeter.find('.pwgauge').css('background-color','red');}
pwmeter.find('.pwgauge').height(5).width(Math.max(10,Math.min(100,Math.round(approx_entropy / 1.2)))+'%');};return{require:'ngModel',link:function(scope,elem,attrs,ctrl){elem.after($('<div class="pwmeter"><span class="pwrating">weak</span><div class="pwgauge"></div></div>').width(elem.width()).hide());elem.on('keyup',calculateEntropy);}};}]);app.directive("placeholder",['$timeout',function($timeout){if(Modernizr.input.placeholder===true)
return{};return{restrict:"A",link:function(scope,elem,attrs){var txt=attrs.placeholder;elem.bind("focus",function(){if(elem.val()===txt){elem.val("");}
scope.$apply();});elem.bind("blur",function(){if(elem.val()===""){elem.val(txt);}
scope.$apply();});$timeout(function(){elem.val(txt);scope.$apply();});}};}]);app.directive('setDefault',['$parse',function($parse){return{restrict:'A',require:'ngModel',link:function(scope,element,attrs){if(attrs.ngModel)
{if(element.prop("tagName")==='INPUT')
{attrs.$observe('setDefault',function(val){$parse(attrs.ngModel).assign(scope,val);});}
else if(element.prop("tagName")==='TEXTAREA')
{attrs.$observe('placeholderedit',function(value){$parse(attrs.ngModel).assign(scope,value);});attrs.$observe('placeholder',function(value){return value;},function(){$parse(attrs.ngModel).assign(scope,value);});}}}};}]);app.directive('colorboxproviders',['$http','$compile','$rootScope','msgService',function($http,$compile,$rootScope,msgService){return{restrict:'AC',link:function(scope,element,attrs){element.on("click",function(e){e.preventDefault();$.colorbox({href:'/provider/add-provider',iframe:'true',innerWidth:'430',innerHeight:'222',onClosed:function(){msgService.inform("Please wait while site is updating.",'info');}});});}};}]);app.directive("passwordVerify",function(){return{require:"ngModel",scope:{passwordVerify:'='},link:function(scope,element,attrs,ctrl){scope.$watch(function(){var combined;if(scope.passwordVerify||ctrl.$viewValue){combined=scope.passwordVerify+'_'+ctrl.$viewValue;}
return combined;},function(value){if(value){ctrl.$parsers.unshift(function(viewValue){var origin=scope.passwordVerify;if(origin!==viewValue){ctrl.$setValidity("passwordVerify",false);return undefined;}else{ctrl.$setValidity("passwordVerify",true);return viewValue;}});}});}};});app.directive('totop',[function(){return{restrict:'A',replace:false,link:function(scope,element,attrs){element.bind('click',function(){scope.$on('$destroy',function(){window.scrollTo(0,0);});});}};}]);function timeoutUntil(pred,exec,time){if(pred())
exec();else
setTimeout((function(pred,exec,time){return function(){timeoutUntil(pred,exec,time);};})(pred,exec,time),time);};app.factory('$FB',['$window',function($window){return{init:function(fbId){if(fbId){this.fbId=fbId;$window.fbAsyncInit=function(){FB.init({appId:fbId,channelUrl:'app/channel.html',status:true,xfbml:true});};(function(d){var js,id='facebook-jssdk',ref=d.getElementsByTagName('script')[0];if(d.getElementById(id)){return;}
js=d.createElement('script');js.id=id;js.async=true;js.src="//connect.facebook.net/en_US/all.js";ref.parentNode.insertBefore(js,ref);}(document));}
else{throw("FB App Id Cannot be blank");}}};}]).directive('facebook',['$timeout','$http','translatorService',function($timeout,$http,$translatorService){return{scope:{shares:'='},transclude:true,link:function(scope,element,attr){var canonicalURLTester=function(scope){return function(){return scope.$root.page.canonicalUrl!==undefined;};};var facebookButtonCreator=function(scope,element){return function(){var url=scope.$root.page.canonicalBaseUrl+'/'+scope.$root.lang+'/'+scope.$root.page.url;var ifr=$('<iframe src="//www.facebook.com/plugins/share_button.php?href='+
encodeURIComponent(url)+'&amp;'+'layout=button" scrolling="no" frameborder="0" '+'style="border:none; overflow:hidden;" allowTransparency="true" height="20" width="57"></iframe>');$(element).append(ifr);};};timeoutUntil(canonicalURLTester(scope),facebookButtonCreator(scope,element),100);}};}]).directive('twitter',['$timeout','$window','translatorService',function($timeout,$window,$translatorService){return{link:function(scope,element,attr){var twitterButtonCreator=function(scope,element){return function(){var firstname=scope.$root.page.firstname;var lastname=scope.$root.page.lastname;var txt=sprintf($translatorService.translate('View the memorial page of %s %s and join us in sharing memories and condolences.'),firstname,lastname);var url=scope.$root.page.canonicalBaseUrl+scope.$root.lang+(scope.$root.lang!==''?'/':'')+scope.$root.page.url;twttr.widgets.createShareButton(url,element[0],{count:'none',text:txt});};};var canonicalURLAndTwitterTester=function(scope){return function(){return scope.$root.page.canonicalUrl!==undefined&&twttr.widgets!==undefined;};};timeoutUntil(canonicalURLAndTwitterTester(scope),twitterButtonCreator(scope,element),100);}};}]).directive('headerReadMore',['$rootScope',function($rootScope){return{link:function(scope,element,attrs){$rootScope.$on('$stateChangeSuccess',function(){$rootScope.ui.readmore=false;});$("div > ul > li, > ul > li",element).removeClass('selected');var on_child_menu=false;var on_menu=false;if(!('ontouchstart'in window)&&!(navigator.msMaxTouchPoints)){$("div > ul > li, > ul > li",element).bind('mouseenter',function(){on_menu=true;$("div > ul > li,  > ul > li",element).removeClass('selected');$(this).addClass('selected');});$("div > ul > li, > ul > li",element).bind('mouseleave',function(){on_menu=false;if(!on_child_menu)
$(this).removeClass('selected');});$("div > ul > li > ul, > ul > li > ul",element).bind('mouseleave',function(event){on_child_menu=false;if(!on_menu)
$($(this).parent()).removeClass('selected');});$("div > ul > li > ul, > ul > li > ul",element).bind('mouseenter',function(event){on_child_menu=true;});}
$("div > ul > li, > ul > li",element).bind('click',function(){var is_selected=$(this).hasClass('selected');$("div > ul > li,  > ul > li",element).removeClass('selected');if(is_selected)
$(this).removeClass('selected');else
$(this).addClass('selected');event.stopPropagation();});$("div > ul > li > ul, > ul > li > ul",element).bind('click',function(event){$($(this).parent()).removeClass('selected');$rootScope.ui.readmore=false;event.stopPropagation();});}};}]);
var app=angular.module('remembr');var countries=['Afghanistan','Albania','Algeria','American Samoa','Andorra','Angola','Anguilla','Antarctica','Antigua and Barbuda','Argentina','Armenia','Aruba','Australia','Austria','Azerbaijan','Bahamas','Bahrain','Bangladesh','Barbados','Belarus','Belgium','Belize','Benin','Bermuda','Bhutan','Bolivia','Bosnia and Herzegovina','Botswana','Bouvet Island','Brazil','British Indian Ocean Territory','Brunei Darussalam','Bulgaria','Burkina Faso','Burundi','Cambodia','Cameroon','Canada','Cape Verde','Cayman Islands','Central African Republic','Chad','Chile','China','Christmas Island','Cocos Islands','Colombia','Comoros','Congo','Congo,  Democratic Republic of the','Cook Islands','Costa Rica','Cote d\'Ivoire','Croatia','Cuba','Cyprus','Czech Republic','Denmark','Djibouti','Dominica','Dominican Republic','Ecuador','Egypt','El Salvador','Equatorial Guinea','Eritrea','Estonia','Ethiopia','Falkland Islands','Faroe Islands','Fiji','Finland','France','French Guiana','French Polynesia','Gabon','Gambia','Georgia','Germany','Ghana','Gibraltar','Greece','Greenland','Grenada','Guadeloupe','Guam','Guatemala','Guinea','Guinea-Bissau','Guyana','Haiti','Heard Island and McDonald Islands','Honduras','Hong Kong','Hungary','Iceland','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan','Kenya','Kiribati','Kuwait','Kyrgyzstan','Laos','Latvia','Lebanon','Lesotho','Liberia','Libya','Liechtenstein','Lithuania','Luxembourg','Macao','Macedonia','Madagascar','Malawi','Malaysia','Maldives','Mali','Malta','Marshall Islands','Martinique','Mauritania','Mauritius','Mayotte','Mexico','Micronesia','Moldova','Monaco','Mongolia','Montserrat','Morocco','Mozambique','Myanmar','Namibia','Nauru','Nepal','Netherlands','Netherlands Antilles','New Caledonia','New Zealand','Nicaragua','Niger','Nigeria','Norfolk Island','North Korea','Norway','Oman','Pakistan','Palau','Palestinian Territory','Panama','Papua New Guinea','Paraguay','Peru','Philippines','Pitcairn','Poland','Portugal','Puerto Rico','Qatar','Romania','Russian Federation','Rwanda','Saint Helena','Saint Kitts and Nevis','Saint Lucia','Saint Pierre and Miquelon','Saint Vincent and the Grenadines','Samoa','San Marino','Sao Tome and Principe','Saudi Arabia','Senegal','Serbia and Montenegro','Seychelles','Sierra Leone','Singapore','Slovakia','Slovenia','Solomon Islands','Somalia','South Africa','South Georgia','South Korea','Spain','Sri Lanka','Sudan','Suriname','Svalbard and Jan Mayen','Swaziland','Sweden','Switzerland','Syrian Arab Republic','Taiwan','Tajikistan','Tanzania','Thailand','Timor-Leste','Togo','Tokelau','Tonga','Trinidad and Tobago','Tunisia','Turkey','Turkmenistan','Tuvalu','Uganda','Ukraine','United Arab Emirates','United Kingdom','United States','United States Minor Outlying Islands','Uruguay','Uzbekistan','Vanuatu','Vatican City','Venezuela','Vietnam','Virgin Islands,  British','Virgin Islands,  U.S.','Wallis and Futuna','Western Sahara','Yemen','Zambia','Zimbabwe'];function templateUrlFunction(regurl,pars)
{return function($stateParams){var lang=$stateParams.lang?$stateParams.lang+'/':'';var url='/tpl/'+lang+regurl;if(pars)
{for(var i=0;i<pars.length;i++)
{var part=(pars[i][0]===':')?$stateParams[pars[i].substring(1)]:pars[i];url+='/'+part;}}
return url;};}
app.run(['$rootScope','DEBUG_STATES','$location',function($rootScope,DEBUG_STATES,$location){$rootScope.locationPath=$location.path();$rootScope.isTouchScreen=!(!('ontouchstart'in window)&&!(navigator.msMaxTouchPoints));console.log(['rrrr',$rootScope.isTouchScreen]);if(DEBUG_STATES){$rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState,fromParams){console.log('$stateChangeStart to '+toState.to+'- fired when the transition begins. toState,toParams : \n',toState,toParams);});$rootScope.$on('$stateChangeError',function(event,toState,toParams,fromState,fromParams){console.log('$stateChangeError - fired when an error occurs during transition.');console.log(arguments);});$rootScope.$on('$stateChangeSuccess',function(event,toState,toParams,fromState,fromParams){console.log('$stateChangeSuccess to '+toState.name+'- fired once the state transition is complete.');});$rootScope.$on('$viewContentLoaded',function(event){console.log('$viewContentLoaded - fired after dom rendered',event);});$rootScope.$on('$stateNotFound',function(event,unfoundState,fromState,fromParams){console.log('$stateNotFound '+unfoundState.to+'  - fired when a state cannot be found by its name.');console.log(unfoundState,fromState,fromParams);});}}]);app.config(['$stateProvider','$urlRouterProvider','$locationProvider','$httpProvider',function($stateProvider,$urlRouterProvider,$locationProvider,$httpProvider)
{$httpProvider.interceptors.push('httpRequestInterceptor');$locationProvider.html5Mode(true);$urlRouterProvider.otherwise("/");$urlRouterProvider.rule(function($injector,$location){var path=$location.path(),normalized=path.toLowerCase();var pos=normalized.indexOf('/?');if(normalized.length>1&&((normalized[normalized.length-1]==='/')||pos>0))
{normalized=pos>0?(normalized.substr(0,pos)+normalized.substr(pos+1)):normalized.substr(0,normalized.length-1);}
normalized=normalized.replace(/^\/en\/(?:herdenkingspaginas|search)\b/,'/en/memorialpages')
normalized=normalized.replace(/^\/nl\/(?:memorialpages|search)\b/,'/nl/herdenkingspaginas')
if(path!==normalized){return normalized;}});$stateProvider.state('root',{abstract:true,url:'/{lang:nl|en|nl\-be|}?',onEnter:['$stateParams','msgService','$rootScope','MessagesInbox','MessagesOutbox','pollingService','Notifications','User',function($stateParams,msgService,$rootScope,MessagesInbox,MessagesOutbox,pollingService,Notifications,User)
{msgService.setTranslation($stateParams.lang);$rootScope.delay=20000;if($rootScope.user.loggedin)
{$rootScope.inbox=MessagesInbox.get();$rootScope.outbox=MessagesOutbox.get();$rootScope.notifications=Notifications.get();pollingService.start();}
else
{pollingService.stop();}}],resolve:{userpromise:['$rootScope','User',function($rootScope,User){if(!($rootScope.user instanceof User))
{$rootScope.user=User.get();return $rootScope.user.$promise;}
return $rootScope.user.$get().$promise;}]},views:{'header@':{templateUrl:templateUrlFunction('content/header')},'subheader@':{templateUrl:templateUrlFunction('content/subheader')},'footer@':{templateUrl:templateUrlFunction('content/footer')}}}).state('root.home',{url:'',title:['translatorService',function(translatorService){return translatorService.translate('Memorial website and online condolences | Remembr.');}],onEnter:['$rootScope','SearchPages','$state',function($rootScope,SearchPages,$state){$rootScope.bodyclass='full-width anonymous-landing-page';$rootScope.landingSearchResults=SearchPages.getRecent();}],views:{'@':{templateUrl:templateUrlFunction('cmscontent/home')}}}).state('root.landingpage',{url:'',title:['translatorService',function(translatorService){return translatorService.translate('Memorial website and online condolences | Remembr.');}],onEnter:['$rootScope','SearchPages','$state',function($rootScope,SearchPages,$state){$state.go('root.home',$state);}],views:{'@':{templateUrl:templateUrlFunction('cmscontent/home')}}}).state('root.welcome',{url:'/home/welcome',onEnter:['$rootScope','$timeout',function($rootScope,$timeout){localStorage.welcomed=true;if(!$rootScope.user.loggedin)
{$timeout(function(){$.fancybox.close();});}}],views:{'fancybox@':{templateUrl:templateUrlFunction('dashboard/landing-popup'),controller:['$scope',function($scope){$scope.close=function(){$.fancybox.close();};localStorage.welcomed=true;}]}}}).state('root.home.fancybox.showvideo',{url:'/home/video',title:['translatorService',function(translatorService){return translatorService.translate('Login | Remembr.');}],views:{'fancybox@':{templateUrl:templateUrlFunction('landing/video'),controller:['msgService','$scope','$stateParams',function(msgService,$scope,$stateParams){$(window).resize();$scope.infoMsgs=angular.copy(msgService.allInfos());}]}}}).state('root.basic',{url:'/{slug:about|faq}',onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='cms-page';}],views:{'@':{templateUrl:templateUrlFunction('cmscontent',[':slug'])}}}).state('root.cms',{url:'/cmscontent/:slug',title:['translatorService','$stateParams',function(translatorService,$stateParams){var msgs={'conditions':translatorService.translate('Terms and conditions | Remembr.'),'privacy':translatorService.translate('Privacy and cookie policy | Remembr.'),'disclaimer':translatorService.translate('Disclaimer | Remembr.'),'contact':translatorService.translate('Contact | Remembr.'),'contact_ok':translatorService.translate('Thank you for your message | Remembr.'),'report':translatorService.translate('Report a problem | Remembr.'),'faq':translatorService.translate('Frequently asked questions | Remembr.'),'not-implemented':translatorService.translate('This feature is not yet available | Remembr.')}
if(msgs[$stateParams.slug])
return msgs[$stateParams.slug];else
return'Remembr.';}],onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='cms-page';}],views:{'@':{templateUrl:templateUrlFunction('cmscontent',[':slug'])}}}).state('root.forgotpassword2',{url:'/account/forgotpassword2/:key',onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='forgotpassword2';}],views:{'@':{templateUrl:templateUrlFunction('account/forgotpassword2',[':key'])}}}).state('root.search',{url:'/{search:search|herdenkingspaginas|memorialpages|huisdieren|pets|vips}/:searchterm?',title:['translatorService',function(translatorService){return translatorService.translate('Find a memorial page | Remembr.');}],onEnter:['$rootScope','SearchPages',function($rootScope,SearchPages){$rootScope.bodyclass='search';$rootScope.user.$get();var range=[];var d=new Date();var n=d.getFullYear();for(var i=n;i>1900;i--){range.push(i);}
$rootScope.range=range;$rootScope.recent=SearchPages.getRecent();$rootScope.slides=SearchPages.getRotators();$rootScope.countries=countries;}],views:{'@':{templateUrl:templateUrlFunction('search'),controller:['$scope','SearchPages','$stateParams','translatorService',function($scope,SearchPages,$stateParams,translatorService){$scope.predicate='-dateofdeath';$scope.term=$stateParams.searchterm;if($.inArray($stateParams.search,['huisdieren','pets'])>=0){$scope.$root.searchpages=SearchPages.getType({'searchterm':$stateParams.searchterm,'searchtype':'animal'});$("input[value=animal][name=type]").prop('checked',true)}else if($.inArray($stateParams.search,['vips'])>=0){$scope.$root.searchpages=SearchPages.getType({'searchterm':$stateParams.searchterm,'searchtype':'vip'});$("input[value=vip][name=type]").prop('checked',true)}else{$scope.$root.searchpages=SearchPages.get({'searchterm':$stateParams.searchterm});}
document.title=translatorService.translate('Find a memorial page | Remembr.');}]}}}).state('root.notifications',{url:'/notifications',title:['translatorService',function(translatorService){return translatorService.translate('Notifications | Remembr.');}],onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='notifications';}],resolve:['$rootScope','Notifications',function($rootScope,Notifications){$rootScope.notificationsHistory=Notifications.getNotificationsHistory();}],views:{'@':{templateUrl:templateUrlFunction('notifications')}}}).state('root.contact_ok',{url:'/cmscontent/contact_ok',title:['translatorService',function(translatorService){return translatorService.translate('Thank you for your message | Remembr.');}],}).state('root.dashboard',{url:'/dashboard',title:['translatorService',function(translatorService){return translatorService.translate('Dashboard | Remembr.');}],onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='dashboard';$rootScope.user.$get();}],resolve:['$rootScope','dashboardVisibility','SharedMemories','pollingService',function($rootScope,dashboardVisibility,SharedMemories,pollingService){if(typeof $rootScope.editdashboard==='undefined'){dashboardVisibility.set(false);}
if(!$rootScope.sharedmemories){$rootScope.sharedmemories=SharedMemories.get();}
pollingService.start();}],views:{'@':{templateUrl:templateUrlFunction('dashboard')}}}).state('root.usersettings',{url:'/settings',title:['translatorService',function(translatorService){return translatorService.translate('Account settings | Remembr.');}],onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='usersettings';}],resolve:['$rootScope','$http','UserSettings','SocialMedia',function($rootScope,$http,UserSettings,SocialMedia){UserSettings.then(function(data){$rootScope.usersettings=data;});if(!$rootScope.socialmedia){$rootScope.socialmedia=SocialMedia.get();}}],views:{'@':{templateUrl:templateUrlFunction('dashboard/settings')}}}).state('root.usersettings.password',{url:'/password',onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='password';}],views:{'@':{templateUrl:templateUrlFunction('dashboard/password')}}}).state('root.usersettings.email',{url:'/email',onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='email';}],views:{'@':{templateUrl:templateUrlFunction('dashboard/email')}}}).state('root.messages',{url:'/messages/:msgid?',title:['translatorService',function(translatorService){return translatorService.translate('Messages | Remembr.');}],onEnter:['$rootScope','MessagesOutbox','$stateParams','$state',function($rootScope,MessagesOutbox,$stateParams,$state){$rootScope.bodyclass='messages';if($stateParams.msgid){$rootScope.selected=$stateParams.msgid;MessagesOutbox.setReadDate({'id':$stateParams.msgid});}}],views:{'@':{templateUrl:templateUrlFunction('messages')}}}).state('root.newmsg',{url:'/newmsg',title:['translatorService',function(translatorService){return translatorService.translate('Send a new message | Remembr.');}],onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='messages';}],views:{'@':{templateUrl:templateUrlFunction('messages')}}}).state('root.page',{title:['$rootScope','translatorService',function($rootScope,translatorService){if(!$rootScope.page)return'';pagename=$rootScope.page.firstname+' '+$rootScope.page.lastname
return translatorService.translate('%s %s remembrance page and online condolences').replace('%s %s',pagename);}],url:"/{page:(?!home|create-page|dashboard|messages|newmsg|notifications|email|settings|password|search)[^/]+}",onEnter:['$rootScope',function($rootScope){$rootScope.bodyclass='remembr-page';}],onExit:['$rootScope',function($rootScope){$rootScope.page={};}],views:{'@':{templateUrl:templateUrlFunction('page'),controller:['$scope','$state','$stateParams','Page','Content','msgService','translatorService',function($scope,$state,$stateParams,Page,Content,msgService,translatorService){$scope.$root.filter={types:{'memory':true,'photo':true,'video':true,'condolence':false},labels:{}};$scope.$root.page=Page.get({url:$stateParams.page},function(page){if($scope.$root.page.memories===undefined)
{$scope.$root.page.memories=Content.list({url:page.url});}
if(page.labels)
{for(var i=0;i<page.labels.length;i++)
{$scope.$root.filter.labels[page.labels[i].id]=false;}}
pagename=page.firstname+' '+page.lastname
document.title=translatorService.translate('%s %s remembrance page and online condolences').replace('%s %s',pagename);},function(result){if(result.data&&result.data.error)
{$scope.$root.page=result.data;console.log(['result',result]);if(result.status==401)
{if($scope.user.loggedin)
{$state.go('root.page.fancybox.private');}
else
{msgService.inform('Please log in to view the page. New to Remembr? Please sign up first.','login');$state.go('root.page.fancybox.login',{},{location:false});}}
else
{}
return;}});$scope.toggle=function(type,id){$scope.$root.filter[type][id]=!$scope.$root.filter[type][id];if(id==='condolence')
{$scope.clearLabels();}
else if(type==='labels')
{$scope.$root.filter.types.condolence=false;}};$scope.showAll=function(type){$scope.$root.filter.types['memory']=!type||type==='memory';$scope.$root.filter.types['photo']=!type||type==='memory';$scope.$root.filter.types['video']=!type||type==='memory';$scope.$root.filter.types['condolence']=!type||type==='condolence';$scope.clearLabels();};$scope.allTypesSelected=function()
{var anytype=true;angular.forEach($scope.$root.filter.types,function(value){anytype&=value;});return anylabel&&anytype;};$scope.allLabelsSelected=function()
{var anylabel=true;angular.forEach($scope.$root.filter.labels,function(value){anylabel&=!value;});return anylabel;};$scope.allSelected=function()
{return $scope.allTypesSelected()&&$scope.allLabelsSelected();};$scope.clearLabels=function()
{angular.forEach($scope.$root.filter.labels,function(value,key){$scope.$root.filter.labels[key]=false;});};$scope.countLabels=function(label)
{var cnt=0;angular.forEach($scope.$root.page.memories,function(m){angular.forEach(m.labels,function(l){if(l.id==label.id)
{cnt++;}});});return cnt;};}]}}}).state('root.page.memoryredirect',{url:"/{msgid:\\d+}",onEnter:['$rootScope','$stateParams','$state','$timeout',function($rootScope,$stateParams,$state,$timeout)
{if($stateParams.msgid&&$rootScope.user.loggedin)
{$timeout(function(){$state.go('root.page.fancybox.memory',{'id':$stateParams.msgid});},2000);}}]}).state('root.page.error',{url:"/error",views:{'@':{templateUrl:templateUrlFunction('page/error')}}});function multiStateProvider(sp,prefixes)
{this.sp=sp;this.prefixes=prefixes;this.state=function(statename,stateconfig)
{for(var i=0;i<prefixes.length;i++)
{sp.state(prefixes[i]+statename,angular.copy(stateconfig));}
return this;};}
var ms=new multiStateProvider($stateProvider,['root.home','root.basic','root.cms','root.password','root.email','root.usersettings','root.newmsg','root.search','root.landingpage','root.dashboard','root.page','root.messages','root.notifications']);ms.state('.fancybox',{url:'',abstract:true,onExit:function()
{$.fancybox.close();},onEnter:['$compile','$rootScope','$timeout','$state',function($compile,$rootScope,$timeout,$state)
{$timeout(function(){var scope=$rootScope.$new();$.fancybox.open('<div id="fancyboxview" ui-view="fancybox"></div>');console.log($compile(angular.element('#fancyboxview')));$compile(angular.element('#fancyboxview'))(scope);angular.element('#fancyboxview').parent().one('$destroy.fancybox',function(evt)
{scope.$destroy();if($state.current.name.match(/\.fancybox(\.|$)/))
{$state.go($state.current.name.replace(/\.fancybox.*$/,''));}});});}]}).state('.fancybox.createpage',{url:'/create-page',abstract:true,views:{'fancybox@':{templateUrl:templateUrlFunction('create-page'),controller:['$scope','$state','$stateParams','Page','$upload','imagePreview','uploadService','localStorageService',function($scope,$state,$stateParams,Page,$upload,imagePreview,uploadService,localStorageService)
{$scope.reset=function()
{$scope.newpage=new Page({currentstep:1,maxstep:0,firstname:'',lastname:'',dateofbirth:'',roi:null,dateofdeath:'',introtext:'',photo:'',url:'',gender:'',residence:'',country:'',publishnow:true,invites:{facebook:{},remembr:{},email:{}}});$scope.newpage.currentstep=1;$scope.newpage.maxstep=0;};$scope.setdraft=function(){Page.getDraft(function(ret){if(ret['draft']!=null)
for(var key in ret['draft'])
$scope.newpage[key]=ret['draft'][key];$scope.$watch("newpage",function(value){$scope.scheduleUpdateDraft();},true);});};$scope.last_draft_update=0;$state.disregard_all_updates=false;$scope.update_pending=false;$scope.reset();$scope.setdraft();$scope.isEmpty=function(){return($scope.newpage.firstname.length+
$scope.newpage.lastname.length+
$scope.newpage.dateofbirth.length+
$scope.newpage.dateofdeath.length+
$scope.newpage.introtext.length+
$scope.newpage.photo.length+
$scope.newpage.url.length+
$scope.newpage.gender.length+
$scope.newpage.residence.length+
$scope.newpage.country.length)==0;};$scope.__updateDraft=function(){if($state.disregard_all_updates)
return;Page.updateDraft($scope.newpage);$scope.last_draft_update=(new Date()).getTime();$scope.update_pending=false;};$scope.scheduleUpdateDraft=function(){if($state.disregard_all_updates)
return;if($scope.update_pending)
return;time_elapsed=(new Date()).getTime()-$scope.last_draft_update;soonest_possible=5000-time_elapsed;if(soonest_possible<=0){$scope.__updateDraft();}else{$scope.update_pending=true;setTimeout($scope.__updateDraft,soonest_possible);}};$scope.setstep=function(num)
{if(!$scope.$root.user.loggedin)
{$state.go('^.^.login',$stateParams);return false;}
if($scope.newpage.maxstep===6)
{$scope.reset();$state.go('.info');return false;}
if($scope.newpage.maxstep<num-1)
{switch($scope.newpage.maxstep)
{case 4:$state.go('^.publish');break;case 3:$state.go('^.url');break;case 2:$state.go('^.photo');break;case 1:$state.go('^.info');break;default:$state.go('^.info');break;}
return false;}
$scope.newpage.currentstep=num;$scope.newpage.maxstep=Math.max($scope.newpage.maxstep,num);return true;};$scope.disableCropper=function(){$('img.actual-image').cropper('destroy');};$scope.ignoreFirstLoad=true;$scope.lastCropperUrl=null;$scope.enableCropper=function(){currentUrl=$("img.actual-image").attr("src");if(!$scope.ignoreFirstLoad&&$scope.lastCropperUrl!=currentUrl)
{$('img.actual-image').cropper({aspectRatio:1.0,viewMode:1,guides:false,rotatable:false,zoomable:false,crop:function($scope,e){$scope.newpage.roi={x:e.x,y:e.y,width:e.width,height:e.height};$scope.newpage.roi={x:e.x,y:e.y,width:e.width,height:e.height};}.bind(undefined,$scope)});$("img.actual-image").cropper('replace',currentUrl);$scope.lastCropperUrl=currentUrl;}
$scope.ignoreFirstLoad=false;};$scope.onFileSelect=function($files){uploadService.process($files,$scope,false);};$scope.onFileSelect=function($files){uploadService.process($files,$scope,false);};$scope.scaleROI=function(roi,factor){roi.x=roi.x*factor;roi.y=roi.y*factor;roi.width=roi.width*factor;roi.height=roi.height*factor;return roi;};$scope.startupload=function(callback){if(!$scope.selectedFile)
{callback();return;}
$scope.progress=0;$scope.upload=$upload.upload({url:'/json/page/file-upload',method:'POST',file:$scope.selectedFile,fileFormDataName:'file'}).success(function(response){$scope.newpage.photo=response.photo;$scope.newpage.roi=$scope.scaleROI($scope.newpage.roi,response.scale_factor);if(angular.isFunction(callback))callback();}).error(function(response){if(angular.isFunction(callback))callback();}).progress(function(evt){$scope.progress=parseInt(Math.min(100.0,100.0*evt.loaded / evt.total));});};}]}}}).state('.fancybox.createpage.info',{url:'/step1-info',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 1 | Remembr.');}],views:{createstep:{templateUrl:templateUrlFunction('create-page/step1-info'),controller:['$scope','$state','$stateParams',function($scope,$state,$stateParams)
{if(!$scope.setstep(1)){return;}
$scope.nextStep=function()
{if($scope.info.$valid)
{$state.go('^.photo');}
else
{$scope.info.gender.$dirty=true;$scope.info.firstname.$dirty=true;$scope.info.lastname.$dirty=true;$scope.info.dateofbirth.$dirty=true;$scope.info.dateofdeath.$dirty=true;$scope.info.introtext.$dirty=true;$scope.info.country.$dirty=true;$scope.info.residence.$dirty=true;}};$scope.countries=countries;}]}}}).state('.fancybox.createpage.photo',{url:'/step2-photo',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 2 | Remembr.');}],views:{createstep:{templateUrl:templateUrlFunction('create-page/step2-photo'),controller:['$scope','$rootScope',function($scope,$rootScope)
{$scope.$parent.lastCropperUrl=null;if(!$scope.setstep(2)){return;}}]}}}).state('.fancybox.createpage.url',{url:'/step3-url',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 3 | Remembr.');}],views:{createstep:{templateUrl:templateUrlFunction('create-page/step3-url'),controller:['$scope','$state','Page',function($scope,$state,Page)
{if(!$scope.setstep(3)){return;}
$scope.suggestions=Page.urlSuggestions({firstname:$scope.newpage.firstname,lastname:$scope.newpage.lastname,dateofbirth:$scope.newpage.dateofbirth,dateofdeath:$scope.newpage.dateofdeath});$scope.checkAvailable=function(callback)
{Page.checkAvailable({url:$scope.newpage.url},function(result)
{$scope.url.url.$setValidity('connect',true);$scope.url.url.$setValidity('available',result.available);$scope.url.url.$dirty=true;if(callback)
{callback();}},function()
{$scope.url.url.$setValidity('connect',false);$scope.url.url.$dirty=true;},callback);};$scope.select=function(suggestion)
{console.log(['select',$scope]);$scope.newpage.url=suggestion.url;};$scope.nextStep=function(){$scope.checkAvailable(function()
{if($scope.url.$valid)
{$state.go('^.publish');}});};}]}}}).state('.fancybox.createpage.publish',{url:'/step4-publish',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 4 | Remembr.');}],views:{createstep:{templateUrl:templateUrlFunction('create-page/step4-publish'),controller:['$scope','$state','Page','localStorageService',function($scope,$state,Page,localStorageService)
{if(!$scope.setstep(4)){return;}
$scope.allowpublish=$scope.$parent.newpage.dateofdeath===''?false:true;$scope.newpage.publishnow=$scope.allowpublish;$scope.nextStep=function(){if($scope.newpage.publishnow)
{$state.go('^.invite');}
else
{$scope.setstep(5);if(this.lock)return
this.lock=true;var callback=function(){Page.create($scope.newpage,function(ret)
{$scope.newpage=ret;$state.disregard_all_updates=true;Page.deleteDraft();$scope.user.$get();$state.go('^.done');},function(){console.log('oh no, some error has occurred');});};$scope.startupload(callback);}};}]}}}).state('.fancybox.createpage.invite',{url:'/step5-invite',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 5 | Remembr.');}],views:{createstep:{templateUrl:templateUrlFunction('create-page/step5-invite'),controller:['$scope','$state','Page','localStorageService',function($scope,$state,Page,localStorageService)
{if(!$scope.setstep(5)){return;}
$scope.nextStep=function()
{if(this.lock)return
this.lock=true;var callback=function(){Page.create($scope.newpage,function(ret)
{$scope.newpage=ret;$state.disregard_all_updates=true;Page.deleteDraft();$scope.user.$get();$state.go('^.done');},function(){console.log('oh no, some error has occurred');});};$scope.startupload(callback);};}]}}}).state('.fancybox.createpage.invite-email',{url:'/step5c-invite-email',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 5 e-mail | Remembr.');}],views:{'createstep':{templateUrl:templateUrlFunction('create-page/step5c-invite-email'),controller:['$scope','$state','msgService','translatorService',function($scope,$state,msgService,translatorService){if(!$scope.setstep(5)){return;}
$scope.invite=$scope.newpage.invites.email;$scope.save=function(){msgService.inform('Your email invitation will be sent in the final step.','info');$scope.newpage.invites.email=$scope.invite;$state.go('^.invite');};}]}}}).state('.fancybox.createpage.done',{url:'/step6-done',title:['translatorService',function(translatorService){return translatorService.translate('Create a memorial page step 6 | Remembr.');}],views:{createstep:{templateUrl:templateUrlFunction('create-page/step6-done'),controller:['$scope','$state','translatorService',function($scope,$state,translatorService)
{if(!$scope.setstep(6)){return;}
$scope.viewPage=function(){$state.go('root.page',{page:$scope.newpage.url,reload:true});};}]}}}).state('.fancybox.login',{url:'/user/login/:redirect?',title:['translatorService',function(translatorService){return translatorService.translate('Login | Remembr.');}],views:{'fancybox@':{templateUrl:templateUrlFunction('user/login'),controller:['msgService','$scope','$stateParams',function(msgService,$scope,$stateParams){$(window).resize();$scope.infoMsgs=angular.copy(msgService.allInfos());}]}}});$stateProvider.state('root.page.fancybox.editanonymous',{url:'/edit-anonymous/{editkey:[0-9a-zA-Z]{40,40}}',views:{'fancybox@':{templateUrl:templateUrlFunction('page/edit-anonymous'),controller:['$rootScope','$scope','$state','$stateParams','Content','msgService','msgTabService',function($rootScope,$scope,$state,$stateParams,Content,msgService,msgTabService){$scope.loading=true;Content.getAnonymous({url:$stateParams.page,editkey:$stateParams.editkey}).$promise.then(function(memory){$scope.found=true;$scope.anonymousEdit=new Content(memory);$scope.loading=false;}).catch(function(){$scope.found=false;$scope.loading=false;});$scope.$root.openTab('condolence');$scope.save=function(){Content.saveAnonymous({url:$stateParams.page,editkey:$stateParams.editkey},$scope.anonymousEdit,function(status){if(status.status=="ok"){$.fancybox.close();msgService.inform("Your condolence message has been updated","info");$scope.$root.page.memories=Content.list({url:$scope.$root.page.url});msgTabService.openTab('condolence');}else if(status.status=="no-text")
msgService.inform("Your condolence message may not be empty.","error");else
msgService.inform("Your condolence message was not found.","error");});}
$scope.delete=function(){Content.deleteAnonymous({url:$stateParams.page,editkey:$stateParams.editkey},function(status){if(status.status=="ok"){$.fancybox.close();msgService.inform("Your condolence message has been removed","info");$scope.$root.page.memories=Content.list({url:$scope.$root.page.url});msgTabService.openTab('condolence');}else
msgService.inform("Your condolence message was not found.","error");});}
$scope.close=$.fancybox.close;}]}}});$stateProvider.state('root.page.fancybox.setting',{url:'/settings',abstract:true,resolve:{isadmin:['$http','$q','$stateParams',function($http,$q,$stateParams){var deferred=$q.defer();$http.get('/json/'+$stateParams.page+'/settings').success(function(data){deferred.resolve(true);}).error(function(data){deferred.resolve(false);});return deferred.promise;}]},views:{'fancybox@':{templateUrl:templateUrlFunction('settings'),controller:['$state','isadmin',function($state,isadmin){if(!isadmin&&!$state.name=='root.page.fancybox.setting.qrcode')
{$state.go('root.page.fancybox.setting.error');}}]}}}).state('root.page.fancybox.setting.error',{url:'/error',views:{'settings':{templateUrl:templateUrlFunction('settings/error'),controller:[function(){}]}}}).state('root.page.fancybox.setting.info',{title:['translatorService',function(translatorService){return translatorService.translate('Change page details | Remembr.');}],url:'/info',views:{'settings':{templateUrl:templateUrlFunction('settings/info'),controller:['$scope','$state','$stateParams','Page','$upload','imagePreview','isadmin','uploadService','translatorService',function($scope,$state,$stateParams,Page,$upload,imagePreview,isadmin,uploadService,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}
$scope.countries=countries;$scope.editpage=Page.get({url:$stateParams.page});$scope.close=function(){$.fancybox.close();};$scope.save=function(){if($scope.info.$invalid)
{$scope.info.gender.$dirty=true;$scope.info.firstname.$dirty=true;$scope.info.lastname.$dirty=true;$scope.info.dateofbirth.$dirty=true;$scope.info.dateofdeath.$dirty=true;$scope.info.introtext.$dirty=true;$scope.info.country.$dirty=true;$scope.info.residence.$dirty=true;return;}
if(!$scope.info.$dirty)
{return;}
var callback=function(){$scope.editpage.$update({part:'info'},function success(data){angular.forEach(['firstname','lastname','dateofbirth','dateofdeath','introtext','photo','gender','residence','country'],function(val){$scope.page[val]=data[val];});$scope.page['roi']={x:Math.round(data['roi']['x']),y:Math.round(data['roi']['y']),width:Math.round(data['roi']['width']),height:Math.round(data['roi']['height'])};$scope.info.$setPristine();},function fail(data){console.log(data.data.error);});};$scope.startupload(callback);};$scope.disableCropper=function(){$('img.actual-image').cropper('destroy');};$scope.lastCropperUrl=null;$scope.roiOnceSet=false;$scope.enableCropper=function(){currentUrl=$("img.actual-image").attr("src");if($scope.lastCropperUrl!=currentUrl)
{if(!$scope.roiOnceSet)
$scope.storedROI=$scope.editpage.roi;console.log('starting cropper');$('img.actual-image').cropper({aspectRatio:1.0,viewMode:1,guides:false,rotatable:false,zoomable:false,crop:function($scope,e){$scope.editpage.roi={x:e.x,y:e.y,width:e.width,height:e.height};$scope.info.roi={x:e.x,y:e.y,width:e.width,height:e.height};$scope.info.$setDirty();}.bind(undefined,$scope),built:function($scope,currentUrl,e){if(!$scope.roiOnceSet)
$("img.actual-image").cropper('setData',$scope.storedROI);$scope.roiOnceSet=true;}.bind(undefined,$scope,currentUrl)});$scope.lastCropperUrl=currentUrl;$("img.actual-image").cropper('replace',currentUrl);}};$scope.onFileSelect=function($files){$scope.info.$setDirty();uploadService.process($files,$scope,false);};$scope.scaleROI=function(roi,factor){roi.x=roi.x*factor;roi.y=roi.y*factor;roi.width=roi.width*factor;roi.height=roi.height*factor;return roi;};$scope.startupload=function(callback){if(!$scope.selectedFile)
{callback();return;}
$scope.progress=0;$scope.uploading=true;$scope.upload=$upload.upload({url:'/json/'+$scope.page.url+'/file-upload',method:'POST',file:$scope.selectedFile,fileFormDataName:'file'}).success(function(response){$scope.uploading=false;$scope.editpage.photo=response.photo;$scope.editpage.roi=$scope.scaleROI($scope.editpage.roi,response.scale_factor);$scope.info.$setDirty();if(angular.isFunction(callback))callback();}).error(function(response){$scope.uploading=false;if(angular.isFunction(callback))callback();}).progress(function(evt){$scope.progress=parseInt(Math.min(100.0,100.0*evt.loaded / evt.total));console.log($scope.progress);});};}]}}}).state('root.page.fancybox.setting.admins',{url:'/admins',views:{'settings':{templateUrl:templateUrlFunction('settings/admins'),controller:['$scope','$state','$stateParams',function($scope,$state,$stateParams){}]}}}).state('root.page.fancybox.setting.privacy',{title:['translatorService',function(translatorService){return translatorService.translate('Change privacy | Remembr.');}],url:'/privacy',views:{'settings':{templateUrl:templateUrlFunction('settings/privacy'),controller:['$scope','$state','$stateParams','Page','isadmin','translatorService',function($scope,$state,$stateParams,Page,isadmin,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}
$scope.editpage=Page.get({url:$stateParams.page});$scope.close=function(){$.fancybox.close();};$scope.save=function(){if(!$scope.privacy.$dirty)
{return;}
$scope.editpage.$update({part:'privacy'},function success(data){$scope.user.$get();$scope.privacy.$setPristine();},function fail(data){console.log(data.data.error);});};}]}}}).state('root.page.fancybox.setting.block',{url:'/block',views:{'settings':{templateUrl:templateUrlFunction('settings/block'),controller:['$scope','$state','$stateParams',function($scope,$state,$stateParams){}]}}}).state('root.page.fancybox.setting.publish',{url:'/publish',title:['translatorService',function(translatorService){return translatorService.translate('Publish memorial page | Remembr.');}],views:{'settings':{templateUrl:templateUrlFunction('settings/publish'),controller:['$scope','$state','$stateParams','$filter','Page','msgService','isadmin','translatorService',function($scope,$state,$stateParams,$filter,Page,msgService,isadmin,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}
$scope.editpage=Page.get({url:$stateParams.page});$scope.close=function(){$.fancybox.close();};$scope.remove=function(){$scope.editpage.status=undefined;Page.update({part:'publish'},{url:$stateParams.page,status:'tobedeleted'},function(data){msgService.inform("An email has been sent to your email address to confirm permanent removal of this page","info");$scope.editpage.status='tobedeleted';$scope.$root.page.status='tobedeleted';},function fail(data){console.log(data.data.error);});};$scope.deactivate=function(){$scope.editpage.status=undefined;Page.update({part:'publish'},{url:$stateParams.page,status:'deactivated'},function(data){$scope.editpage.status='deactivated';$scope.$root.page.status='deactivated';},function fail(data){console.log(data.data.error);});};$scope.publishnow=function(){$scope.editpage.status=undefined;Page.update({part:'publish'},{url:$stateParams.page,status:'published'},function(data){console.log(data);$scope.editpage.status='published';$scope.$root.page.status='published';},function fail(data){console.log(data.data.error);});};}]}}}).state('root.page.fancybox.setting.themes',{url:'/themes',views:{'settings':{templateUrl:templateUrlFunction('settings/themes'),controller:['$scope','$state','$stateParams',function($scope,$state,$stateParams){}]}}}).state('root.page.fancybox.setting.labels',{url:'/labels',title:['translatorService',function(translatorService){return translatorService.translate('Create labels | Remembr.');}],views:{'settings':{templateUrl:templateUrlFunction('settings/labels'),controller:['$scope','$state','$stateParams','Page','isadmin','translatorService',function($scope,$state,$stateParams,Page,isadmin,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}
$scope.editpage=Page.get({url:$stateParams.page});$scope.newlabel='';$scope.close=function(){$.fancybox.close();};$scope.add=function(){if($.trim($scope.newlabel))
{$scope.editpage.labels.push({name:$.trim($scope.newlabel),'new':true});$scope.newlabel='';$scope.labels.$setDirty();}};$scope.deleteToggle=function(label){$scope.labels.$setDirty();if(label['new'])
{$scope.editpage.labels=$.grep($scope.editpage.labels,function(el){return el!==label;});}
else
{label['delete']=!label['delete'];}};$scope.save=function(){if(!$scope.labels.$dirty)
{return;}
$scope.editpage.$update({part:'labels'},function success(data){$scope.labels.$setPristine();$scope.page.uselabels=data.uselabels;$scope.page.labels=data.labels;},function fail(data){console.log(data.data.error);});};}]}}}).state('root.page.fancybox.setting.invite',{url:'/invite',title:['translatorService',function(translatorService){return translatorService.translate('Send invitations | Remembr.');}],views:{'settings':{templateUrl:templateUrlFunction('settings/invite'),controller:['$state','isadmin','translatorService',function($state,isadmin,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}}]}}}).state('root.page.fancybox.setting.invite-email',{url:'/invite-email',title:['translatorService',function(translatorService){return translatorService.translate('Send invitations via e-mail | Remembr.');}],views:{'settings':{templateUrl:templateUrlFunction('settings/invite-email'),controller:['$scope','$state','$stateParams','Page','isadmin','msgService','translatorService',function($scope,$state,$stateParams,Page,isadmin,msgService,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}
$scope.invite={};$scope.loading=false;$scope.send=function(){$scope.loading=true;$(':focus').blur();if(!$scope.inviteemail.$dirty)
{return;}
Page.invite({url:$stateParams.page},{email:$scope.invite},function success(data){$scope.invite.recipients='';$scope.inviteemail.$setPristine();$scope.loading=false;msgService.inform('Your email invitation has been sent.','info');},function fail(data){console.log(data.data.error);$scope.loading=false;});};}]}}}).state('root.page.fancybox.setting.invite-facebook',{url:'/invite-facebook',title:['translatorService',function(translatorService){return translatorService.translate('Send invitations via Facebook | Remembr.');}],views:{'settings':{templateUrl:templateUrlFunction('settings/invite-facebook'),controller:['$scope','$state','isadmin','Facebook','$stateParams','translatorService',function($scope,$state,isadmin,Facebook,$stateParams,translatorService){if(!isadmin)
{$state.go('root.page.fancybox.setting.error');return;}
$scope.friends=Facebook.getFriends();$scope.sendRequest=function(title,link,linktxt){var thepage=document.location.origin+'/'+$stateParams.page;FB.ui({method:'send',name:title,link:thepage});};}]}}}).state('root.page.fancybox.setting.qrcode',{url:'/qrcode',title:['translatorService',function(translatorService){return translatorService.translate('Create QR code | Remembr.');}],views:{'settings':{templateUrl:function($stateParams){var lang=$stateParams.lang?$stateParams.lang+'/':'';return'/tpl/'+lang+$stateParams.page+'/settings/qrcode';}}}}).state('root.page.fancybox.memory',{url:'/memory/:id',views:{'fancybox@':{templateUrl:templateUrlFunction('page/show'),controller:'MemoryDetailCtrl'}},onEnter:['$rootScope','$state','translatorService',function($rootScope,$state,translatorService)
{var stop=$rootScope.$watch(function(){return $rootScope.page&&$rootScope.page.firstname;},function()
{pagename=$rootScope.page.firstname+' '+$rootScope.page.lastname;document.title=translatorService.translate('%s %s memory | Remembr.').replace('%s %s',pagename);stop();});}]}).state('root.page.fancybox.confirmremoval',{url:'/remove/confirm/:confirmkey',views:{'fancybox@':{templateUrl:templateUrlFunction('page/remove'),controller:['$scope','$state','$stateParams','$http','msgService','$location',function($scope,$state,$stateParams,$http,msgService,$location){if(!$scope.$root.user.loggedin)
{msgService.inform('You need to log in before you can confirm removal of this remembr page','login');var params=angular.copy($stateParams);params.redirect=$location.path().replace(/\//g,'|');$state.go('root.page.fancybox.login',params,{location:false});}
$(window).resize();$scope.close=function(){$.fancybox.close();};$scope.confirm=function(){$http({url:'/json/'+$stateParams.page+'/confirm-removal',data:{confirmkey:$stateParams.confirmkey},method:"POST"}).success(function(result,status){if(result.removed)
{msgService.inform("The page has been removed.","success");$state.go('root.dashboard');}}).error(function(result,status){if(result.error)
{if($scope.page.status=='deactivated')
{msgService.inform('Your request to remove the page has expired because the setting of the page has in the meanwhile been changed to "deactivated".',"error");}
else if($scope.page.status=='published')
{msgService.inform('Your request to remove the page has expired because the setting of the page has in the meanwhile been changed to "published".',"error");}
else
{msgService.inform("An error occurred while trying to remove the page","error");}}
$scope.status=status;});};}]}}}).state('root.search.fancybox.private',{url:'/requestaccess/:page',title:['translatorService',function(translatorService){return translatorService.translate('Send an access request | Remembr.');}],views:{'fancybox@':{templateUrl:templateUrlFunction('page/requestaccess'),controller:['$scope','$state','$stateParams','$http','msgService','Page','$location',function($scope,$state,$stateParams,$http,msgService,Page,$location){var setpage=function(){angular.forEach($scope.searchpages.pages,function(v){if(v.url==$stateParams.page)
{$scope.page=v;}});}
setpage();$scope.$watch(function(){return $scope.searchpages.pages;},setpage);$scope.requestaccess=function()
{if(!$scope.user.loggedin)
{msgService.inform('Please log in to send a request to the administrator','login');$state.go('root.search.fancybox.login');}
else
{console.log($scope.page);Page.requestAccess({url:$scope.page.url},{},function(resp){msgService.inform('Your request has been sent to the administrator','info');},function(resp){console.log(resp);});}}}]}}}).state('root.page.fancybox.private',{url:'/requestaccess',views:{'fancybox@':{templateUrl:templateUrlFunction('page/requestaccess'),controller:['$scope','$state','$stateParams','$http','msgService','Page',function($scope,$state,$stateParams,$http,msgService,Page){$scope.$watch('$root.page.extra.data',function(val){$scope.page=val;});$scope.requestaccess=function()
{if(!$scope.user.loggedin)
{msgService.inform('Please log in to send a request to the administrator','error');$state.go('root.search.fancybox.login');}
else
{Page.requestAccess({url:$scope.page.url},{},function(resp){msgService.inform('Your request has been sent to the administrator','info');},function(resp){console.log(resp);});}}}]}}});}]);
angular.module('remembrConfig',[]).constant('DEBUG_STATES',true).constant('POLLING_INTERVAL',60000);