(function(){'use strict';angular.module('la.rotonda').controller('SiteIndexController',SiteIndexController)
function SiteIndexController($scope,$rootScope,$timeout,HistoryService,LocationService,Geodecoder,LRModalService,MapDrawService){var vm=this,unsubscribe_list=[];vm.setLeasingOfferMode=setLeasingOfferMode;vm.setLeasingRequestMode=setLeasingRequestMode;vm.setPlace=setPlace;vm.setOfferMode=setOfferMode;vm.setRequestMode=setRequestMode;vm.showLogin=showLogin;vm.toIndex=toIndex;vm.mapPlaceholder=mapPlaceholder;vm.$onInit=$onInit;vm.$onDestroy=$onDestroy
function $onInit(){unsubscribe_list.push($scope.$on('index.map.show_modal',_showModal));unsubscribe_list.push($scope.$on('index.map.show_index',_resetStatus));unsubscribe_list.push(google_map.on('map_click',_mapClickHandler));_checkParams()}
function $onDestroy(){angular.forEach(unsubscribe_list,function(unsubcribe){unsubcribe()})}
function _mapClickHandler(data){Geodecoder.getApproximate(data.latLng).then(function(result){var formatted_address=result.formatted_address;vm.search=formatted_address},function(){vm.search=undefined})}
function _checkParams(){var search_params=location.search.substring(1).split('&');if(search_params.length>=1){var params=_splitParams(search_params);if(params.register){_showRegisterModal()}else{var mode=_checkServiceParams(params);_checkLocationParams(params,mode)}}else{_resetStatus();_setDefaultLocation()}
function _checkLocationParams(params,mode){var $address=null,$country=params.x||"Argentina";if(params.p&&params.z){$address=params.z+', '+params.p+', '+$country}else if(params.p){$address='Provincia de '+params.p+', '+$country}else if(params.x)$address=$country;if($address){Geodecoder.decode({address:$address}).then(_moveMapToViewPoint(params,mode))}else _setDefaultLocation()}
function _moveMapToViewPoint(params,mode){return function(result){if(result.length>0){var location_bounds_data=LocationService.getLocationBoundsData(params.p||params.x),place=result[result.length-1],location=location_bounds_data?location_bounds_data.center:place.geometry.location,viewport=location_bounds_data?location_bounds_data.bounds:place.geometry.viewport,formatted_address=place.formatted_address;setPlace(viewport,location,formatted_address);vm.show=mode}}}
function _setDefaultLocation(){google_map.onLoad(function(){LocationService.getLocation().then(function(location){google_map.setCenter(location)})})}
function _checkServiceParams(params){var mode=undefined;switch(params.t){case"s":vm.loaded=true;mode=setRequestMode(params);break;case"o":vm.loaded=true;mode=setOfferMode(params);break;default:_resetStatus()};return mode}
function _showRegisterModal(){$timeout(function(){showLogin('register')})}
function _splitParams(search_params){if(!(search_params.map&&search_params.reduce))return{};return search_params.map(function(a){return a.split('=')}).reduce(function(accumulator,value){accumulator[value[0]]=window.decodeURI(value[1]).toLowerCase();return accumulator},{})}}
function _resetStatus(){vm.loaded=false;vm.search=undefined;vm.show=undefined;vm.showSearch=undefined;google_map.resetMap()}
function toIndex(){if(vm.show)HistoryService.popState();$scope.$broadcast('index.map.show_index')}
function mapPlaceholder(){switch(this.show){case'offer':return'Ubicá tu zona de trabajo';break;case'leasing_offer':return'Ubicá tu lote';break;case'leasing_request':return'Ubicá tu zona de busqueda';break;default:return'Buscá tu lote o localidad';break}}
function setPlace(viewport,location,formatted_address){var map=google_map.getMap();vm.place=location;if(viewport){map.fitBounds(viewport)}else map.setCenter(location);vm.search=formatted_address;$timeout(function(){$scope.$broadcast('index_map_set_position',{latLng:vm.place,map:map})})}
function _init_internal(map){vm.loaded=true;map.setOptions({draggable:true,zoomControl:true})}
function _setMode(mode,event,params){google_map.onLoad(function(map){var ga=window.ga||function(){},unbind=$scope.$on('index_form_loaded',function(){var place=vm.place||google_map.getMap().getCenter();$scope.$broadcast(event,place,params);unbind()});ga('send','event','Map','set_mode',mode);if(mode=='leasing_offer')_addDrawing(map);_init_internal(map);if(!params)vm.show=mode;HistoryService.pushState().then(_rollback)})
function _rollback(){$timeout(function(){$scope.$broadcast('index.map.show_index')})}}
function setOfferMode(params){_setMode('offer','index_map_show_offer',params);return'offer'}
function setRequestMode(params){_setMode('request','index_map_show_request',params);return'request'}
function setLeasingOfferMode(params){_setMode('leasing_offer','index_map_show_leasing_offer',params);return'leasing_offer'}
function setLeasingRequestMode(params){_setMode('leasing_request','index_map_show_leasing_request',params);return'leasing_request'}
function _showModal($event,data){LRModalService.open('first_request_form',data)}
function showLogin(section){$rootScope.$broadcast("open-login-view",section)}
function _addDrawing(map){MapDrawService.addDrawing(map,null,google.maps.ControlPosition.BOTTOM_CENTER);MapDrawService.setDrawingMode(null)}}})();(function(){'use strict';angular.module('la.rotonda').controller("SubmitDialogController",SubmitDialogController)
function SubmitDialogController($http,LRService){var vm=this;vm.submit=submit;vm.$onInit=function(){vm.not_actions=true;if(vm.modal)vm.modal.registryOpen(function(data){vm.user={};vm.valid=true;vm.data=data})}
function submit(){if(vm.form.$valid){vm.data.LoginForm=vm.user;$http.post(LRService.getUrl('prelogin'),vm.data).then(function(response){var response_data=response.data;if(response_data.status){location.reload()}else vm.valid=false})}}}})();(function(){'use strict';angular.module('la.rotonda').controller('IndexOfferModeController',IndexOfferModeController).controller('IndexLeasingOfferModeController',IndexLeasingOfferModeController).controller('IndexLeasingRequestModeController',IndexLeasingRequestModeController).controller('IndexRequestModeController',IndexRequestModeController)
function _extendModeController($injector,$scope,self,mode,afterInit){var parent=$injector.instantiate(["MapHelper","Marker","RotonderCounter","ServiceList","MapDrawService","LRService","Geodecoder",IndexModeController]);angular.extend(self,parent);self.inicialize($scope,mode,afterInit)}
function IndexRequestModeController($injector,$scope){var vm=this;vm._getData=_getData;_extendModeController($injector,$scope,vm,'request')
function _getData(point){return{Input:{lat:point.lat,lng:point.lng,service_target_id:vm.input.service.target,service_type_id:vm.input.service.type,final_price:vm.input.price,value:vm.input.value,city:vm.input.city,country:vm.input.country,iso:vm.input.iso,state:vm.input.state}}}}
function IndexOfferModeController(Marker,$injector,$scope){var vm=this;vm.updateDist=updateDist;vm._getData=_getData;vm.input={dist:100};_extendModeController($injector,$scope,vm,'offer',function(){updateDist(true)})
function _getData(point){return{Offers:{service:vm.input.service,lat:point.lat,lng:point.lng,dist:vm.input.dist,city:vm.input.city,country:vm.input.country,iso:vm.input.iso,state:vm.input.state}}}
function updateDist(keep_bounds){var dist=parseInt(vm.input.dist);if(dist){var circle=Marker.setRadius(vm.marker,google_map.getMap(),vm.input.dist);if(!keep_bounds)google_map.getMap().fitBounds(circle.getBounds())}}}
function IndexLeasingRequestModeController(Marker,LRService,$injector,$scope){var vm=this;vm.updateDist=updateDist;vm._getData=_getData;vm.input={dist:100};vm.input.service={};_extendModeController($injector,$scope,vm,'leasing_request',function(){updateDist(true)})
function _getData(point){vm.input.service.type=this.services.types.find(function(y){return y.class==LRService.LEASING_SERVICE}).id;vm.input.service.target=this.services.targets.find(function(y){return y.class==LRService.LEASING_SERVICE}).id;return{LeasingRequest:{service:vm.input.service,initial_price:vm.input.price,lat:point.lat,lng:point.lng,dist:vm.input.dist,hectares:vm.input.hectares,max_hectares:vm.input.max_hectares,class:LRService.LEASING_SERVICE,city:vm.input.city,country:vm.input.country,iso:vm.input.iso,state:vm.input.state}}}
function updateDist(keep_bounds){var dist=parseInt(vm.input.dist);if(dist){var circle=Marker.setRadius(vm.marker,google_map.getMap(),vm.input.dist);if(!keep_bounds)google_map.getMap().fitBounds(circle.getBounds())}}}
function IndexLeasingOfferModeController(MapDrawService,LRService,$injector,$scope,$timeout){var vm=this,missingPlot=false,sizeError=false;vm.plotMissingError=plotMissingError;vm.plotSizeError=plotSizeError;vm._getData=_getData;vm.setDrawingMode=setDrawingMode;vm.resetPol=resetPol;vm.plotSubmit=plotSubmit;vm.area=0;vm.input={dist:100};_extendModeController($injector,$scope,vm,'leasing_offer',function(){MapDrawService.setSelectionCallback(_selectionCallback)})
function _getData(point){return{LeasingOffer:{lat:point.lat,lng:point.lng,coordinates:vm.input.coordinates,service_target_id:_leasingTargetId(),service_type_id:_leasingTypeId(),leasing_price:vm.input.leasing_price,final_price:0,value:vm.input.hectare,city:vm.input.city,country:vm.input.country,iso:vm.input.iso,state:vm.input.state}}}
function resetPol(){MapDrawService.deleteSelectedShape();$timeout(function(){vm.area=MapDrawService.getArea()})}
function setDrawingMode(){MapDrawService.setDrawingMode(google.maps.drawing.OverlayType.POLYGON)}
function plotMissingError(){return missingPlot}
function plotSizeError(){return sizeError}
function _plotSubmitCheck(){vm.input.coordinates=MapDrawService.getPolygonCoords();if(vm.input.coordinates){if(vm.area>0)if(Number(vm.input.hectare)+50<Number(vm.area)){vm.hectaresError=true;sizeError=true;return false};return true}else{missingPlot=true;return false}}
function _leasingTypeId(){const service=vm.services.types.find(function(y){return y.class==LRService.LEASING_SERVICE});return service.id}
function _leasingTargetId(){const service=vm.services.targets.find(function(y){return y.class==LRService.LEASING_SERVICE});return service.id}
function plotSubmit(){if(_plotSubmitCheck())this.submit()}
function _selectionCallback(){missingPlot=false;$timeout(function(){vm.area=MapDrawService.getArea()});$scope.$apply()}}
function IndexModeController(MapHelper,Marker,RotonderCounter,ServiceList,MapDrawService,LRService,Geodecoder){this.close=close;this.inicialize=inicialize;this.submit=submit;var setMarkerPosition,listeners=[]
function inicialize($scope,mode,afterInit){this.$scope=$scope;this.mode=mode;this.afterInit=afterInit;setMarkerPosition=_setMarkerPosition.bind(this);listeners.push(google_map.on('map_click',setMarkerPosition));listeners.push(this.$scope.$on('index_map_show_'+this.mode,_init_mode(this,this.mode)));listeners.push(this.$scope.$on('index.map.show_index',_reset.bind(this)));listeners.push(this.$scope.$on('index_map_set_position',function($event,data){setMarkerPosition(data)}))};this.$onInit=function(){this.input||(this.input={});this.first_visit=true;this.service_wait=ServiceList.getList().then(_setServices.bind(this));this.$scope.$emit('index_form_loaded')};this.$onDestroy=function(){angular.forEach(listeners,function(remove){remove()})}
function submit(){var ga=window.ga||function(){};if(this.form.$valid){ga('send','event','Map','submit','valid');var point=MapHelper.getPointValues(this.marker.position),data=this._getData(point);this.$scope.$emit('index.map.show_modal',data)}else ga('send','event','Map','submit','invalid')}
function close(){this.$scope.$emit('index.map.show_index')}
function _setServices(services){this.services=services;if(this.services.length>0)this.service=this.services[0].id}
function _init_mode(self,mode){return function($event,latLng,params){setMarkerPosition({latLng:latLng,map:google_map.getMap(),mode:mode});self.showInputs=false;_checkParams(self,params,mode);if(self.afterInit)self.afterInit()}}
function _setMarkerPosition(data){var content;if(this.mode==='request'||this.mode==='leasing_offer'){content='<div class="map-popover">¡Ubicá acá tu lote!</div>'}else if(this.mode==='offer'){content='<div class="map-popover">¡Ubicá acá tus equipos!</div>'}else if(this.mode==='leasing_request')content='<div class="map-popover">¡Ubicá acá tu zona de busqueda!</div>';if(!this.marker){this.marker=Marker.createMarker(data.map,data.latLng)}else Marker.setMarkerInMap(this.marker,data.map,data.latLng);if(!this.marker.infoWindow){this.infoWindow=Marker.setInfoToMarker(this.marker,data.map,content);Marker.openInfoMarker(this.marker,data.map,this.infoWindow)};var that=this;Geodecoder.getApproximate(this.marker.position).then(function(result){if(result.address_components)MapHelper.setStateInfo(result.address_components,that.input)})}
function _reset(){if(this.marker){if(this.marker.circle)this.marker.circle.setMap(null);this.marker.setMap(null);this.marker=undefined};if(this.form)this.form.$setPristine()}
function _checkParams(self,params,mode){self.service_wait.then(function(){var value_id,value_message,price_message;if(mode==='request'){value_id="#request-hectares";value_message="Cuántas hectáreas tiene tu lote";price_message="Lo máximo que estás dispuesto a pagar por este servicio"}else if(mode==='offer'){value_id="#offer-distance";value_message="Cuántos kilómetros estás dispuesto a desplazarte";price_message="Monto mínimo que estás dispuesto a percibir por tu trabajo"};if(params&&(params.s||params.c)){if(!self.input)self.input={};if(!self.input.service)self.input.service={};if(params.s)angular.forEach(self.services.types,function(type){if(type.description.toLowerCase()===params.s)self.input.service.type=type.id});if(params.c)angular.forEach(self.services.targets,function(target){if(target.description.toLowerCase()===params.c)self.input.service.target=target.id});if(params.s&&!params.c){_initPopover("#"+mode+"-target","Elegí el tipo de cultivo","change",value_id);$("#"+mode+"-target").focus();_initPopover(value_id,value_message,undefined,"#"+mode+"-price");_initPopover("#"+mode+"-price",price_message)}else if(!params.s&&params.c){_initPopover("#"+mode+"-service","Elegí el servicio","change",value_id);$("#"+mode+"-service").focus();_initPopover(value_id,value_message,undefined,"#"+mode+"-price");_initPopover("#"+mode+"-price",price_message)}else if(params.s&&params.c){_initPopover(value_id,value_message,undefined,"#"+mode+"-price");$(value_id).focus();_initPopover("#"+mode+"-price",price_message)}}else{_initPopover("#"+mode+"-service","Elegí el servicio","change","#"+mode+"-target");_initPopover("#"+mode+"-target","Elegí el tipo de cultivo","change",value_id);_initPopover(value_id,value_message,undefined,"#"+mode+"-price");_initPopover("#"+mode+"-price",price_message)}})}
function _initPopover(css_selector,content,mode,next_selector){$(css_selector).popover({content:content,placement:"right",trigger:"manual",container:"body"});if(mode)$(css_selector)[mode](function(){if(next_selector)$(next_selector).focus()});$(css_selector).focusin(function(){var width=$(window).innerWidth();if(width>767){$(css_selector).popover("show");setTimeout(function(){$(css_selector).popover("destroy")},2e4)}});$(css_selector).focusout(function(){$(this).popover("hide")})}
function _showRotonders(mode){var data={map:google_map.getMap(),latLng:google_map.getMap().getCenter(),mode:mode};RotonderCounter.show(data)}}})();(function(){'use strict';angular.module('la.rotonda').controller('FirstActionModalController',FirstActionModalController)
function FirstActionModalController($rootScope){var vm=this;vm.register=register;vm.$onInit=function(){vm.not_actions=true;if(vm.modal)vm.modal.registryOpen(function(data){vm.count=data.count;vm.mode=data.mode})}
function register(){vm.modal.hide();$rootScope.$broadcast("open-login-view",'register')}}})()
;
(function(){'use strict';angular.module('la.rotonda').service('MapHelper',MapHelper)
function MapHelper($q){return{getDistance:getDistance,getMapBounds:getBounds,getPointValues:getPointValues,setStateInfo:setStateInfo}
function getPointValues(latLng){var lat=angular.isFunction(latLng.lat)?latLng.lat():latLng.lat,lng=angular.isFunction(latLng.lng)?latLng.lng():latLng.lng;return{lat:lat,lng:lng}}
function getBounds(map){return $q(function(resolve){var bounds=map.getBounds();if(!bounds){var handler=google.maps.event.addListener(map,'bounds_changed',function(){resolve(_getBoundData(map));google.maps.event.removeListener(handler)})}else resolve(_getBoundData(map))})}
function getDistance(p1,p2){var R=6378137,dLat=_rad(p2.lat()-p1.lat()),dLong=_rad(p2.lng()-p1.lng()),a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(_rad(p1.lat()))*Math.cos(_rad(p2.lat()))*Math.sin(dLong/2)*Math.sin(dLong/2),c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)),d=R*c;return d/1e3}
function _rad(x){return x*Math.PI/180}
function _getBoundData(map){var bounds=map.getBounds(),ne=bounds.getNorthEast(),sw=bounds.getSouthWest();return{bounds:bounds,ne:ne,sw:sw}}
function setStateInfo(address_component,plot){if(address_component&&plot){var stateIndex=_getStateIndex(address_component);if(stateIndex>=0){plot.city=address_component[stateIndex].long_name;plot.state=address_component[stateIndex+1].long_name;plot.country=address_component[stateIndex+2].long_name;plot.iso=address_component[stateIndex+2].short_name}}}
function _getStateIndex(mapResult){var find=false,index=0;while(!find&&index<mapResult.length){find=mapResult[index].types[0]=='administrative_area_level_2';index++};if(find==true){return index-1}else return-1}}})();(function(){'use strict';angular.module('la.rotonda').service('RotonderCounter',RotonderCounter)
function RotonderCounter(Geodecoder,LRModalService,MapHelper,$http){var ALLOW_COUNTRIES_FOR_MESSAGE=['Argentina','Uruguay'];return{show:show}
function show(data){return Geodecoder.getApproximate(data.latLng).then(function(result){var country_name=_getCountryName(result);if(isCountryAllowed(country_name))return _count(data).then(function(count){if(count>0)LRModalService.open('first_action_modal',{mode:data.mode,count:count})})})}
function isCountryAllowed(country_name){var allowed=ALLOW_COUNTRIES_FOR_MESSAGE.indexOf(country_name.trim())>=0;return allowed}
function _getCountryName(result){var full_address=result.formatted_address.split(","),country=full_address[full_address.length-1];return country}
function _count(data){return MapHelper.getMapBounds(data.map).then(function(bounds_data){var pos=MapHelper.getPointValues(data.latLng),radius=MapHelper.getDistance(bounds_data.ne,bounds_data.sw)/2;return $http.get('process/countRotonders',{params:{lat:pos.lat,lng:pos.lng,rad:radius,mode:data.mode}}).then(function(response){return response.data})})}}})();(function(){'use strict';angular.module('la.rotonda').service('MapCreator',MapCreator)
function MapCreator(){return{createMap:createMap}
function createMap(elementId){var mapElement=document.getElementById(elementId);if(mapElement&&window.google){var map=new google.maps.Map(mapElement,{center:{lat:-37.26941496733317,lng:-58.968465802392515},zoom:12,mapTypeId:google.maps.MapTypeId.HYBRID,disableDefaultUI:true,scrollwheel:true,draggable:true});return map}}}})();(function(){'use strict';angular.module('la.rotonda').service('Marker',MarkerService)
function MarkerService(){return{createMarker:createMarker,setMarkerInMap:setMarkerInMap,setRadius:setRadius,setInfoToMarker:setInfoToMarker,openInfoMarker:openInfoMarker}
function createMarker(map,latLng,icon){var marker=new google.maps.Marker({position:latLng,map:map,icon:{url:icon||'/images/pin.svg',size:new google.maps.Size(30,48),origin:new google.maps.Point(0,0),scaledSize:new google.maps.Size(30,48)}});marker.addListener('dblclick',function(e){map.setOptions({zoom:map.zoom+1});map.setCenter(marker.position)});return marker}
function setInfoToMarker(marker,map,content){var infoWindow=new google.maps.InfoWindow({content:content});marker.addListener('click',function(){infoWindow.open(map,marker)});marker.infoWindow=infoWindow;return infoWindow}
function openInfoMarker(marker,map,infoWindow){infoWindow.open(map,marker)}
function setMarkerInMap(marker,map,latLng){marker.setPosition(latLng);marker.setMap(map);if(marker.circle)marker.circle.setCenter(marker.position)}
function setRadius(marker,map,radius,custom_options){radius=parseInt(radius)*1e3;if(marker.circle){marker.circle.setRadius(radius);marker.circle.setCenter(marker.position);return marker.circle}else{var options={strokeColor:"#0000FF",strokeOpacity:0.10,strokeWeight:2,fillColor:"#0000FF",fillOpacity:0.20};angular.extend(options,custom_options);options.map=map;options.radius=radius;options.center=marker.position;marker.circle=new google.maps.Circle(options);marker.circle.addListener('click',function(e){google_map.fire('map_click',{latLng:e.latLng,map:map})});return marker.circle}}}})();(function(){'use strict';angular.module('la.rotonda').service('Geodecoder',GoogleGeodecoderService)
function GoogleGeodecoderService($q){var geocoder;google_map.onLoad(function(){initGeo()});return{decode:decode,getApproximate:getApproximate,initGeo:initGeo}
function initGeo(){geocoder=new google.maps.Geocoder()}
function getApproximate(latLng){return $q(function(response,reject){geocoder.geocode({latLng:latLng},function(results,status){if(status==='OK'){var approximate_results=$.grep(results,function(result){var location_type=result.geometry.location_type;return location_type!=='GEOMETRIC_CENTER'}),result=undefined;if(!approximate_results){result=results[0]}else result=approximate_results[0];if(result){response(result)}else reject({results:results,status:status})}else reject({status:status,result:results})})})}
function decode(options){return $q(function(response,reject){google_map.onLoad(function(){geocoder.geocode(options,function(result,status){if(status==='OK'){response(result)}else reject({status:status,result:result})})})})}}})();(function(){'use strict';angular.module('la.rotonda').directive('lrGac',GoogleAutoComplete)
function GoogleAutoComplete(Geodecoder){return{restrict:'A',scope:{lrGac:'&'},link:createAutocomplete}
function createAutocomplete(scope,element){google_map.onLoad(function(){var autocomplete=new google.maps.places.Autocomplete(element[0]);autocomplete.bindTo('bounds',google_map.getMap());autocomplete.addListener('place_changed',function(){var ga=window.ga||function(){},place=autocomplete.getPlace();if(!place.geometry){ga('send','event','Map','search_enter',place.name);Geodecoder.decode({address:place.name}).then(function(result){if(result.length>0){place=result[result.length-1];doCallback(scope,place,autocomplete)}})}else{ga('send','event','Map','search_selected',place.formatted_address);doCallback(scope,place,autocomplete);scope.$apply()}})})}
function doCallback(scope,place,autocomplete){var viewport=place.geometry.viewport,location=place.geometry.location;scope.lrGac({autocomplete:autocomplete,viewport:viewport,location:location,formatted_address:place.formatted_address})}}})();(function(){'use strict';angular.module('la.rotonda').service('ServiceList',ServiceList)
function ServiceList($http,LRService){this.getList=_getList()
function _getList(){var promise;return function(){return promise?promise:(promise=_get())}}
function _get(){return $http.get(LRService.getUrl('se_getServiceList')).then(function(response){var services=response.data;return services})}}})();(function(){'use strict';angular.module('la.rotonda').service('LocationService',LocationService)
function LocationService($q,$http,LRService){return{getLocation:getLocation,getLocationBoundsData:getLocationBoundsData}
function getLocation(){return _getBestLocation().then(_location,_defaultLocation)}
function getLocationBoundsData(location){var location_bounds={argentina:{bounds:{north:-19,south:-40,east:-58,west:-65},center:{lat:-35.644076,lng:-62.246952}},"buenos aires":{bounds:{north:-34,south:-38.5,east:-58.5,west:-63},center:{lat:-36.332235,lng:-60.366843}}},key=location?location.toLowerCase():undefined;return location_bounds[key]}
function _getBestLocation(){return $q(function(success,reject){if(navigator.geolocation){var options={enableHighAccuracy:true};navigator.geolocation.getCurrentPosition(function(position){success({lat:position.coords.latitude,lng:position.coords.longitude})},function(){_getIpLocation().then(success,reject)},options)}else _getIpLocation().then(success,reject)})}
function _getIpLocation(){return $q(function(success,reject){return $http.get(LRService.getUrl('location')).then(function(response){if(response.data&&response.data.countryCode==="AR"){success({lat:response.data.lat,lng:response.data.lon})}else reject()},function(){reject()})})}
function _location(location){return location}
function _defaultLocation(){return{lat:-37.26941496733317,lng:-58.968465802392515}}}})();(function(){'use strict';angular.module('la.rotonda').service('MapDrawService',MapDrawService)
function MapDrawService(){var drawingManager,selectedShape,selectionCallback,area=0;return{addDrawing:addDrawing,getPolygonCoords:getPolygonCoords,deleteSelectedShape:deleteSelectedShape,setSelection:setSelection,addPlotShape:addPlotShape,disableDrawing:disableDrawing,setDrawingMode:setDrawingMode,setSelectionCallback:setSelectionCallback,getArea:getArea}
function addDrawing(map,callback,position,mode){selectionCallback=callback;drawingManager=new google.maps.drawing.DrawingManager({drawingMode:mode||google.maps.drawing.OverlayType.POLYGON,drawingControl:true,drawingControlOptions:{position:position||google.maps.ControlPosition.TOP_CENTER,drawingModes:[google.maps.drawing.OverlayType.POLYGON]},polygonOptions:{editable:true,fillColor:'#fac031',strokeColor:'#fac031'}});drawingManager.setMap(map);google.maps.event.addListener(drawingManager,'polygoncomplete',function(polygon){disableDrawing();var newPlotShape=polygon;google.maps.event.addListener(newPlotShape,'click',function(){setSelection(newPlotShape)});setSelection(newPlotShape)})}
function setSelection(shape){selectedShape=shape;try{area=google.maps.geometry.spherical.computeArea(selectedShape.getPath())}catch(e){area=0};shape.setEditable(true);if(selectionCallback)selectionCallback()}
function addPlotShape(map,coordinates){if(coordinates){const cords=_stringToCoord(coordinates);var plotShape=new google.maps.Polygon({paths:cords,editable:true,fillColor:'#fac031',strokeColor:'#fac031'});if(plotShape){disableDrawing();plotShape.setMap(map);google.maps.event.addListener(plotShape,'click',function(){setSelection(plotShape)});setSelection(plotShape)}}}
function disableDrawing(){setDrawingMode(null);drawingManager.setOptions({drawingControl:false})}
function setSelectionCallback(callback){selectionCallback=callback}
function setDrawingMode(mode){drawingManager.setDrawingMode(mode)}
function getPolygonCoords(){if(selectedShape){var coords=selectedShape.getPath().getArray();if(area==0)return null;var cordObject=[];for(var i=0;i<coords.length;i++)cordObject.push({lat:coords[i].lat().toFixed(5),lng:coords[i].lng().toFixed(5)});return _coordToStrig(cordObject)}else return null}
function deleteSelectedShape(){if(selectedShape){selectedShape.setMap(null);drawingManager.setOptions({drawingControl:true});selectedShape=null};area=0}
function _stringToCoord(coordString){if(coordString.charAt(coordString.length-1)==';')coordString=coordString.slice(0,-1);const points=coordString.split(';');const coordArray=[];for(var i=0;i<points.length;i++){var point=points[i].split(' ');coordArray.push({lat:parseFloat(point[0]),lng:parseFloat(point[1])})};return coordArray}
function _coordToStrig(coordObj){var coordString='';for(var i=0;i<coordObj.length;i++)coordString+=coordObj[i].lat+' '+coordObj[i].lng+';';return coordString}
function getArea(){return(area/1e4).toFixed()}}})()
;
(function(){'use strict';angular.module('la.rotonda').controller('loginCtrl',loginCtrl)
function loginCtrl($http,$scope,$timeout,LRService){var login=this;login.login=loginFn;login.recovery=recovery;login.register=register;login.setLoginMode=setLoginMode;login.setLostMode=setLostMode;login.setRegisterMode=setRegisterMode;login.title='Iniciar sesión';login.show='login';$scope.$on('open-login-view',function($event,view){var ga=window.ga||function(){};ga('send','event','Login','open_mode',view);switch(view){case"login":setLoginMode();break;case"lost":setLostMode();break;case"register":setRegisterMode();break};$('#login-modal').modal()})
function setLoginMode(){login.title='Ingresar';login.show='login';_setAuth0('login')}
function setRegisterMode(){login.title='Registrarse';login.show='register';_setAuth0('register')}
function setLostMode(){login.title="Recuperar contraseña";login.show='lost'}
function _setAuth0(mode){$timeout(function(){var options=_getAuth0Options(mode),lock=new Auth0Lock(LRService.AUTH0_CLIENT_ID,LRService.AUTH0_DOMAIN,options);lock.show()})}
function _getAuth0Options(mode){var options={auth:{redirectUrl:LRService.AUTH0_CALLBACK_URL,responseMode:'form_post',responseType:'code',params:{scope:'openid email'},sso:false},container:'login-auth0-lock',socialButtonStyle:'big',allowForgotPassword:false,allowedConnections:['facebook','google-oauth2'],allowLogin:mode==='login',allowSignUp:mode==='register',language:'es'};return options}
function loginFn(){if(login.user){var username=login.user.username,password=login.user.password;if(username&&password)$http.post(LRService.getUrl('login'),{LoginForm:login.user},{params:{ajax:true}}).then(function(response){var data=response.data;if(data.status){location.replace(data.data.returnUrl)}else login.user.error=data.error},function(error){console.log(error)})}}
function recovery(){if(login.user)$http.post(LRService.getUrl('passwordforgot'),{email:login.user.username}).then(function(response){if(response.data.status){location.href=response.data.data}else login.lost.error=response.data.errors})}
function register(){if(login.registry&&login.form.$valid){var registry=login.registry,data={Registry:registry};$http.post(LRService.getUrl('registry'),data).then(function(response){if(response.data.status){location.href=LRService.getUrl('checkemail')+'?email='+registry.email}else if(response.data.errors){registry.error=response.data.errors;login.form.$setDirty()}})}}}})();(function(){'use strict';angular.module('la.rotonda').run(ModalRunConfig)
function ModalRunConfig(HistoryService,$injector){var histories=[];if(!HistoryService.getCurrentData().modal_loaded){$("body").on('shown.bs.modal',function(e){if(!histories[e.target.id]){histories[e.target.id]=History.getState().hash;HistoryService.pushState({id:e.target.id}).then(function(){if(histories[e.target.id])$(e.target).modal("hide");histories[e.target.id]=false})}});$("body").on('hidden.bs.modal',function(e){if(histories[e.target.id]){histories[e.target.id]=false;HistoryService.popState()}});if($injector.has('$mdDialog')){var $mdDialog=$injector.get('$mdDialog'),default_hide=$mdDialog.hide,default_show=$mdDialog.show,rand=Math.random();$mdDialog.hide=function(response){HistoryService.popState();return default_hide(response)};$mdDialog.show=function(config){HistoryService.pushState({id:rand}).then(function(){default_hide()});return default_show(config)}}};HistoryService.addData({modal_loaded:true})}})();(function(){'use strict';angular.module('la.rotonda').directive('onlyDigitsDirective',onlyDigitsDirective)
function onlyDigitsDirective(){return{restrict:'EA',require:'?ngModel',scope:{allowDecimal:'@',allowNegative:'@',minNum:'@',maxNum:'@'},link:function(scope,element,attrs,ngModel){if(!ngModel)return;ngModel.$parsers.unshift(function(inputValue){var decimalFound=false,digits=inputValue.split('').filter(function(s,i){var b=(!isNaN(s)&&s!==' ');if(!b&&attrs.allowDecimal&&attrs.allowDecimal==="true")if(s==="."&&decimalFound===false){decimalFound=true;b=true};if(!b&&attrs.allowNegative&&attrs.allowNegative==="true")b=(s==='-'&&i===0);return b}).join('');if(attrs.maxNum&&!isNaN(attrs.maxNum)&&parseFloat(digits)>parseFloat(attrs.maxNum))digits=attrs.maxNum;if(attrs.minNum&&!isNaN(attrs.minNum)&&parseFloat(digits)<parseFloat(attrs.minNum))digits=attrs.minNum;ngModel.$viewValue=digits;ngModel.$render();return digits})}}}})();(function(){'use strict';angular.module('la.rotonda').service('HistoryService',HistoryService)
function HistoryService($q){var default_title=document.title;inicialize();var states_deferred=[];return{pushState:pushState,popState:popState,getCurrentData:getCurrentData,addData:addData}
function addData(data){var state=History.getState(),new_data={};angular.extend(new_data,state.data,data);state.data=new_data;History.replaceState(new_data,state.title,state.url)}
function getCurrentData(){var state=History.getState();return state.data}
function pushState(data,name,path){var deferred=$q.defer(),state=History.getState(),_data=data||{};if(!path)path=null;if(!name)name=default_title;History.pushState(_data,name,path);states_deferred[state.id]=deferred;return deferred.promise}
function popState(){History.back(false)}
function inicialize(){History.replaceState({},default_title,null);History.Adapter.bind(window,'statechange',function(){var state=History.getState();if(states_deferred[state.id]){states_deferred[state.id].resolve(state.data);states_deferred[state.id]=undefined}})}}})();(function(){'use strict';angular.module('la.rotonda').directive('lrLabel',LabelDirective)
function LabelDirective($timeout){return{restrict:'EA',require:'^form',scope:{lrInputs:"@",lrMessages:"<",lrAlways:'='},transclude:true,template:"<div class=\"lr-input_msg\" \n\
                      ng-class=\"{'lr-input_invalid': invalid}\"\n\
                    >\n\
                      <div ng-if=\"invalid\" class = \"fa fa-times error\"></div>\n\
                    <span ng-show=\"text\">\n\
                        {{text.message}}\n\
                    </span>\n\
                    <span ng-show=\"!text\">\n\
                        <ng-transclude></ng-transclude>\n\
                    </span>\n\
                </div>",link:labelLinker}
function labelLinker($scope,$element,$attrs,FormController){$scope.check=!!$scope.lrAlways;$timeout(function(){var input_names=$scope.lrInputs.split(','),input_models=[];angular.forEach(input_names,function(input_name){var input_name_trimmed=input_name.trim(),input_model=FormController[input_name_trimmed];if(input_model)input_models.push(input_model)});if(input_models.length>0)controlInput(input_models,$scope,FormController)})}
function controlInput(input_models,$scope,FormController){$scope.$watch(function(){if($scope.check||(FormController.$submitted)){var countInvalidInputModels=_countInvalidInputModels(input_models);return countInvalidInputModels}else return false},function(new_value,old_value){$scope.invalid=!!new_value;if(new_value!==old_value){var error_list={},active_error=undefined;angular.forEach(input_models,function(input_model){error_list=angular.merge(error_list,input_model.$error)});angular.forEach(error_list,function(error,error_name){if(error)active_error=error_name});if($scope.lrMessages&&$scope.lrMessages[active_error]){$scope.text={message:$scope.lrMessages[active_error]}}else $scope.text=undefined}else if($scope.text)$scope.text=undefined})}
function _countInvalidInputModels(input_models){var invalid_inputs="",i=0;while(i<input_models.length){if(input_models[i].$invalid)for(var error_name in input_models[i].$error)invalid_inputs+=error_name;i++};return invalid_inputs}}})();(function(){angular.module('la.rotonda').controller('MainController',MainController)
function MainController($scope,LRService){var vm=this;vm.t=moment().unix();$scope.$on('change_time',function(){vm.t=moment().unix()});$scope.$user_enabled=LRService.user_enabled;$scope.$has_phone=LRService.has_phone}})();(function(){'use strict';angular.module('la.rotonda').directive('lrPhoneInput',LRPhoneInput)
function LRPhoneInput(){return{restrict:'A',require:'ngModel',scope:{lrOutput:'='},transclude:true,link:setUp}
function setUp(scope,element,attrs,ctrl){var phoneInput=element;_initIntlTelInput(phoneInput);if(attrs.value!=='NULL'){ctrl.$setViewValue(attrs.value)}else ctrl.$setViewValue('');ctrl.$setPristine();scope.$watch(_numberWatcher,function(newValue,oldValue){if(newValue!==oldValue){var isEmpty=newValue.length===0;if(phoneInput.intlTelInput("isValidNumber")){var number=_parseNumber(newValue);scope.lrOutput=number;phoneInput.intlTelInput("setNumber",number)}else if(isEmpty)scope.lrOutput=null}})
function validate(errorCode){var toReturn=true,isEmpty=element.intlTelInput("getNumber").length===0;if(!isEmpty){var error=element.intlTelInput("getValidationError");toReturn=error!==errorCode};return toReturn};ctrl.$validators.notANumber=function(){var isEmpty=element.intlTelInput("getNumber").length===0;return isEmpty||phoneInput.intlTelInput("isValidNumber")};ctrl.$validators.invalidCountryCode=function(){return validate(intlTelInputUtils.validationError.INVALID_COUNTRY_CODE)};ctrl.$validators.tooLong=function(){return validate(intlTelInputUtils.validationError.TOO_LONG)};ctrl.$validators.tooShort=function(){return validate(intlTelInputUtils.validationError.TOO_SHORT)}
function _numberWatcher(){return phoneInput.intlTelInput("getNumber",intlTelInputUtils.numberFormat.NATIONAL)}
function _parseNumber(newValue){if(newValue.length>0){var number=newValue,country=phoneInput.intlTelInput("getSelectedCountryData").dialCode,num_split=number.split(" "),local=num_split[0].substr(1),is_mobile=phoneInput.intlTelInput("getNumberType")===intlTelInputUtils.numberType.MOBILE,is_arg=country===54;if(is_mobile&&is_arg){number=num_split[1].substr(3).split("-").join("")}else number=num_split[1].split("-").join("");return'00'+country+local+number};return null}}
function _initIntlTelInput(phoneInput){phoneInput.intlTelInput({formatOnDisplay:true,initialCountry:"ar",nationalMode:true,placeholderNumberType:"FIXED_LINE",preferredCountries:['ar']})}}})();(function(){$(function(){activate_production_scripts()})
function activate_production_scripts(){if(window.$prod_data&&$prod_data.is_prod===true){var email=$prod_data.email;start_smartlook();start_tidio();function start_smartlook(){window.smartlook||(function(d){var o=smartlook=function(){o.api.push(arguments)},h=d.getElementsByTagName('head')[0],c=d.createElement('script');o.api=new Array();c.async=true;c.type='text/javascript';c.charset='utf-8';c.src='https://rec.smartlook.com/recorder.js';h.appendChild(c)})(document);window.smartlook('init','31e7237242c5ab76568e8323fd9afb5bc9a543ad');if(email)window.smartlook('tag','email',email)};function start_tidio(){window.tidio||(function(d){var h=d.getElementsByTagName('head')[0],c=d.createElement('script');c.async=true;c.type='text/javascript';c.charset='utf-8';c.src='//code.tidio.co/ejrtve3zxloz9iwoklz9ekdbp5lshhmi.js';h.appendChild(c)})(document);$("body").on('hidden.bs.modal',toggleTidio(true));$("body").on('shown.bs.modal',toggleTidio(false))
function toggleTidio(show){return function(){if(window.tidioChatApi)window.tidioChatApi.method('chatDisplay',show)}}}}}})();(function(){'use strict';angular.module('la.rotonda').service('LRModalService',LRModalService)
function LRModal(id,id_or_element){if(angular.isElement(id_or_element)){this.modal=$(id_or_element[0]);if(!this.modal.attr('id'))this.modal.attr('id',id)}else this.modal=$("#"+id_or_element);this.id=id;this.opened=false;this.hide=hide;this.show=show;this.registryOpen=registryOpen;this.registryClose=registryClose;this.registryShow=registryShow;this.registryShown=registryShown;this.registryHide=registryHide;this.registryHidden=registryHidden;this.unreg=unreg
function hide(){this.modal.modal('hide')}
function show(data){var self=this,defered=this.$q.defer();if(this.open)this.open(data);var handler=function(){if(self.opened){var returnData=undefined;self.opened=false;if(self.close)returnData=self.close();self.modal.off('hide.bs.modal',handler);defered.resolve(returnData)}else defered.reject()};this.modal.on('hide.bs.modal',handler);this.modal.modal('show');this.opened=true;return defered.promise}
function registryOpen(callback){this.open=callback;return this}
function registryClose(callback){this.close=callback;return this}
function registryShow(callback){this.modal.on('show.bs.modal',callback);return this}
function registryShown(callback){this.modal.on('shown.bs.modal',callback);return this}
function registryHide(callback){this.modal.on('hide.bs.modal',callback);return this}
function registryHidden(callback){this.modal.on('hidden.bs.modal',callback);return this}
function unreg(event,callback){this.modal.off(event,callback);return this}}
function LRModalService($q){var self=this;self.modals={};self.current=undefined;self.preload_map={};self.registry=registry;self.open=open;self.get=get;LRModal.prototype.$q=$q
function get(id){return this.modals[id]}
function registry(id,modal_id){this.modals[id]=new LRModal(id,modal_id);return this.modals[id]}
function open(id,data){return $q(function(resolve,reject){if(self.current){var current=self.current,handler=function(){current.unreg('hidden.bs.modal',handler);_show(id,data,resolve,reject,true)};self.current.registryHidden(handler);self.current.hide()}else _show(id,data,resolve,reject)})}
function _show(id,data,resolve,reject,do_apply){var modal_obj=self.modals[id];if(modal_obj){self.current=modal_obj;modal_obj.show(data).then(function(){self.current=false;resolve.apply(self,arguments)});if(do_apply){var modal_scope=modal_obj.modal.scope();modal_scope.$apply()}}else self.preload_map[id]={reject:reject,resolve:resolve,do_apply:do_apply,data:data}}}})();(function(){angular.module('la.rotonda').directive('lrModal',LRModalComponent)
function LRModalComponent(LRModalService,$parse){return{controller:'@',controllerAs:'vm',name:'controllerName',templateUrl:'./html/modal.html',scope:{modalId:'@'},transclude:{title:'lrModalTitle',body:'lrModalFormBody',actions:'?lrModalActions'},compile:function(){return _link}}
function _link($scope,$element,$attrs,$controller,$transclude){$element.addClass('modal fade');$element.attr('role','dialog');_parseScreenAttributes($attrs,$element);_registryModal($scope,$element,$controller);_loadSections($scope,$element,$transclude);if($controller.$onInit){$controller.$onInit();if(LRModalService.preload_map[$scope.modalId]){var id=$scope.modalId,data=LRModalService.preload_map[$scope.modalId].data,resolve=LRModalService.preload_map[$scope.modalId].resolve,reject=LRModalService.preload_map[$scope.modalId].reject;LRModalService.open(id,data).then(resolve,reject)}}}
function _registryModal($scope,$element,$controller){$controller.modal=LRModalService.registry($scope.modalId,$element).registryHidden(function(){$controller.form.$setPristine()})}
function _loadSections($scope,$element,$transclude){angular.forEach(['title','body','actions'],function(section){var section_selector='[modal-'+section+']';$transclude($scope,_appendTo($element,section_selector),null,section)})}
function _appendTo($element,section_selector){return function(clone){return $element.find(section_selector).append(clone)}}
function _parseScreenAttributes($elementAttrs,$element){var attr_map={lrXs:'xs',lrSm:'sm',lrMd:'md',lrLg:'lg'},MAX=12,value,offset,containers=$element.find('[modal-container]');angular.forEach(attr_map,function(attr,index){if($elementAttrs[index]){value=$parse($elementAttrs[index])();offset=parseInt((MAX-value)/2);containers.addClass('col-'+attr+'-'+value);containers.addClass('col-'+attr+'-offset-'+offset)}})}}})();(function(){'use strict';angular.module('la.rotonda').controller('MainHeaderController',MainHeaderController)
function MainHeaderController($rootScope){var vm=this;vm.showLogin=showLogin
function showLogin(mode){$rootScope.$broadcast("open-login-view",mode);$('#login-modal').modal()}}})()
;
window.initMap=function(){google_map.loadMap()};_loadScript()
function _loadScript(){var api_url="https://maps.googleapis.com/maps/api/js",params="?key="+$map_data+"&callback=initMap&libraries=places,drawing,geometry",c=document.createElement('script'),h=document.getElementsByTagName('head')[0];c.async=true;c.type='text/javascript';c.charset='utf-8';c.src=api_url+params;h.appendChild(c)};window.google_map=(function(){var toDoOnLoad=[],internal_map=undefined,listeners=[];return{createMap:function(){google_map.loadMap();return(internal_map&&internal_map.createMap())},getMap:function(){return internal_map&&internal_map.getMap()},addControl:function(control){if(internal_map){return internal_map.addControl(control)}else toDoOnLoad.push({action:"add",data:control})},resetMap:function(){if(internal_map){return internal_map.resetMap()}else toDoOnLoad.push({action:"reset"})},setCenter:function(location){if(location&&internal_map)return internal_map.setCenter(location)},removeControl:function(id){if(internal_map){return internal_map.removeControl(id)}else toDoOnLoad.push({action:"remove",data:id})},loadMap:function(){if(window.google&&!internal_map){internal_map=LoadMap();if(internal_map){angular.forEach(toDoOnLoad,function(action){switch(action.action){case"add":internal_map.addControl(action.data);break;case"remove":internal_map.removeControl(action.data);break;case"reset":internal_map.resetMap()}});this.fire('map_loaded',this.getMap())}}},on:function(action,callback){if(!listeners[action])listeners[action]=[];listeners[action].push(callback);return function(){var index=listeners[action].indexOf(callback);if(index>=0)listeners[action].splice(index,1)}},fire:function(action,data){angular.forEach(angular.copy(listeners[action]),function(callback){callback(data)})},onLoad:function(callback){if(internal_map){callback(internal_map.getMap())}else var unreg=this.on('map_loaded',function(){callback.apply(null,arguments);unreg()})}}
function LoadMap(){var map=_createMap(),controls=[],map_zoom=12;if(map){return{getMap:getMap,createMap:function(){return map=_createMap()},addControl:addControl,removeControl:removeControl,resetMap:resetMap,setCenter:setCenter}}else return false
function getMap(){return map}
function addControl(control){var id=control.id||_getIdFromElto(control.elto);if(id){if(controls[id])removeControl(id);var control_el=control.elto||document.getElementById(id),position=google.maps.ControlPosition[control.position];map.controls[position].push(control_el);controls[control.id]=control};if(control.onSetUp&&angular.isFunction(control.onSetUp))control.onSetUp(map);google_map.fire('control_added',control)}
function _getIdFromElto(elto){if(elto){return $(elto).attr('id')}else return undefined}
function removeControl(id){var current_control=controls[id],elto=undefined;if(current_control){var pos=-1,position=google.maps.ControlPosition[current_control.position],elto=document.getElementById(id);map.controls[position].forEach(function(control,index){if(control===elto)pos=index});if(pos!==-1)map.controls[position].removeAt(pos);delete controls[id]};google_map.fire('control_removed',{control:current_control,elto:elto});return elto}
function _createMap(){var mapElement=document.getElementById('google_map');if(mapElement){var map=new google.maps.Map(mapElement,{center:{lat:-37.26941496733317,lng:-58.968465802392515},zoom:map_zoom,mapTypeId:google.maps.MapTypeId.HYBRID,disableDefaultUI:true,scrollwheel:false,draggable:true});map.addListener('click',function(event){var latLng=event.latLng;google_map.fire('map_click',{map:map,latLng:latLng})});return map}}
function setCenter(location){if(map)map.setCenter(location)}
function resetMap(){if(map){map.setOptions({disableDefaultUI:true,scrollwheel:false,draggable:true,zoom:map_zoom});google.maps.event.trigger(map,'resize')}}}})()
;
!function(t){var e={topSpacing:0,bottomSpacing:0,className:"is-sticky",wrapperClassName:"sticky-wrapper",center:!1,getWidthFrom:""},i=t(window),n=t(document),o=[],r=i.height(),s=function(){for(var e=i.scrollTop(),s=n.height(),a=s-r,c=e>a?a-e:0,p=0;p<o.length;p++){var l=o[p];if(e<=l.stickyWrapper.offset().top-l.topSpacing-c)null!==l.currentTop&&(l.stickyElement.css("position","").css("top",""),l.stickyElement.parent().removeClass(l.className),l.currentTop=null);else{var d=s-l.stickyElement.outerHeight()-l.topSpacing-l.bottomSpacing-e-c;d<0?d+=l.topSpacing:d=l.topSpacing,l.currentTop!=d&&(l.stickyElement.css("position","fixed").css("top",d),void 0!==l.getWidthFrom&&l.stickyElement.css("width",t(l.getWidthFrom).width()),l.stickyElement.parent().addClass(l.className),l.currentTop=d)}}},a=function(){r=i.height()},c={init:function(i){var n=t.extend(e,i);return this.each(function(){var e=t(this),i=e.attr("id"),r=t("<div></div>").attr("id",i+"-sticky-wrapper").addClass(n.wrapperClassName);e.wrapAll(r),n.center&&e.parent().css({width:e.outerWidth(),marginLeft:"auto",marginRight:"auto"}),"right"==e.css("float")&&e.css({float:"none"}).parent().css({float:"right"});var s=e.parent();s.css("height",e.outerHeight()),o.push({topSpacing:n.topSpacing,bottomSpacing:n.bottomSpacing,stickyElement:e,currentTop:null,stickyWrapper:s,className:n.className,getWidthFrom:n.getWidthFrom})})},update:s,unstick:function(e){return this.each(function(){var e=t(this);removeIdx=-1;for(var i=0;i<o.length;i++)o[i].stickyElement.get(0)==e.get(0)&&(removeIdx=i);-1!=removeIdx&&(o.splice(removeIdx,1),e.unwrap(),e.removeAttr("style"))})}};window.addEventListener?(window.addEventListener("scroll",s,!1),window.addEventListener("resize",a,!1)):window.attachEvent&&(window.attachEvent("onscroll",s),window.attachEvent("onresize",a)),t.fn.sticky=function(e){return c[e]?c[e].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof e&&e?void t.error("Method "+e+" does not exist on jQuery.sticky"):c.init.apply(this,arguments)},t.fn.unstick=function(e){return c[e]?c[e].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof e&&e?void t.error("Method "+e+" does not exist on jQuery.sticky"):c.unstick.apply(this,arguments)},t(function(){setTimeout(s,0)})}(jQuery);
;
jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInCubic:function(e,f,a,h,g){return h*(f/=g)*f*f+a},easeOutCubic:function(e,f,a,h,g){return h*((f=f/g-1)*f*f+1)+a},easeInOutCubic:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f+a}return h/2*((f-=2)*f*f+2)+a},easeInQuart:function(e,f,a,h,g){return h*(f/=g)*f*f*f+a},easeOutQuart:function(e,f,a,h,g){return -h*((f=f/g-1)*f*f*f-1)+a},easeInOutQuart:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f+a}return -h/2*((f-=2)*f*f*f-2)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInSine:function(e,f,a,h,g){return -h*Math.cos(f/g*(Math.PI/2))+h+a},easeOutSine:function(e,f,a,h,g){return h*Math.sin(f/g*(Math.PI/2))+a},easeInOutSine:function(e,f,a,h,g){return -h/2*(Math.cos(Math.PI*f/g)-1)+a},easeInExpo:function(e,f,a,h,g){return(f==0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f==0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInCirc:function(e,f,a,h,g){return -h*(Math.sqrt(1-(f/=g)*f)-1)+a},easeOutCirc:function(e,f,a,h,g){return h*Math.sqrt(1-(f=f/g-1)*f)+a},easeInOutCirc:function(e,f,a,h,g){if((f/=g/2)<1){return -h/2*(Math.sqrt(1-f*f)-1)+a}return h/2*(Math.sqrt(1-(f-=2)*f)+1)+a},easeInElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return -(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e},easeOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return g*Math.pow(2,-10*h)*Math.sin((h*k-i)*(2*Math.PI)/j)+l+e},easeInOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k/2)==2){return e+l}if(!j){j=k*(0.3*1.5)}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}if(h<1){return -0.5*(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e}return g*Math.pow(2,-10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j)*0.5+l+e},easeInBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*(f/=h)*f*((g+1)*f-g)+a},easeOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*((f=f/h-1)*f*((g+1)*f+g)+1)+a},easeInOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}if((f/=h/2)<1){return i/2*(f*f*(((g*=(1.525))+1)*f-g))+a}return i/2*((f-=2)*f*(((g*=(1.525))+1)*f+g)+2)+a},easeInBounce:function(e,f,a,h,g){return h-jQuery.easing.easeOutBounce(e,g-f,0,h,g)+a},easeOutBounce:function(e,f,a,h,g){if((f/=g)<(1/2.75)){return h*(7.5625*f*f)+a}else{if(f<(2/2.75)){return h*(7.5625*(f-=(1.5/2.75))*f+0.75)+a}else{if(f<(2.5/2.75)){return h*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return h*(7.5625*(f-=(2.625/2.75))*f+0.984375)+a}}}},easeInOutBounce:function(e,f,a,h,g){if(f<g/2){return jQuery.easing.easeInBounce(e,f*2,0,h,g)*0.5+a}return jQuery.easing.easeOutBounce(e,f*2-g,0,h,g)*0.5+h*0.5+a}});

;
;(function($){var h=$.scrollTo=function(a,b,c){$(window).scrollTo(a,b,c)};h.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1,limit:true};h.window=function(a){return $(window)._scrollable()};$.fn._scrollable=function(){return this.map(function(){var a=this,isWin=!a.nodeName||$.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!isWin)return a;var b=(a.contentWindow||a).document||a.ownerDocument||a;return/webkit/i.test(navigator.userAgent)||b.compatMode=='BackCompat'?b.body:b.documentElement})};$.fn.scrollTo=function(e,f,g){if(typeof f=='object'){g=f;f=0}if(typeof g=='function')g={onAfter:g};if(e=='max')e=9e9;g=$.extend({},h.defaults,g);f=f||g.duration;g.queue=g.queue&&g.axis.length>1;if(g.queue)f/=2;g.offset=both(g.offset);g.over=both(g.over);return this._scrollable().each(function(){if(!e)return;var d=this,$elem=$(d),targ=e,toff,attr={},win=$elem.is('html,body');switch(typeof targ){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ)){targ=both(targ);break}targ=$(targ,this);if(!targ.length)return;case'object':if(targ.is||targ.style)toff=(targ=$(targ)).offset()}$.each(g.axis.split(''),function(i,a){var b=a=='x'?'Left':'Top',pos=b.toLowerCase(),key='scroll'+b,old=d[key],max=h.max(d,a);if(toff){attr[key]=toff[pos]+(win?0:old-$elem.offset()[pos]);if(g.margin){attr[key]-=parseInt(targ.css('margin'+b))||0;attr[key]-=parseInt(targ.css('border'+b+'Width'))||0}attr[key]+=g.offset[pos]||0;if(g.over[pos])attr[key]+=targ[a=='x'?'width':'height']()*g.over[pos]}else{var c=targ[pos];attr[key]=c.slice&&c.slice(-1)=='%'?parseFloat(c)/100*max:c}if(g.limit&&/^\d+$/.test(attr[key]))attr[key]=attr[key]<=0?0:Math.min(attr[key],max);if(!i&&g.queue){if(old!=attr[key])animate(g.onAfterFirst);delete attr[key]}});animate(g.onAfter);function animate(a){$elem.animate(attr,f,g.easing,a&&function(){a.call(this,e,g)})}}).end()};h.max=function(a,b){var c=b=='x'?'Width':'Height',scroll='scroll'+c;if(!$(a).is('html,body'))return a[scroll]-$(a)[c.toLowerCase()]();var d='client'+c,html=a.ownerDocument.documentElement,body=a.ownerDocument.body;return Math.max(html[scroll],body[scroll])-Math.min(html[d],body[d])};function both(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
;
(function($){$(window).load(function(){$("#navigation").sticky({topSpacing:0});$('.navbar-nav li a').bind('click',function(event){var $anchor=$(this),nav=$($anchor.attr('href'));if(nav.length){$('html, body').stop().animate({scrollTop:$($anchor.attr('href')).offset().top},1500,'easeInOutExpo');event.preventDefault()}});$('a.totop,a#btn-scroll,a.btn-scroll,.carousel-inner .item a.btn').bind('click',function(event){var $anchor=$(this);$('html, body').stop().animate({scrollTop:$($anchor.attr('href')).offset().top},1500,'easeInOutExpo');event.preventDefault()})})})(jQuery)
;
(function(){var $,AbstractChosen,Chosen,SelectParser,_ref,__hasProp={}.hasOwnProperty,__extends=function(child,parent){for(var key in parent)if(__hasProp.call(parent,key))child[key]=parent[key]
function ctor(){this.constructor=child};ctor.prototype=parent.prototype;child.prototype=new ctor();child.__super__=parent.prototype;return child};SelectParser=(function(){function SelectParser(){this.options_index=0;this.parsed=[]};SelectParser.prototype.add_node=function(child){if(child.nodeName.toUpperCase()==="OPTGROUP"){return this.add_group(child)}else return this.add_option(child)};SelectParser.prototype.add_group=function(group){var group_position,option,_i,_len,_ref,_results;group_position=this.parsed.length;this.parsed.push({array_index:group_position,group:true,label:this.escapeExpression(group.label),title:group.title?group.title:void(0),children:0,disabled:group.disabled,classes:group.className});_ref=group.childNodes;_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];_results.push(this.add_option(option,group_position,group.disabled))};return _results};SelectParser.prototype.add_option=function(option,group_position,group_disabled){if(option.nodeName.toUpperCase()==="OPTION"){if(option.text!==""){if(group_position!=null)this.parsed[group_position].children+=1;this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:option.value,text:option.text,html:option.innerHTML,title:option.title?option.title:void(0),selected:option.selected,disabled:group_disabled===true?group_disabled:option.disabled,group_array_index:group_position,group_label:group_position!=null?this.parsed[group_position].label:null,classes:option.className,style:option.style.cssText})}else this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:true});return this.options_index+=1}};SelectParser.prototype.escapeExpression=function(text){var map,unsafe_chars;if((text==null)||text===false)return"";if(!/[\&\<\>\"\'\`]/.test(text))return text;map={"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"};unsafe_chars=/&(?!\w+;)|[\<\>\"\'\`]/g;return text.replace(unsafe_chars,function(chr){return map[chr]||"&amp;"})};return SelectParser})();SelectParser.select_to_array=function(select){var child,parser,_i,_len,_ref;parser=new SelectParser();_ref=select.childNodes;for(_i=0,_len=_ref.length;_i<_len;_i++){child=_ref[_i];parser.add_node(child)};return parser.parsed};AbstractChosen=(function(){function AbstractChosen(form_field,options){this.form_field=form_field;this.options=options!=null?options:{};if(!AbstractChosen.browser_is_supported())return;this.is_multiple=this.form_field.multiple;this.set_default_text();this.set_default_values();this.setup();this.set_up_html();this.register_observers();this.on_ready()};AbstractChosen.prototype.set_default_values=function(){var _this=this;this.click_test_action=function(evt){return _this.test_active_click(evt)};this.activate_action=function(evt){return _this.activate_field(evt)};this.active_field=false;this.mouse_on_container=false;this.results_showing=false;this.result_highlighted=null;this.allow_single_deselect=(this.options.allow_single_deselect!=null)&&(this.form_field.options[0]!=null)&&this.form_field.options[0].text===""?this.options.allow_single_deselect:false;this.disable_search_threshold=this.options.disable_search_threshold||0;this.disable_search=this.options.disable_search||false;this.enable_split_word_search=this.options.enable_split_word_search!=null?this.options.enable_split_word_search:true;this.group_search=this.options.group_search!=null?this.options.group_search:true;this.search_contains=this.options.search_contains||false;this.single_backstroke_delete=this.options.single_backstroke_delete!=null?this.options.single_backstroke_delete:true;this.max_selected_options=this.options.max_selected_options||Infinity;this.inherit_select_classes=this.options.inherit_select_classes||false;this.display_selected_options=this.options.display_selected_options!=null?this.options.display_selected_options:true;this.display_disabled_options=this.options.display_disabled_options!=null?this.options.display_disabled_options:true;this.include_group_label_in_selected=this.options.include_group_label_in_selected||false;this.max_shown_results=this.options.max_shown_results||Number.POSITIVE_INFINITY;return this.case_sensitive_search=this.options.case_sensitive_search||false};AbstractChosen.prototype.set_default_text=function(){if(this.form_field.getAttribute("data-placeholder")){this.default_text=this.form_field.getAttribute("data-placeholder")}else if(this.is_multiple){this.default_text=this.options.placeholder_text_multiple||this.options.placeholder_text||AbstractChosen.default_multiple_text}else this.default_text=this.options.placeholder_text_single||this.options.placeholder_text||AbstractChosen.default_single_text;return this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||AbstractChosen.default_no_result_text};AbstractChosen.prototype.choice_label=function(item){if(this.include_group_label_in_selected&&(item.group_label!=null)){return"<b class='group-name'>"+item.group_label+"</b>"+item.html}else return item.html};AbstractChosen.prototype.mouse_enter=function(){return this.mouse_on_container=true};AbstractChosen.prototype.mouse_leave=function(){return this.mouse_on_container=false};AbstractChosen.prototype.input_focus=function(evt){var _this=this;if(this.is_multiple){if(!this.active_field)return setTimeout((function(){return _this.container_mousedown()}),50)}else if(!this.active_field)return this.activate_field()};AbstractChosen.prototype.input_blur=function(evt){var _this=this;if(!this.mouse_on_container){this.active_field=false;return setTimeout((function(){return _this.blur_test()}),100)}};AbstractChosen.prototype.results_option_build=function(options){var content,data,data_content,shown_results,_i,_len,_ref;content='';shown_results=0;_ref=this.results_data;for(_i=0,_len=_ref.length;_i<_len;_i++){data=_ref[_i];data_content='';if(data.group){data_content=this.result_add_group(data)}else data_content=this.result_add_option(data);if(data_content!==''){shown_results++;content+=data_content};if(options!=null?options.first:void(0))if(data.selected&&this.is_multiple){this.choice_build(data)}else if(data.selected&&!this.is_multiple)this.single_set_selected_text(this.choice_label(data));if(shown_results>=this.max_shown_results)break};return content};AbstractChosen.prototype.result_add_option=function(option){var classes,option_el;if(!option.search_match)return'';if(!this.include_option_in_results(option))return'';classes=[];if(!option.disabled&&!(option.selected&&this.is_multiple))classes.push("active-result");if(option.disabled&&!(option.selected&&this.is_multiple))classes.push("disabled-result");if(option.selected)classes.push("result-selected");if(option.group_array_index!=null)classes.push("group-option");if(option.classes!=="")classes.push(option.classes);option_el=document.createElement("li");option_el.className=classes.join(" ");option_el.style.cssText=option.style;option_el.setAttribute("data-option-array-index",option.array_index);option_el.innerHTML=option.search_text;if(option.title)option_el.title=option.title;return this.outerHTML(option_el)};AbstractChosen.prototype.result_add_group=function(group){var classes,group_el;if(!(group.search_match||group.group_match))return'';if(!(group.active_options>0))return'';classes=[];classes.push("group-result");if(group.classes)classes.push(group.classes);group_el=document.createElement("li");group_el.className=classes.join(" ");group_el.innerHTML=group.search_text;if(group.title)group_el.title=group.title;return this.outerHTML(group_el)};AbstractChosen.prototype.results_update_field=function(){this.set_default_text();if(!this.is_multiple)this.results_reset_cleanup();this.result_clear_highlight();this.results_build();if(this.results_showing)return this.winnow_results()};AbstractChosen.prototype.reset_single_select_options=function(){var result,_i,_len,_ref,_results;_ref=this.results_data;_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){result=_ref[_i];if(result.selected){_results.push(result.selected=false)}else _results.push(void(0))};return _results};AbstractChosen.prototype.results_toggle=function(){if(this.results_showing){return this.results_hide()}else return this.results_show()};AbstractChosen.prototype.results_search=function(evt){if(this.results_showing){return this.winnow_results()}else return this.results_show()};AbstractChosen.prototype.winnow_results=function(){var escapedSearchText,option,regex,results,results_group,searchText,startpos,text,zregex,_i,_len,_ref;this.no_results_clear();results=0;searchText=this.get_search_text();escapedSearchText=searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");zregex=new RegExp(escapedSearchText,'i');regex=this.get_search_regex(escapedSearchText);_ref=this.results_data;for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];option.search_match=false;results_group=null;if(this.include_option_in_results(option)){if(option.group){option.group_match=false;option.active_options=0};if((option.group_array_index!=null)&&this.results_data[option.group_array_index]){results_group=this.results_data[option.group_array_index];if(results_group.active_options===0&&results_group.search_match)results+=1;results_group.active_options+=1};option.search_text=option.group?option.label:option.html;if(!(option.group&&!this.group_search)){option.search_match=this.search_string_match(option.search_text,regex);if(option.search_match&&!option.group)results+=1;if(option.search_match){if(searchText.length){startpos=option.search_text.search(zregex);text=option.search_text.substr(0,startpos+searchText.length)+'</em>'+option.search_text.substr(startpos+searchText.length);option.search_text=text.substr(0,startpos)+'<em>'+text.substr(startpos)};if(results_group!=null)results_group.group_match=true}else if((option.group_array_index!=null)&&this.results_data[option.group_array_index].search_match)option.search_match=true}}};this.result_clear_highlight();if(results<1&&searchText.length){this.update_results_content("");return this.no_results(searchText)}else{this.update_results_content(this.results_option_build());return this.winnow_results_set_highlight()}};AbstractChosen.prototype.get_search_regex=function(escaped_search_string){var regex_anchor,regex_flag;regex_anchor=this.search_contains?"":"^";regex_flag=this.case_sensitive_search?"":"i";return new RegExp(regex_anchor+escaped_search_string,regex_flag)};AbstractChosen.prototype.search_string_match=function(search_string,regex){var part,parts,_i,_len;if(regex.test(search_string)){return true}else if(this.enable_split_word_search&&(search_string.indexOf(" ")>=0||search_string.indexOf("[")===0)){parts=search_string.replace(/\[|\]/g,"").split(" ");if(parts.length)for(_i=0,_len=parts.length;_i<_len;_i++){part=parts[_i];if(regex.test(part))return true}}};AbstractChosen.prototype.choices_count=function(){var option,_i,_len,_ref;if(this.selected_option_count!=null)return this.selected_option_count;this.selected_option_count=0;_ref=this.form_field.options;for(_i=0,_len=_ref.length;_i<_len;_i++){option=_ref[_i];if(option.selected)this.selected_option_count+=1};return this.selected_option_count};AbstractChosen.prototype.choices_click=function(evt){evt.preventDefault();if(!(this.results_showing||this.is_disabled))return this.results_show()};AbstractChosen.prototype.keyup_checker=function(evt){var stroke,_ref;stroke=(_ref=evt.which)!=null?_ref:evt.keyCode;this.search_field_scale();switch(stroke){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0){return this.keydown_backstroke()}else if(!this.pending_backstroke){this.result_clear_highlight();return this.results_search()};break;case 13:evt.preventDefault();if(this.results_showing)return this.result_select(evt);break;case 27:if(this.results_showing)this.results_hide();return true;case 9:case 38:case 40:case 16:case 91:case 17:case 18:break;default:return this.results_search()}};AbstractChosen.prototype.clipboard_event_checker=function(evt){var _this=this;return setTimeout((function(){return _this.results_search()}),50)};AbstractChosen.prototype.container_width=function(){if(this.options.width!=null){return this.options.width}else return""+this.form_field.offsetWidth+"px"};AbstractChosen.prototype.include_option_in_results=function(option){if(this.is_multiple&&(!this.display_selected_options&&option.selected))return false;if(!this.display_disabled_options&&option.disabled)return false;if(option.empty)return false;return true};AbstractChosen.prototype.search_results_touchstart=function(evt){this.touch_started=true;return this.search_results_mouseover(evt)};AbstractChosen.prototype.search_results_touchmove=function(evt){this.touch_started=false;return this.search_results_mouseout(evt)};AbstractChosen.prototype.search_results_touchend=function(evt){if(this.touch_started)return this.search_results_mouseup(evt)};AbstractChosen.prototype.outerHTML=function(element){var tmp;if(element.outerHTML)return element.outerHTML;tmp=document.createElement("div");tmp.appendChild(element);return tmp.innerHTML};AbstractChosen.browser_is_supported=function(){if("Microsoft Internet Explorer"===window.navigator.appName)return document.documentMode>=8;return true};AbstractChosen.default_multiple_text="Select Some Options";AbstractChosen.default_single_text="Select an Option";AbstractChosen.default_no_result_text="No results match";return AbstractChosen})();$=jQuery;$.fn.extend({chosen:function(options){if(!AbstractChosen.browser_is_supported())return this;return this.each(function(input_field){var $this,chosen;$this=$(this);chosen=$this.data('chosen');if(options==='destroy'){if(chosen instanceof Chosen)chosen.destroy();return};if(!(chosen instanceof Chosen))$this.data('chosen',new Chosen(this,options))})}});Chosen=(function(_super){__extends(Chosen,_super)
function Chosen(){_ref=Chosen.__super__.constructor.apply(this,arguments);return _ref};Chosen.prototype.setup=function(){this.form_field_jq=$(this.form_field);this.current_selectedIndex=this.form_field.selectedIndex;return this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")};Chosen.prototype.set_up_html=function(){var container_classes,container_props;container_classes=["chosen-container"];container_classes.push("chosen-container-"+(this.is_multiple?"multi":"single"));if(this.inherit_select_classes&&this.form_field.className)container_classes.push(this.form_field.className);if(this.is_rtl)container_classes.push("chosen-rtl");container_props={'class':container_classes.join(' '),style:"width: "+(this.container_width())+";",title:this.form_field.title};if(this.form_field.id.length)container_props.id=this.form_field.id.replace(/[^\w]/g,'_')+"_chosen";this.container=$("<div />",container_props);if(this.is_multiple){this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>')}else this.container.html('<a class="chosen-single chosen-default"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>');this.form_field_jq.hide().after(this.container);this.dropdown=this.container.find('div.chosen-drop').first();this.search_field=this.container.find('input').first();this.search_results=this.container.find('ul.chosen-results').first();this.search_field_scale();this.search_no_results=this.container.find('li.no-results').first();if(this.is_multiple){this.search_choices=this.container.find('ul.chosen-choices').first();this.search_container=this.container.find('li.search-field').first()}else{this.search_container=this.container.find('div.chosen-search').first();this.selected_item=this.container.find('.chosen-single').first()};this.results_build();this.set_tab_index();return this.set_label_behavior()};Chosen.prototype.on_ready=function(){return this.form_field_jq.trigger("chosen:ready",{chosen:this})};Chosen.prototype.register_observers=function(){var _this=this;this.container.bind('touchstart.chosen',function(evt){_this.container_mousedown(evt);return evt.preventDefault()});this.container.bind('touchend.chosen',function(evt){_this.container_mouseup(evt);return evt.preventDefault()});this.container.bind('mousedown.chosen',function(evt){_this.container_mousedown(evt)});this.container.bind('mouseup.chosen',function(evt){_this.container_mouseup(evt)});this.container.bind('mouseenter.chosen',function(evt){_this.mouse_enter(evt)});this.container.bind('mouseleave.chosen',function(evt){_this.mouse_leave(evt)});this.search_results.bind('mouseup.chosen',function(evt){_this.search_results_mouseup(evt)});this.search_results.bind('mouseover.chosen',function(evt){_this.search_results_mouseover(evt)});this.search_results.bind('mouseout.chosen',function(evt){_this.search_results_mouseout(evt)});this.search_results.bind('mousewheel.chosen DOMMouseScroll.chosen',function(evt){_this.search_results_mousewheel(evt)});this.search_results.bind('touchstart.chosen',function(evt){_this.search_results_touchstart(evt)});this.search_results.bind('touchmove.chosen',function(evt){_this.search_results_touchmove(evt)});this.search_results.bind('touchend.chosen',function(evt){_this.search_results_touchend(evt)});this.form_field_jq.bind("chosen:updated.chosen",function(evt){_this.results_update_field(evt)});this.form_field_jq.bind("chosen:activate.chosen",function(evt){_this.activate_field(evt)});this.form_field_jq.bind("chosen:open.chosen",function(evt){_this.container_mousedown(evt)});this.form_field_jq.bind("chosen:close.chosen",function(evt){_this.input_blur(evt)});this.search_field.bind('blur.chosen',function(evt){_this.input_blur(evt)});this.search_field.bind('keyup.chosen',function(evt){_this.keyup_checker(evt)});this.search_field.bind('keydown.chosen',function(evt){_this.keydown_checker(evt)});this.search_field.bind('focus.chosen',function(evt){_this.input_focus(evt)});this.search_field.bind('cut.chosen',function(evt){_this.clipboard_event_checker(evt)});this.search_field.bind('paste.chosen',function(evt){_this.clipboard_event_checker(evt)});if(this.is_multiple){return this.search_choices.bind('click.chosen',function(evt){_this.choices_click(evt)})}else return this.container.bind('click.chosen',function(evt){evt.preventDefault()})};Chosen.prototype.destroy=function(){$(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action);$(this.container[0].ownerDocument).unbind("touchstart",function(){});if(this.search_field[0].tabIndex)this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex;this.container.remove();this.form_field_jq.removeData('chosen');return this.form_field_jq.show()};Chosen.prototype.search_field_disabled=function(){this.is_disabled=this.form_field_jq[0].disabled;if(this.is_disabled){this.container.addClass('chosen-disabled');this.search_field[0].disabled=true;if(!this.is_multiple)this.selected_item.unbind("focus.chosen",this.activate_action);return this.close_field()}else{this.container.removeClass('chosen-disabled');this.search_field[0].disabled=false;if(!this.is_multiple)return this.selected_item.bind("focus.chosen",this.activate_action)}};Chosen.prototype.container_mousedown=function(evt){if(!this.is_disabled){if(evt&&evt.type==="mousedown"&&!this.results_showing)evt.preventDefault();if(!((evt!=null)&&($(evt.target)).hasClass("search-choice-close"))){if(!this.active_field){if(this.is_multiple)this.search_field.val("");$(this.container[0].ownerDocument).bind('click.chosen',this.click_test_action);$(this.container[0].ownerDocument).bind('touchstart',this.click_test_action);this.results_show()}else if(!this.is_multiple&&evt&&(($(evt.target)[0]===this.selected_item[0])||$(evt.target).parents("a.chosen-single").length)){evt.preventDefault();this.results_toggle()};return this.activate_field()}}};Chosen.prototype.container_mouseup=function(evt){if(evt.target.nodeName==="ABBR"&&!this.is_disabled)return this.results_reset(evt)};Chosen.prototype.search_results_mousewheel=function(evt){var delta;if(evt.originalEvent)delta=evt.originalEvent.deltaY||-evt.originalEvent.wheelDelta||evt.originalEvent.detail;if(delta!=null){evt.preventDefault();if(evt.type==='DOMMouseScroll')delta=delta*40;return this.search_results.scrollTop(delta+this.search_results.scrollTop())}};Chosen.prototype.blur_test=function(evt){if(!this.active_field&&this.container.hasClass("chosen-container-active"))return this.close_field()};Chosen.prototype.close_field=function(){$(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action);$(this.container[0].ownerDocument).unbind("touchstart",this.click_test_action);this.active_field=false;this.results_hide();this.container.removeClass("chosen-container-active");this.clear_backstroke();this.show_search_field_default();return this.search_field_scale()};Chosen.prototype.activate_field=function(){this.container.addClass("chosen-container-active");this.active_field=true;this.search_field.val(this.search_field.val());return this.search_field.focus()};Chosen.prototype.test_active_click=function(evt){var active_container;active_container=$(evt.target).closest('.chosen-container');if(active_container.length&&this.container[0]===active_container[0]){return this.active_field=true}else return this.close_field()};Chosen.prototype.results_build=function(){this.parsing=true;this.selected_option_count=null;this.results_data=SelectParser.select_to_array(this.form_field);if(this.is_multiple){this.search_choices.find("li.search-choice").remove()}else if(!this.is_multiple){this.single_set_selected_text();if(this.disable_search||this.form_field.options.length<=this.disable_search_threshold){this.search_field[0].readOnly=true;this.container.addClass("chosen-container-single-nosearch")}else{this.search_field[0].readOnly=false;this.container.removeClass("chosen-container-single-nosearch")}};this.update_results_content(this.results_option_build({first:true}));this.search_field_disabled();this.show_search_field_default();this.search_field_scale();return this.parsing=false};Chosen.prototype.result_do_highlight=function(el){var high_bottom,high_top,maxHeight,visible_bottom,visible_top;if(el.length){this.result_clear_highlight();this.result_highlight=el;this.result_highlight.addClass("highlighted");maxHeight=parseInt(this.search_results.css("maxHeight"),10);visible_top=this.search_results.scrollTop();visible_bottom=maxHeight+visible_top;high_top=this.result_highlight.position().top+this.search_results.scrollTop();high_bottom=high_top+this.result_highlight.outerHeight();if(high_bottom>=visible_bottom){return this.search_results.scrollTop((high_bottom-maxHeight)>0?high_bottom-maxHeight:0)}else if(high_top<visible_top)return this.search_results.scrollTop(high_top)}};Chosen.prototype.result_clear_highlight=function(){if(this.result_highlight)this.result_highlight.removeClass("highlighted");return this.result_highlight=null};Chosen.prototype.results_show=function(){if(this.is_multiple&&this.max_selected_options<=this.choices_count()){this.form_field_jq.trigger("chosen:maxselected",{chosen:this});return false};this.container.addClass("chosen-with-drop");this.results_showing=true;this.search_field.focus();this.search_field.val(this.search_field.val());this.winnow_results();return this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this})};Chosen.prototype.update_results_content=function(content){return this.search_results.html(content)};Chosen.prototype.results_hide=function(){if(this.results_showing){this.result_clear_highlight();this.container.removeClass("chosen-with-drop");this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})};return this.results_showing=false};Chosen.prototype.set_tab_index=function(el){var ti;if(this.form_field.tabIndex){ti=this.form_field.tabIndex;this.form_field.tabIndex=-1;return this.search_field[0].tabIndex=ti}};Chosen.prototype.set_label_behavior=function(){var _this=this;this.form_field_label=this.form_field_jq.parents("label");if(!this.form_field_label.length&&this.form_field.id.length)this.form_field_label=$("label[for='"+this.form_field.id+"']");if(this.form_field_label.length>0)return this.form_field_label.bind('click.chosen',function(evt){if(_this.is_multiple){return _this.container_mousedown(evt)}else return _this.activate_field()}).bind('touchstart',function(evt){if(_this.is_multiple){return _this.container_mousedown(evt)}else return _this.activate_field()})};Chosen.prototype.show_search_field_default=function(){if(this.is_multiple&&this.choices_count()<1&&!this.active_field){this.search_field.val(this.default_text);return this.search_field.addClass("default")}else{this.search_field.val("");return this.search_field.removeClass("default")}};Chosen.prototype.search_results_mouseup=function(evt){var target;target=$(evt.target).hasClass("active-result")?$(evt.target):$(evt.target).parents(".active-result").first();if(target.length){this.result_highlight=target;this.result_select(evt);return this.search_field.focus()}};Chosen.prototype.search_results_mouseover=function(evt){var target;target=$(evt.target).hasClass("active-result")?$(evt.target):$(evt.target).parents(".active-result").first();if(target)return this.result_do_highlight(target)};Chosen.prototype.search_results_mouseout=function(evt){if($(evt.target).hasClass("active-result"||$(evt.target).parents('.active-result').first()))return this.result_clear_highlight()};Chosen.prototype.choice_build=function(item){var choice,close_link,_this=this;choice=$('<li />',{"class":"search-choice"}).html("<span>"+(this.choice_label(item))+"</span>");if(item.disabled){choice.addClass('search-choice-disabled')}else{close_link=$('<a />',{"class":'search-choice-close','data-option-array-index':item.array_index});close_link.bind('click.chosen',function(evt){return _this.choice_destroy_link_click(evt)});close_link.bind('touchstart',function(evt){return _this.choice_destroy_link_click(evt)});choice.append(close_link)};return this.search_container.before(choice)};Chosen.prototype.choice_destroy_link_click=function(evt){evt.preventDefault();evt.stopPropagation();if(!this.is_disabled)return this.choice_destroy($(evt.target))};Chosen.prototype.choice_destroy=function(link){if(this.result_deselect(link[0].getAttribute("data-option-array-index"))){this.show_search_field_default();if(this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1)this.results_hide();link.parents('li').first().remove();return this.search_field_scale()}};Chosen.prototype.results_reset=function(){this.reset_single_select_options();this.form_field.options[0].selected=true;this.single_set_selected_text();this.show_search_field_default();this.results_reset_cleanup();this.form_field_jq.trigger("change");if(this.active_field)return this.results_hide()};Chosen.prototype.results_reset_cleanup=function(){this.current_selectedIndex=this.form_field.selectedIndex;return this.selected_item.find("abbr").remove()};Chosen.prototype.result_select=function(evt){var high,item;if(this.result_highlight){high=this.result_highlight;this.result_clear_highlight();if(this.is_multiple&&this.max_selected_options<=this.choices_count()){this.form_field_jq.trigger("chosen:maxselected",{chosen:this});return false};if(this.is_multiple){high.removeClass("active-result")}else this.reset_single_select_options();high.addClass("result-selected");item=this.results_data[high[0].getAttribute("data-option-array-index")];item.selected=true;this.form_field.options[item.options_index].selected=true;this.selected_option_count=null;if(this.is_multiple){this.choice_build(item)}else this.single_set_selected_text(this.choice_label(item));if(!((evt.metaKey||evt.ctrlKey)&&this.is_multiple))this.results_hide();this.show_search_field_default();if(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)this.form_field_jq.trigger("change",{selected:this.form_field.options[item.options_index].value});this.current_selectedIndex=this.form_field.selectedIndex;evt.preventDefault();return this.search_field_scale()}};Chosen.prototype.single_set_selected_text=function(text){if(text==null)text=this.default_text;if(text===this.default_text){this.selected_item.addClass("chosen-default")}else{this.single_deselect_control_build();this.selected_item.removeClass("chosen-default")};return this.selected_item.find("span").html(text)};Chosen.prototype.result_deselect=function(pos){var result_data;result_data=this.results_data[pos];if(!this.form_field.options[result_data.options_index].disabled){result_data.selected=false;this.form_field.options[result_data.options_index].selected=false;this.selected_option_count=null;this.result_clear_highlight();if(this.results_showing)this.winnow_results();this.form_field_jq.trigger("change",{deselected:this.form_field.options[result_data.options_index].value});this.search_field_scale();return true}else return false};Chosen.prototype.single_deselect_control_build=function(){if(!this.allow_single_deselect)return;if(!this.selected_item.find("abbr").length)this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");return this.selected_item.addClass("chosen-single-with-deselect")};Chosen.prototype.get_search_text=function(){return $('<div/>').text($.trim(this.search_field.val())).html()};Chosen.prototype.winnow_results_set_highlight=function(){var do_high,selected_results;selected_results=!this.is_multiple?this.search_results.find(".result-selected.active-result"):[];do_high=selected_results.length?selected_results.first():this.search_results.find(".active-result").first();if(do_high!=null)return this.result_do_highlight(do_high)};Chosen.prototype.no_results=function(terms){var no_results_html;no_results_html=$('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>');no_results_html.find("span").first().html(terms);this.search_results.append(no_results_html);return this.form_field_jq.trigger("chosen:no_results",{chosen:this})};Chosen.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()};Chosen.prototype.keydown_arrow=function(){var next_sib;if(this.results_showing&&this.result_highlight){next_sib=this.result_highlight.nextAll("li.active-result").first();if(next_sib)return this.result_do_highlight(next_sib)}else return this.results_show()};Chosen.prototype.keyup_arrow=function(){var prev_sibs;if(!this.results_showing&&!this.is_multiple){return this.results_show()}else if(this.result_highlight){prev_sibs=this.result_highlight.prevAll("li.active-result");if(prev_sibs.length){return this.result_do_highlight(prev_sibs.first())}else{if(this.choices_count()>0)this.results_hide();return this.result_clear_highlight()}}};Chosen.prototype.keydown_backstroke=function(){var next_available_destroy;if(this.pending_backstroke){this.choice_destroy(this.pending_backstroke.find("a").first());return this.clear_backstroke()}else{next_available_destroy=this.search_container.siblings("li.search-choice").last();if(next_available_destroy.length&&!next_available_destroy.hasClass("search-choice-disabled")){this.pending_backstroke=next_available_destroy;if(this.single_backstroke_delete){return this.keydown_backstroke()}else return this.pending_backstroke.addClass("search-choice-focus")}}};Chosen.prototype.clear_backstroke=function(){if(this.pending_backstroke)this.pending_backstroke.removeClass("search-choice-focus");return this.pending_backstroke=null};Chosen.prototype.keydown_checker=function(evt){var stroke,_ref1;stroke=(_ref1=evt.which)!=null?_ref1:evt.keyCode;this.search_field_scale();if(stroke!==8&&this.pending_backstroke)this.clear_backstroke();switch(stroke){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:if(this.results_showing&&!this.is_multiple)this.result_select(evt);this.mouse_on_container=false;break;case 13:if(this.results_showing)evt.preventDefault();break;case 32:if(this.disable_search)evt.preventDefault();break;case 38:evt.preventDefault();this.keyup_arrow();break;case 40:evt.preventDefault();this.keydown_arrow();break}};Chosen.prototype.search_field_scale=function(){var div,f_width,h,style,style_block,styles,w,_i,_len;if(this.is_multiple){h=0;w=0;style_block="position:absolute; left: -1000px; top: -1000px; display:none;";styles=['font-size','font-style','font-weight','font-family','line-height','text-transform','letter-spacing'];for(_i=0,_len=styles.length;_i<_len;_i++){style=styles[_i];style_block+=style+":"+this.search_field.css(style)+";"};div=$('<div />',{style:style_block});div.text(this.search_field.val());$('body').append(div);w=div.width()+25;div.remove();f_width=this.container.outerWidth();if(w>f_width-10)w=f_width-10;return this.search_field.css({width:w+'px'})}};return Chosen})(AbstractChosen)}).call(this)
;
(function(){var indexOf=[].indexOf||function(item){for(var i=0,l=this.length;i<l;i++)if(i in this&&this[i]===item)return i;return-1};angular.module('localytics.directives',[]);angular.module('localytics.directives').directive('chosen',['$timeout',function($timeout){var CHOSEN_OPTION_WHITELIST,NG_OPTIONS_REGEXP,isEmpty,snakeCase;NG_OPTIONS_REGEXP=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;CHOSEN_OPTION_WHITELIST=['persistentCreateOption','createOptionText','createOption','skipNoResults','noResultsText','allowSingleDeselect','disableSearchThreshold','disableSearch','enableSplitWordSearch','inheritSelectClasses','maxSelectedOptions','placeholderTextMultiple','placeholderTextSingle','searchContains','singleBackstrokeDelete','displayDisabledOptions','displaySelectedOptions','width','includeGroupLabelInSelected','maxShownResults'];snakeCase=function(input){return input.replace(/[A-Z]/g,function($1){return"_"+($1.toLowerCase())})};isEmpty=function(value){var key;if(angular.isArray(value)){return value.length===0}else if(angular.isObject(value))for(key in value)if(value.hasOwnProperty(key))return false;return true};return{restrict:'A',require:'?ngModel',priority:1,link:function(scope,element,attr,ngModel){var chosen,empty,initOrUpdate,match,options,origRender,startLoading,stopLoading,updateMessage,valuesExpr,viewWatch;scope.disabledValuesHistory=scope.disabledValuesHistory?scope.disabledValuesHistory:[];element=$(element);element.addClass('localytics-chosen');options=scope.$eval(attr.chosen)||{};angular.forEach(attr,function(value,key){if(indexOf.call(CHOSEN_OPTION_WHITELIST,key)>=0)return attr.$observe(key,function(value){var prefix;prefix=String(element.attr(attr.$attr[key])).slice(0,2);options[snakeCase(key)]=prefix==='{{'?value:scope.$eval(value);return updateMessage()})});startLoading=function(){return element.addClass('loading').attr('disabled',true).trigger('chosen:updated')};stopLoading=function(){element.removeClass('loading');if(angular.isDefined(attr.disabled)){element.attr('disabled',attr.disabled)}else element.attr('disabled',false);return element.trigger('chosen:updated')};chosen=null;empty=false;initOrUpdate=function(){var defaultText,dropListDom;if(chosen){dropListDom=$(element.parent()).find("div.chosen-drop");if(dropListDom&&dropListDom.length>0&&dropListDom.css("left").indexOf("0")>=0);return element.trigger('chosen:updated')}else{scope.$evalAsync(function(){chosen=element.chosen(options).data('chosen');$(element).attr('style','display:visible; position:absolute; clip:rect(0,0,0,0)')});if(angular.isObject(chosen))return defaultText=chosen.default_text}};updateMessage=function(){if(chosen&&empty){element.attr('data-placeholder',chosen.results_none_found).attr('disabled',true)}else element.removeAttr('data-placeholder');return element.trigger('chosen:updated')};if(ngModel){origRender=ngModel.$render;ngModel.$render=function(){origRender();return initOrUpdate()};element.on('chosen:hiding_dropdown',function(){return scope.$apply(function(){return ngModel.$setTouched()})});if(attr.multiple){viewWatch=function(){return ngModel.$viewValue};scope.$watch(viewWatch,function(){ngModel.$render()},true)}}else initOrUpdate();attr.$observe('disabled',function(){return element.trigger('chosen:updated')});if(attr.ngOptions&&ngModel){match=attr.ngOptions.match(NG_OPTIONS_REGEXP);valuesExpr=match[7];var timer;scope.$watchCollection(valuesExpr,function(newVal,oldVal){return timer=$timeout(function(){if(angular.isUndefined(newVal)){return startLoading()}else{empty=isEmpty(newVal);stopLoading();return updateMessage()}})});return scope.$on('$destroy',function(event){if(typeof timer!=="undefined"&&timer!==null)return $timeout.cancel(timer)})}}}}])}).call(this)
;
(function(window,undefined){"use strict";var History=window.History=window.History||{},jQuery=window.jQuery;if(typeof History.Adapter!=='undefined')throw new Error('History.js Adapter has already been loaded...');History.Adapter={bind:function(el,event,callback){jQuery(el).bind(event,callback)},trigger:function(el,event,extra){jQuery(el).trigger(event,extra)},extractEventData:function(key,event,extra){var result=(event&&event.originalEvent&&event.originalEvent[key])||(extra&&extra[key])||undefined;return result},onDomLoad:function(callback){jQuery(callback)}};if(typeof History.init!=='undefined')History.init()})(window)
;
(function(window,undefined){"use strict";var console=window.console||undefined,document=window.document,navigator=window.navigator,sessionStorage=false,setTimeout=window.setTimeout,clearTimeout=window.clearTimeout,setInterval=window.setInterval,clearInterval=window.clearInterval,JSON=window.JSON,alert=window.alert,History=window.History=window.History||{},history=window.history;try{sessionStorage=window.sessionStorage;sessionStorage.setItem('TEST','1');sessionStorage.removeItem('TEST')}catch(e){sessionStorage=false};JSON.stringify=JSON.stringify||JSON.encode;JSON.parse=JSON.parse||JSON.decode;if(typeof History.init!=='undefined')throw new Error('History.js Core has already been loaded...');History.init=function(options){if(typeof History.Adapter==='undefined')return false;if(typeof History.initCore!=='undefined')History.initCore();if(typeof History.initHtml4!=='undefined')History.initHtml4();return true};History.initCore=function(options){if(typeof History.initCore.initialized!=='undefined'){return false}else History.initCore.initialized=true;History.options=History.options||{};History.options.hashChangeInterval=History.options.hashChangeInterval||100;History.options.safariPollInterval=History.options.safariPollInterval||500;History.options.doubleCheckInterval=History.options.doubleCheckInterval||500;History.options.disableSuid=History.options.disableSuid||false;History.options.storeInterval=History.options.storeInterval||1e3;History.options.busyDelay=History.options.busyDelay||250;History.options.debug=History.options.debug||false;History.options.initialTitle=History.options.initialTitle||document.title;History.options.html4Mode=History.options.html4Mode||false;History.options.delayInit=History.options.delayInit||false;History.intervalList=[];History.clearAllIntervals=function(){var i,il=History.intervalList;if(typeof il!=="undefined"&&il!==null){for(i=0;i<il.length;i++)clearInterval(il[i]);History.intervalList=null}};History.debug=function(){if((History.options.debug||false))History.log.apply(History,arguments)};History.log=function(){var consoleExists=!(typeof console==='undefined'||typeof console.log==='undefined'||typeof console.log.apply==='undefined'),textarea=document.getElementById('log'),message,i,n,args,arg;if(consoleExists){args=Array.prototype.slice.call(arguments);message=args.shift();if(typeof console.debug!=='undefined'){console.debug.apply(console,[message,args])}else console.log.apply(console,[message,args])}else message=("\n"+arguments[0]+"\n");for(i=1,n=arguments.length;i<n;++i){arg=arguments[i];if(typeof arg==='object'&&typeof JSON!=='undefined')try{arg=JSON.stringify(arg)}catch(Exception){};message+="\n"+arg+"\n"};if(textarea){textarea.value+=message+"\n-----\n";textarea.scrollTop=textarea.scrollHeight-textarea.clientHeight}else if(!consoleExists)alert(message);return true};History.getInternetExplorerMajorVersion=function(){var result=History.getInternetExplorerMajorVersion.cached=(typeof History.getInternetExplorerMajorVersion.cached!=='undefined')?History.getInternetExplorerMajorVersion.cached:(function(){var v=3,div=document.createElement('div'),all=div.getElementsByTagName('i');while((div.innerHTML='<!--[if gt IE '+(++v)+']><i></i><![endif]-->')&&all[0]);return(v>4)?v:false})();return result};History.isInternetExplorer=function(){var result=History.isInternetExplorer.cached=(typeof History.isInternetExplorer.cached!=='undefined')?History.isInternetExplorer.cached:Boolean(History.getInternetExplorerMajorVersion());return result};if(History.options.html4Mode){History.emulated={pushState:true,hashChange:true}}else History.emulated={pushState:!Boolean(window.history&&window.history.pushState&&window.history.replaceState&&!(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(navigator.userAgent)||/AppleWebKit\/5([0-2]|3[0-2])/i.test(navigator.userAgent))),hashChange:Boolean(!(('onhashchange'in window)||('onhashchange'in document))||(History.isInternetExplorer()&&History.getInternetExplorerMajorVersion()<8))};History.enabled=!History.emulated.pushState;History.bugs={setHash:Boolean(!History.emulated.pushState&&navigator.vendor==='Apple Computer, Inc.'&&/AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),safariPoll:Boolean(!History.emulated.pushState&&navigator.vendor==='Apple Computer, Inc.'&&/AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),ieDoubleCheck:Boolean(History.isInternetExplorer()&&History.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(History.isInternetExplorer()&&History.getInternetExplorerMajorVersion()<7)};History.isEmptyObject=function(obj){for(var name in obj)if(obj.hasOwnProperty(name))return false;return true};History.cloneObject=function(obj){var hash,newObj;if(obj){hash=JSON.stringify(obj);newObj=JSON.parse(hash)}else newObj={};return newObj};History.getRootUrl=function(){var rootUrl=document.location.protocol+'//'+(document.location.hostname||document.location.host);if(document.location.port||false)rootUrl+=':'+document.location.port;rootUrl+='/';return rootUrl};History.getBaseHref=function(){var baseElements=document.getElementsByTagName('base'),baseElement=null,baseHref='';if(baseElements.length===1){baseElement=baseElements[0];baseHref=baseElement.href.replace(/[^\/]+$/,'')};baseHref=baseHref.replace(/\/+$/,'');if(baseHref)baseHref+='/';return baseHref};History.getBaseUrl=function(){var baseUrl=History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();return baseUrl};History.getPageUrl=function(){var State=History.getState(false,false),stateUrl=(State||{}).url||History.getLocationHref(),pageUrl;pageUrl=stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){return/\./.test(part)?part:part+'/'});return pageUrl};History.getBasePageUrl=function(){var basePageUrl=(History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){return/[^\/]$/.test(part)?'':part}).replace(/\/+$/,'')+'/';return basePageUrl};History.getFullUrl=function(url,allowBaseHref){var fullUrl=url,firstChar=url.substring(0,1);allowBaseHref=(typeof allowBaseHref==='undefined')?true:allowBaseHref;if(/[a-z]+\:\/\//.test(url));else if(firstChar==='/'){fullUrl=History.getRootUrl()+url.replace(/^\/+/,'')}else if(firstChar==='#'){fullUrl=History.getPageUrl().replace(/#.*/,'')+url}else if(firstChar==='?'){fullUrl=History.getPageUrl().replace(/[\?#].*/,'')+url}else if(allowBaseHref){fullUrl=History.getBaseUrl()+url.replace(/^(\.\/)+/,'')}else fullUrl=History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');return fullUrl.replace(/\#$/,'')};History.getShortUrl=function(url){var shortUrl=url,baseUrl=History.getBaseUrl(),rootUrl=History.getRootUrl();if(History.emulated.pushState)shortUrl=shortUrl.replace(baseUrl,'');shortUrl=shortUrl.replace(rootUrl,'/');if(History.isTraditionalAnchor(shortUrl))shortUrl='./'+shortUrl;shortUrl=shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');return shortUrl};History.getLocationHref=function(doc){doc=doc||document;if(doc.URL===doc.location.href)return doc.location.href;if(doc.location.href===decodeURIComponent(doc.URL))return doc.URL;if(doc.location.hash&&decodeURIComponent(doc.location.href.replace(/^[^#]+/,""))===doc.location.hash)return doc.location.href;if(doc.URL.indexOf('#')==-1&&doc.location.href.indexOf('#')!=-1)return doc.location.href;return doc.URL||doc.location.href};History.store={};History.idToState=History.idToState||{};History.stateToId=History.stateToId||{};History.urlToId=History.urlToId||{};History.storedStates=History.storedStates||[];History.savedStates=History.savedStates||[];History.normalizeStore=function(){History.store.idToState=History.store.idToState||{};History.store.urlToId=History.store.urlToId||{};History.store.stateToId=History.store.stateToId||{}};History.getState=function(friendly,create){if(typeof friendly==='undefined')friendly=true;if(typeof create==='undefined')create=true;var State=History.getLastSavedState();if(!State&&create)State=History.createStateObject();if(friendly){State=History.cloneObject(State);State.url=State.cleanUrl||State.url};return State};History.getIdByState=function(newState){var id=History.extractId(newState.url),str;if(!id){str=History.getStateString(newState);if(typeof History.stateToId[str]!=='undefined'){id=History.stateToId[str]}else if(typeof History.store.stateToId[str]!=='undefined'){id=History.store.stateToId[str]}else{while(true){id=(new Date()).getTime()+String(Math.random()).replace(/\D/g,'');if(typeof History.idToState[id]==='undefined'&&typeof History.store.idToState[id]==='undefined')break};History.stateToId[str]=id;History.idToState[id]=newState}};return id};History.normalizeState=function(oldState){var newState,dataNotEmpty;if(!oldState||(typeof oldState!=='object'))oldState={};if(typeof oldState.normalized!=='undefined')return oldState;if(!oldState.data||(typeof oldState.data!=='object'))oldState.data={};newState={};newState.normalized=true;newState.title=oldState.title||'';newState.url=History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));newState.hash=History.getShortUrl(newState.url);newState.data=History.cloneObject(oldState.data);newState.id=History.getIdByState(newState);newState.cleanUrl=newState.url.replace(/\??\&_suid.*/,'');newState.url=newState.cleanUrl;dataNotEmpty=!History.isEmptyObject(newState.data);if((newState.title||dataNotEmpty)&&History.options.disableSuid!==true){newState.hash=History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');if(!/\?/.test(newState.hash))newState.hash+='?';newState.hash+='&_suid='+newState.id};newState.hashedUrl=History.getFullUrl(newState.hash);if((History.emulated.pushState||History.bugs.safariPoll)&&History.hasUrlDuplicate(newState))newState.url=newState.hashedUrl;return newState};History.createStateObject=function(data,title,url){var State={data:data,title:title,url:url};State=History.normalizeState(State);return State};History.getStateById=function(id){id=String(id);var State=History.idToState[id]||History.store.idToState[id]||undefined;return State};History.getStateString=function(passedState){var State,cleanedState,str;State=History.normalizeState(passedState);cleanedState={data:State.data,title:passedState.title,url:passedState.url};str=JSON.stringify(cleanedState);return str};History.getStateId=function(passedState){var State,id;State=History.normalizeState(passedState);id=State.id;return id};History.getHashByState=function(passedState){var State,hash;State=History.normalizeState(passedState);hash=State.hash;return hash};History.extractId=function(url_or_hash){var id,parts,url,tmp;if(url_or_hash.indexOf('#')!=-1){tmp=url_or_hash.split("#")[0]}else tmp=url_or_hash;parts=/(.*)\&_suid=([0-9]+)$/.exec(tmp);url=parts?(parts[1]||url_or_hash):url_or_hash;id=parts?String(parts[2]||''):'';return id||false};History.isTraditionalAnchor=function(url_or_hash){var isTraditional=!(/[\/\?\.]/.test(url_or_hash));return isTraditional};History.extractState=function(url_or_hash,create){var State=null,id,url;create=create||false;id=History.extractId(url_or_hash);if(id)State=History.getStateById(id);if(!State){url=History.getFullUrl(url_or_hash);id=History.getIdByUrl(url)||false;if(id)State=History.getStateById(id);if(!State&&create&&!History.isTraditionalAnchor(url_or_hash))State=History.createStateObject(null,null,url)};return State};History.getIdByUrl=function(url){var id=History.urlToId[url]||History.store.urlToId[url]||undefined;return id};History.getLastSavedState=function(){return History.savedStates[History.savedStates.length-1]||undefined};History.getLastStoredState=function(){return History.storedStates[History.storedStates.length-1]||undefined};History.hasUrlDuplicate=function(newState){var hasDuplicate=false,oldState;oldState=History.extractState(newState.url);hasDuplicate=oldState&&oldState.id!==newState.id;return hasDuplicate};History.storeState=function(newState){History.urlToId[newState.url]=newState.id;History.storedStates.push(History.cloneObject(newState));return newState};History.isLastSavedState=function(newState){var isLast=false,newId,oldState,oldId;if(History.savedStates.length){newId=newState.id;oldState=History.getLastSavedState();oldId=oldState.id;isLast=(newId===oldId)};return isLast};History.saveState=function(newState){if(History.isLastSavedState(newState))return false;History.savedStates.push(History.cloneObject(newState));return true};History.getStateByIndex=function(index){var State=null;if(typeof index==='undefined'){State=History.savedStates[History.savedStates.length-1]}else if(index<0){State=History.savedStates[History.savedStates.length+index]}else State=History.savedStates[index];return State};History.getCurrentIndex=function(){var index=null;if(History.savedStates.length<1){index=0}else index=History.savedStates.length-1;return index};History.getHash=function(doc){var url=History.getLocationHref(doc),hash;hash=History.getHashByUrl(url);return hash};History.unescapeHash=function(hash){var result=History.normalizeHash(hash);result=decodeURIComponent(result);return result};History.normalizeHash=function(hash){var result=hash.replace(/[^#]*#/,'').replace(/#.*/,'');return result};History.setHash=function(hash,queue){var State,pageUrl;if(queue!==false&&History.busy()){History.pushQueue({scope:History,callback:History.setHash,args:arguments,queue:queue});return false};History.busy(true);State=History.extractState(hash,true);if(State&&!History.emulated.pushState){History.pushState(State.data,State.title,State.url,false)}else if(History.getHash()!==hash)if(History.bugs.setHash){pageUrl=History.getPageUrl();History.pushState(null,null,pageUrl+'#'+hash,false)}else document.location.hash=hash;return History};History.escapeHash=function(hash){var result=History.normalizeHash(hash);result=window.encodeURIComponent(result);if(!History.bugs.hashEscape)result=result.replace(/\%21/g,'!').replace(/\%26/g,'&').replace(/\%3D/g,'=').replace(/\%3F/g,'?');return result};History.getHashByUrl=function(url){var hash=String(url).replace(/([^#]*)#?([^#]*)#?(.*)/,'$2');hash=History.unescapeHash(hash);return hash};History.setTitle=function(newState){var title=newState.title,firstState;if(!title){firstState=History.getStateByIndex(0);if(firstState&&firstState.url===newState.url)title=firstState.title||History.options.initialTitle};try{document.getElementsByTagName('title')[0].innerHTML=title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ')}catch(Exception){};document.title=title;return History};History.queues=[];History.busy=function(value){if(typeof value!=='undefined'){History.busy.flag=value}else if(typeof History.busy.flag==='undefined')History.busy.flag=false;if(!History.busy.flag){clearTimeout(History.busy.timeout);var fireNext=function(){var i,queue,item;if(History.busy.flag)return;for(i=History.queues.length-1;i>=0;--i){queue=History.queues[i];if(queue.length===0)continue;item=queue.shift();History.fireQueueItem(item);History.busy.timeout=setTimeout(fireNext,History.options.busyDelay)}};History.busy.timeout=setTimeout(fireNext,History.options.busyDelay)};return History.busy.flag};History.busy.flag=false;History.fireQueueItem=function(item){return item.callback.apply(item.scope||History,item.args||[])};History.pushQueue=function(item){History.queues[item.queue||0]=History.queues[item.queue||0]||[];History.queues[item.queue||0].push(item);return History};History.queue=function(item,queue){if(typeof item==='function')item={callback:item};if(typeof queue!=='undefined')item.queue=queue;if(History.busy()){History.pushQueue(item)}else History.fireQueueItem(item);return History};History.clearQueue=function(){History.busy.flag=false;History.queues=[];return History};History.stateChanged=false;History.doubleChecker=false;History.doubleCheckComplete=function(){History.stateChanged=true;History.doubleCheckClear();return History};History.doubleCheckClear=function(){if(History.doubleChecker){clearTimeout(History.doubleChecker);History.doubleChecker=false};return History};History.doubleCheck=function(tryAgain){History.stateChanged=false;History.doubleCheckClear();if(History.bugs.ieDoubleCheck)History.doubleChecker=setTimeout(function(){History.doubleCheckClear();if(!History.stateChanged)tryAgain();return true},History.options.doubleCheckInterval);return History};History.safariStatePoll=function(){var urlState=History.extractState(History.getLocationHref()),newState;if(!History.isLastSavedState(urlState)){newState=urlState}else return;if(!newState)newState=History.createStateObject();History.Adapter.trigger(window,'popstate');return History};History.back=function(queue){if(queue!==false&&History.busy()){History.pushQueue({scope:History,callback:History.back,args:arguments,queue:queue});return false};History.busy(true);History.doubleCheck(function(){History.back(false)});history.go(-1);return true};History.forward=function(queue){if(queue!==false&&History.busy()){History.pushQueue({scope:History,callback:History.forward,args:arguments,queue:queue});return false};History.busy(true);History.doubleCheck(function(){History.forward(false)});history.go(1);return true};History.go=function(index,queue){var i;if(index>0){for(i=1;i<=index;++i)History.forward(queue)}else if(index<0){for(i=-1;i>=index;--i)History.back(queue)}else throw new Error('History.go: History.go requires a positive or negative integer passed.');return History};if(History.emulated.pushState){var emptyFunction=function(){};History.pushState=History.pushState||emptyFunction;History.replaceState=History.replaceState||emptyFunction}else{History.onPopState=function(event,extra){var stateId=false,newState=false,currentHash,currentState;History.doubleCheckComplete();currentHash=History.getHash();if(currentHash){currentState=History.extractState(currentHash||History.getLocationHref(),true);if(currentState){History.replaceState(currentState.data,currentState.title,currentState.url,false)}else{History.Adapter.trigger(window,'anchorchange');History.busy(false)};History.expectedStateId=false;return false};stateId=History.Adapter.extractEventData('state',event,extra)||false;if(stateId){newState=History.getStateById(stateId)}else if(History.expectedStateId){newState=History.getStateById(History.expectedStateId)}else newState=History.extractState(History.getLocationHref());if(!newState)newState=History.createStateObject(null,null,History.getLocationHref());History.expectedStateId=false;if(History.isLastSavedState(newState)){History.busy(false);return false};History.storeState(newState);History.saveState(newState);History.setTitle(newState);History.Adapter.trigger(window,'statechange');History.busy(false);return true};History.Adapter.bind(window,'popstate',History.onPopState);History.pushState=function(data,title,url,queue){if(History.getHashByUrl(url)&&History.emulated.pushState)throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');if(queue!==false&&History.busy()){History.pushQueue({scope:History,callback:History.pushState,args:arguments,queue:queue});return false};History.busy(true);var newState=History.createStateObject(data,title,url);if(History.isLastSavedState(newState)){History.busy(false)}else{History.storeState(newState);History.expectedStateId=newState.id;history.pushState(newState.id,newState.title,newState.url);History.Adapter.trigger(window,'popstate')};return true};History.replaceState=function(data,title,url,queue){if(History.getHashByUrl(url)&&History.emulated.pushState)throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');if(queue!==false&&History.busy()){History.pushQueue({scope:History,callback:History.replaceState,args:arguments,queue:queue});return false};History.busy(true);var newState=History.createStateObject(data,title,url);if(History.isLastSavedState(newState)){History.busy(false)}else{History.storeState(newState);History.expectedStateId=newState.id;history.replaceState(newState.id,newState.title,newState.url);History.Adapter.trigger(window,'popstate')};return true}};if(sessionStorage){try{History.store=JSON.parse(sessionStorage.getItem('History.store'))||{}}catch(err){History.store={}};History.normalizeStore()}else{History.store={};History.normalizeStore()};History.Adapter.bind(window,"unload",History.clearAllIntervals);History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));if(sessionStorage){History.onUnload=function(){var currentStore,item,currentStoreString;try{currentStore=JSON.parse(sessionStorage.getItem('History.store'))||{}}catch(err){currentStore={}};currentStore.idToState=currentStore.idToState||{};currentStore.urlToId=currentStore.urlToId||{};currentStore.stateToId=currentStore.stateToId||{};for(item in History.idToState){if(!History.idToState.hasOwnProperty(item))continue;currentStore.idToState[item]=History.idToState[item]};for(item in History.urlToId){if(!History.urlToId.hasOwnProperty(item))continue;currentStore.urlToId[item]=History.urlToId[item]};for(item in History.stateToId){if(!History.stateToId.hasOwnProperty(item))continue;currentStore.stateToId[item]=History.stateToId[item]};History.store=currentStore;History.normalizeStore();currentStoreString=JSON.stringify(currentStore);try{sessionStorage.setItem('History.store',currentStoreString)}catch(e){if(e.code===DOMException.QUOTA_EXCEEDED_ERR){if(sessionStorage.length){sessionStorage.removeItem('History.store');sessionStorage.setItem('History.store',currentStoreString)}}else throw e}};History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));History.Adapter.bind(window,'beforeunload',History.onUnload);History.Adapter.bind(window,'unload',History.onUnload)};if(!History.emulated.pushState){if(History.bugs.safariPoll)History.intervalList.push(setInterval(History.safariStatePoll,History.options.safariPollInterval));if(navigator.vendor==='Apple Computer, Inc.'||(navigator.appCodeName||'')==='Mozilla'){History.Adapter.bind(window,'hashchange',function(){History.Adapter.trigger(window,'popstate')});if(History.getHash())History.Adapter.onDomLoad(function(){History.Adapter.trigger(window,'hashchange')})}}};if(!History.options||!History.options.delayInit)History.init()})(window)
;
