/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.lj.repostbutton.js 
*/

/**
 * @name $.lj.repostbutton
 * @requires $.ui.core, $.ui.widget, $.lj.basicWidget, $.lj.bubble
 * @class Represents repost button
 * @author dmitry.petrov@sup.com (Dmitry Petrov), anazarov@sup.com (Alexander Nazarov)
 */
;(function ($) {
  'use strict';

  /** @lends $.lj.repostbutton.prototype */
  $.widget('lj.repostbutton', $.lj.basicWidget, {
    options: {
      classNames: {
        active: 'repost-button-active',
        inactive: 'repost-button-inactive',
        popupLoad: 'b-reposted-popup-load',
        popupNomore: 'b-reposted-popup-footer-hide',
        repostError: 'repost-error'
      },

      selectors: {
        counterParent: '.lj-button-c',
        button: '.lj-button-b',
        counter: '.lj-like-item-count',
        buttonLink: '.lj-button-link',
        popupContent: '.b-reposted-popup-content',
        popupFooter: '.b-reposted-popup-footer',
        popupMore: '.b-reposted-popup-footer > a'
      },

      templates: {
        popup: 'templates-CleanHtml-reposted'
      },

      url: '',
      reposted: false,
      cost: 0,
      budget: 0,
      paid: false
    },

    _create: function() {
      $.lj.basicWidget.prototype._create.apply(this);

      if (!this.options.url) {
        console.warn(this.widgetName, ': no url in options, initialization won\'t continue');
      }

      this._journal = LJ.get('currentJournal');
      this._count = null;
      this._remote = LJ.get('remoteUser');
      this._reposted = this.options.reposted;
      this._el('buttonLink');
      this._href = this.element.find(this._s('button')).data('href');
      this._href = LJ.Util.Journal.parseLink(this._href) || {};

      if (!this._canRepost()) {
        this.element.addClass(this._cl('inactive'));
        this._buttonLink.removeAttr('title');
        this._lock();
      }

      this._popup = null;
      this._popupContent = null;
      this._popupLocked = false;
      this._lastUser = null;
      this._el('counterParent');
      this._el('counter');

      if (!Number(this._counter.html())) { this._hideCounter(); }

      this._bindControls();
    },

    _hideCounter: function () {
      this._counterParent.addClass('empty');
    },

    _showCounter: function () {
      this._counterParent.removeClass('empty');
    },

    _bindControls: function() {
      var repost = this;

      this.element.on('click', this._s('button'), this._onUpdateButton.bind(this));

      this._counterParent.one('click', function() {
        if ( !Number(repost._counter.html()) ) {
          return;
        }

        repost._popup = repost._tmpl('popup');
        repost._el('popupFooter', repost._popup);
        repost._popupContent = repost._popup.find(repost._s('popupContent'));

        repost._popup.bubble({
          showOn: 'click',
          align: 'side',
          alwaysShowUnderTarget: true,
          target: repost._counterParent
        })
        .on('bubblehide', function () {
          repost._lastUser = null;
          repost._popupContent.empty();
          repost._popupFooter.removeClass(repost._cl('popupNomore'));
        })
        .on('bubbleshow', function () {
          repost._loadRepostedList();
        })
        .on('click', repost._s('popupMore'), repost._loadRepostedList.bind(repost));

        Function.defer(function() {
          repost._popup.bubble('show');
        });
      });

      $.lj.basicWidget.prototype._bindControls.apply(repost);
    },

    _loadRepostedList: function(ev) {
      var repost = this;

      if (ev) { ev.preventDefault(); }
      if (this._popupLocked) { return; }

      this._popupLocked = true;
      this._popupContent.addClass(this._cl('popupLoad'));

      LJ.Api.call('repost.get_list', { url: this.options.url, last: this._lastUser }, function(answer) {
        repost._popupContent.removeClass(repost._cl('popupLoad'));
        repost._popupLocked = false;
        if (answer.error) {
          repost._handleAnswer(answer);
        } else {
          repost._render(answer.users, answer.nomore, answer.count);
          repost._lastUser = answer.last;
        }
      });
    },

    _render: function(users, nomore, count) {
      var repost = this;

      /* Display users */
      if (users.length > 0) {
        repost._tmpl('popup', {
          content: true,
          dropComma: !!repost._lastUser,
          users: users
        }).appendTo(repost._popupContent);
      }

      this._updateCounter(count);

      /* Hide 'Show More' button */
      if (nomore) {
        repost._popupFooter.addClass(repost._cl('popupNomore'));
      }
    },

    _onUpdateButton: function(ev) {
      if (!this.locked()) {
        this.toggleRepost();
      }
      ev.preventDefault();
    },

    _handleAnswer: function(answer) {
      if (answer.hasOwnProperty('delete')) {
        if (answer.message) {
          this._showMessage(answer.message);
        }

        /* LJSUP-13479: Repost type or cost changed */
        if ( this.paid !== Boolean(answer.paid) || this.paid && (this.cost !== answer.cost) ) {
          this.element.replaceWith(LJ.Likes.renderRepostButton(this.options.url, answer));
          return;
        }
      }

      if (answer.error) {
        if (answer.error.message) {
          this._showMessage(answer.error.message);
        }

        if (answer.error.data) {
          // Redraw button completely with new data
          this.element.replaceWith(LJ.Likes.renderRepostButton(this.options.url, answer.error.data));
          return;
        }
      } else {
        this._updateButton( !this._reposted );
      }

      if (!answer.hasOwnProperty('count') && answer.hasOwnProperty('delete')) {
        answer.count = this._count - 1;
      }

      this._updateCounter(answer.count);
      this._unlock();
    },

    _showMessage: function (message) {
      var errorBubble = $('<div />', {
        'class': this._cl('repostError'),
        text: message
      })
      .bubble({
        target: this.element,
        align: 'center',
        hide: function () {
          errorBubble.remove();
        }
      })
      .bubble('show');
    },

    _updateButton: function(reposted) {
      this._reposted = reposted;
      this.element.toggleClass(this._cl('active'), this._reposted);
    },

    _updateCounter: function (count) {
      if (typeof count !== 'undefined') {
        this._count = Number(count);
        this._counter.html(this._count);
      }

      if (!Number(this._counter.html())) {
        this._hideCounter();
      } else {
        this._showCounter();
      }
    },

    _canRepost: function () {
      if (LJ.get('preview')) { return false; }
      if (!this._remote) { return false; }
      if (LJ.get('remote_is_identity')) { return false; }
      if (this._remote === this._href.journal) { return false; }

      return true;
    },

    toggleRepost: function() {
      var repost = this,
        args = {
          url: this.options.url
        };

      if (!this._canRepost()) { return; }

      if (this._count === null) {
        this._count = parseInt( this._el('counter').html(), 10) || 0;
      }

      this._lock();
      if (this._reposted) {
        LJ.Api.call('repost.delete', args, function (answer) {
          /* LJSUP-12559: Reload page when repost is deleted in remote user's journal */
          if (!answer.error && !answer.reposted && repost._journal === repost._remote && !location.href.match(/\/friends(?:friends|times)?\b/)) {
            location.reload();
          } else {
            repost._handleAnswer(answer);
          }
        });
      } else {
        args.timezone = LJ.Util.Date.timezone();

        if (this.options.paid) {
          args.cost = this.options.cost;
        }

        LJ.Api.call('repost.create', args, this._handleAnswer.bind(this));
      }
    }
  });
}(jQuery));

;

/* file-end: js/jquery/jquery.lj.repostbutton.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.hotkeys.js 
*/

/*
 * jQuery Hotkeys Plugin
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Based upon the plugin by Tzury Bar Yochay:
 * http://github.com/tzuryby/hotkeys
 *
 * Original idea by:
 * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/
*/

(function(jQuery){
	
	jQuery.hotkeys = {
		version: "0.8",

		specialKeys: {
			8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
			20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
			37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 
			96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
			104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 
			112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 
			120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 187: "+", 189: "-", 191: "/", 224: "meta"
		},
	
		shiftNums: {
			"`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", 
			"8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", 
			".": ">",  "/": "?",  "\\": "|"
		}
	};

	function keyHandler( handleObj ) {
		// Only care when a possible input has been specified
		if ( typeof handleObj.data !== "string" ) {
			return;
		}
		
		var origHandler = handleObj.handler,
			keys = handleObj.data.toLowerCase().split(" ");
	
		handleObj.handler = function( event ) {
			// Don't fire in text-accepting inputs that we didn't directly bind to
			if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) ||
				 /text|password|search|tel|url|email|number/.test( event.target.type ) ) ) {
				return;
			}
			
			// Keypress represents characters, not special keys
			var special = event.type !== "keypress" && jQuery.hotkeys.specialKeys[ event.which ],
				character = String.fromCharCode( event.which ).toLowerCase(),
				key, modif = "", possible = {};

			// check combinations (alt|ctrl|shift+anything)
			if ( event.altKey && special !== "alt" ) {
				modif += "alt+";
			}

			if ( event.ctrlKey && special !== "ctrl" ) {
				modif += "ctrl+";
			}
			
			// TODO: Need to make sure this works consistently across platforms
			if ( event.metaKey && !event.ctrlKey && special !== "meta" ) {
				modif += "meta+";
			}

			if ( event.shiftKey && special !== "shift" ) {
				modif += "shift+";
			}

			if ( special ) {
				possible[ modif + special ] = true;

			} else {
				possible[ modif + character ] = true;
				possible[ modif + jQuery.hotkeys.shiftNums[ character ] ] = true;

				// "$" can be triggered as "Shift+4" or "Shift+$" or just "$"
				if ( modif === "shift+" ) {
					possible[ jQuery.hotkeys.shiftNums[ character ] ] = true;
				}
			}

			for ( var i = 0, l = keys.length; i < l; i++ ) {
				if ( possible[ keys[i] ] ) {
					return origHandler.apply( this, arguments );
				}
			}
		};
	}

	jQuery.each([ "keydown", "keyup", "keypress" ], function() {
		jQuery.event.special[ this ] = { add: keyHandler };
	});

})( jQuery );
;

/* file-end: js/jquery/jquery.hotkeys.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.easing.js 
*/

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */;

/* file-end: js/jquery/jquery.easing.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.lj.photouploader.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/lib/jquery-ui/jquery.ui.mouse.min.js 
*/

/*! jQuery UI - v1.8.24 - 2012-09-28
* https://github.com/jquery/jquery-ui
* Includes: jquery.ui.mouse.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
(function(a,b){var c=!1;a(document).mouseup(function(a){c=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){if(!0===a.data(c.target,b.widgetName+".preventClickEvent"))return a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(b){if(c)return;this._mouseStarted&&this._mouseUp(b),this._mouseDownEvent=b;var d=this,e=b.which==1,f=typeof this.options.cancel=="string"&&b.target.nodeName?a(b.target).closest(this.options.cancel).length:!1;if(!e||f||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)){this._mouseStarted=this._mouseStart(b)!==!1;if(!this._mouseStarted)return b.preventDefault(),!0}return!0===a.data(b.target,this.widgetName+".preventClickEvent")&&a.removeData(b.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),b.preventDefault(),c=!0,!0},_mouseMove:function(b){return!a.browser.msie||document.documentMode>=9||!!b.button?this._mouseStarted?(this._mouseDrag(b),b.preventDefault()):(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b)),!this._mouseStarted):this._mouseUp(b)},_mouseUp:function(b){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b)),!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})})(jQuery);;

/* file-end: js/lib/jquery-ui/jquery.ui.mouse.min.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/lib/jquery-ui/jquery.ui.sortable.min.js 
*/

/*! jQuery UI - v1.8.24 - 2012-09-28
* https://github.com/jquery/jquery-ui
* Includes: jquery.ui.sortable.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
(function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){b==="disabled"?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(b);var e=null,f=this,g=a(b.target).parents().each(function(){if(a.data(this,d.widgetName+"-item")==f)return e=a(this),!1});a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target));if(!e)return!1;if(this.options.handle&&!c){var h=!1;a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(h=!0)});if(!h)return!1}return this.currentItem=e,this._removeCurrentsFromItems(),!0},_mouseStart:function(b,c,d){var e=this.options,f=this;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));return a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b),!0},_mouseDrag:function(b){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY<c.scrollSensitivity?this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop+c.scrollSpeed:b.pageY-this.overflowOffset.top<c.scrollSensitivity&&(this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop-c.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-b.pageX<c.scrollSensitivity?this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft+c.scrollSpeed:b.pageX-this.overflowOffset.left<c.scrollSensitivity&&(this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft-c.scrollSpeed)):(b.pageY-a(document).scrollTop()<c.scrollSensitivity?d=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<c.scrollSensitivity&&(d=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed)),b.pageX-a(document).scrollLeft()<c.scrollSensitivity?d=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(d=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed))),d!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(!h)continue;if(f.instance!==this.currentContainer)continue;if(g!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],g):!0)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f))this._rearrange(b,f);else break;this._trigger("change",b,this._uiHash());break}}return this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(b,c){if(!b)return;a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b);if(this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"="),d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")}),d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&d+j<i&&b+k>f&&b+k<g;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?l:f<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<g&&h<d+this.helperProportions.height/2&&e-this.helperProportions.height/2<i},_intersectsWithPointer:function(b){var c=this.options.axis==="x"||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top,b.height),d=this.options.axis==="y"||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left,b.width),e=c&&d,f=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();return e?this.floating?g&&g=="right"||f=="down"?2:1:f&&(f=="down"?2:1):!1},_intersectsWithSides:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top+b.height/2,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left+b.width/2,b.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?f=="right"&&d||f=="left"&&!d:e&&(e=="down"&&c||e=="up"&&!c)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){return this._refreshItems(a),this.refreshPositions(),this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=this,d=[],e=[],f=this._connectWith();if(f&&b)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&e.push([a.isFunction(j.options.items)?j.options.items.call(j.element):a(j.options.items,j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),j])}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var g=e.length-1;g>=0;g--)e[g][0].each(function(){d.push(this)});return a(d)},_removeCurrentsFromItems:function(){var a=this.currentItem.find(":data("+this.widgetName+"-item)");for(var b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(b){this.items=[],this.containers=[this];var c=this.items,d=this,e=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]],f=this._connectWith();if(f&&this.ready)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&(e.push([a.isFunction(j.options.items)?j.options.items.call(j.element[0],b,{item:this.currentItem}):a(j.options.items,j.element),j]),this.containers.push(j))}}for(var g=e.length-1;g>=0;g--){var k=e[g][1],l=e[g][0];for(var i=0,m=l.length;i<m;i++){var n=a(l[i]);n.data(this.widgetName+"-item",k),c.push({item:n,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var c=this.items.length-1;c>=0;c--){var d=this.items[c];if(d.instance!=this.currentContainer&&this.currentContainer&&d.item[0]!=this.currentItem[0])continue;var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return e||(b.style.visibility="hidden"),b},update:function(a,b){if(e&&!d.forcePlaceholderSize)return;b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){var c=null,d=null;for(var e=this.containers.length-1;e>=0;e--){if(a.ui.contains(this.currentItem[0],this.containers[e].element[0]))continue;if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"];for(var i=this.items.length-1;i>=0;i--){if(!a.ui.contains(this.containers[d].element[0],this.items[i].item[0]))continue;var j=this.containers[d].floating?this.items[i].item.offset().left:this.items[i].item.offset().top;Math.abs(j-h)<f&&(f=Math.abs(j-h),g=this.items[i],this.direction=j-h>0?"down":"up")}if(!g&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[d],g?this._rearrange(b,g,null,!0):this._rearrange(b,null,this.containers[d].element,!0),this._trigger("change",b,this._uiHash()),this.containers[d]._trigger("change",b,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1}},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b,this.currentItem])):c.helper=="clone"?this.currentItem.clone():this.currentItem;return d.parents("body").length||a(c.appendTo!="parent"?c.appendTo:this.currentItem[0].parentNode)[0].appendChild(d[0]),d[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(d[0].style.width==""||c.forceHelperSize)&&d.width(this.currentItem.width()),(d[0].style.height==""||c.forceHelperSize)&&d.height(this.currentItem.height()),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)){var c=a(b.containment)[0],d=a(b.containment).offset(),e=a(c).css("overflow")!="hidden";this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(e?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(e?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var f=b.pageX,g=b.pageY;if(this.originalPosition){this.containment&&(b.pageX-this.offset.click.left<this.containment[0]&&(f=this.containment[0]+this.offset.click.left),b.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),b.pageX-this.offset.click.left>this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top));if(c.grid){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1];g=this.containment?h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3]?h-this.offset.click.top<this.containment[1]?h+c.grid[1]:h-c.grid[1]:h:h;var i=this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0];f=this.containment?i-this.offset.click.left<this.containment[0]||i-this.offset.click.left>this.containment[2]?i-this.offset.click.left<this.containment[0]?i+c.grid[0]:i-c.grid[0]:i:i}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_rearrange:function(a,b,c,d){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var e=this,f=this.counter;window.setTimeout(function(){f==e.counter&&e.refreshPositions(!d)},0)},_clear:function(b,c){this.reverting=!1;var d=[],e=this;!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var f in this._storedCSS)if(this._storedCSS[f]=="auto"||this._storedCSS[f]=="static")this._storedCSS[f]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!c&&d.push(function(a){this._trigger("receive",a,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!c&&d.push(function(a){this._trigger("update",a,this._uiHash())}),this!==this.currentContainer&&(c||(d.push(function(a){this._trigger("remove",a,this._uiHash())}),d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.currentContainer)),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.currentContainer))));for(var f=this.containers.length-1;f>=0;f--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=0);this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!1}c||this._trigger("beforeStop",b,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!c){for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){a.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(b){var c=b||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:b?b.element:null}}}),a.extend(a.ui.sortable,{version:"1.8.24"})})(jQuery);;

/* file-end: js/lib/jquery-ui/jquery.ui.sortable.min.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/swfupload/swfupload.js 
*/

/**
 * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
 *
 * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
 *
 * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz�n and Mammon Media and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */


/* ******************* */
/* Constructor & Init  */
/* ******************* */
var SWFUpload;

if (SWFUpload == undefined) {
	SWFUpload = function (settings) {
		this.initSWFUpload(settings);
	};

	// debug mode. Default: false;
	// It has been provided for IE, as part of #LJSUP-13493.
	// because SWFUploader doesn't catch errors
	SWFUpload.debug = false;
}

SWFUpload.prototype.initSWFUpload = function (settings) {
	try {
		this.customSettings = {};	// A container where developers can place their own settings associated with this instance.
		this.settings = settings;
		this.eventQueue = [];
		this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
		this.movieElement = null;


		// Setup global control tracking
		SWFUpload.instances[this.movieName] = this;

		// Load the settings.  Load the Flash movie.
		this.initSettings();
		this.loadFlash();
		this.displayDebugInfo();
	} catch (ex) {
		delete SWFUpload.instances[this.movieName];
		if (SWFUpload.debug) throw ex;
	}
};

/* *************** */
/* Static Members  */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
SWFUpload.QUEUE_ERROR = {
	QUEUE_LIMIT_EXCEEDED	  		: -100,
	FILE_EXCEEDS_SIZE_LIMIT  		: -110,
	ZERO_BYTE_FILE			  		: -120,
	INVALID_FILETYPE		  		: -130
};
SWFUpload.UPLOAD_ERROR = {
	HTTP_ERROR				  		: -200,
	MISSING_UPLOAD_URL	      		: -210,
	IO_ERROR				  		: -220,
	SECURITY_ERROR			  		: -230,
	UPLOAD_LIMIT_EXCEEDED	  		: -240,
	UPLOAD_FAILED			  		: -250,
	SPECIFIED_FILE_ID_NOT_FOUND		: -260,
	FILE_VALIDATION_FAILED	  		: -270,
	FILE_CANCELLED			  		: -280,
	UPLOAD_STOPPED					: -290
};
SWFUpload.FILE_STATUS = {
	QUEUED		 : -1,
	IN_PROGRESS	 : -2,
	ERROR		 : -3,
	COMPLETE	 : -4,
	CANCELLED	 : -5
};
SWFUpload.BUTTON_ACTION = {
	SELECT_FILE  : -100,
	SELECT_FILES : -110,
	START_UPLOAD : -120
};
SWFUpload.CURSOR = {
	ARROW : -1,
	HAND : -2
};
SWFUpload.WINDOW_MODE = {
	WINDOW : "window",
	TRANSPARENT : "transparent",
	OPAQUE : "opaque"
};

// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function(url) {
	if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
		return url;
	}
	
	var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
	
	var indexSlash = window.location.pathname.lastIndexOf("/");
	if (indexSlash <= 0) {
		path = "/";
	} else {
		path = window.location.pathname.substr(0, indexSlash) + "/";
	}
	
	return /*currentURL +*/ path + url;
	
};


/* ******************** */
/* Instance Members  */
/* ******************** */

// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
	this.ensureDefault = function (settingName, defaultValue) {
		this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	};
	
	// Upload backend settings
	this.ensureDefault("upload_url", "");
	this.ensureDefault("preserve_relative_urls", false);
	this.ensureDefault("file_post_name", "Filedata");
	this.ensureDefault("post_params", {});
	this.ensureDefault("use_query_string", false);
	this.ensureDefault("requeue_on_error", false);
	this.ensureDefault("http_success", []);
	this.ensureDefault("assume_success_timeout", 0);
	
	// File Settings
	this.ensureDefault("file_types", "*.*");
	this.ensureDefault("file_types_description", "All Files");
	this.ensureDefault("file_size_limit", 0);	// Default zero means "unlimited"
	this.ensureDefault("file_upload_limit", 0);
	this.ensureDefault("file_queue_limit", 0);

	// Flash Settings
	this.ensureDefault("flash_url", "swfupload.swf");
	this.ensureDefault("prevent_swf_caching", true);
	
	// Button Settings
	this.ensureDefault("button_image_url", "");
	this.ensureDefault("button_width", 1);
	this.ensureDefault("button_height", 1);
	this.ensureDefault("button_text", "");
	this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
	this.ensureDefault("button_text_top_padding", 0);
	this.ensureDefault("button_text_left_padding", 0);
	this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
	this.ensureDefault("button_disabled", false);
	this.ensureDefault("button_placeholder_id", "");
	this.ensureDefault("button_placeholder", null);
	this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
	this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
	
	// Debug Settings
	this.ensureDefault("debug", false);
	this.settings.debug_enabled = this.settings.debug;	// Here to maintain v2 API
	
	// Event Handlers
	this.settings.return_upload_start_handler = this.returnUploadStart;
	this.ensureDefault("swfupload_loaded_handler", null);
	this.ensureDefault("file_dialog_start_handler", null);
	this.ensureDefault("file_queued_handler", null);
	this.ensureDefault("file_queue_error_handler", null);
	this.ensureDefault("file_dialog_complete_handler", null);
	
	this.ensureDefault("upload_start_handler", null);
	this.ensureDefault("upload_progress_handler", null);
	this.ensureDefault("upload_error_handler", null);
	this.ensureDefault("upload_success_handler", null);
	this.ensureDefault("upload_complete_handler", null);
	
	this.ensureDefault("debug_handler", this.debugMessage);

	this.ensureDefault("custom_settings", {});

	// Other settings
	this.customSettings = this.settings.custom_settings;
	
	// Update the flash url if needed
	if (!!this.settings.prevent_swf_caching) {
		this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
	}
	
	if (!this.settings.preserve_relative_urls) {
		//this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url);	// Don't need to do this one since flash doesn't look at it
		this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
		this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
	}
	
	delete this.ensureDefault;
};

// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
	var targetElement, tempParent;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		if (SWFUpload.debug) throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the element where we will be placing the flash movie
	targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;

	if (targetElement == undefined) {
		if (SWFUpload.debug) throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
	}

	// Append the container and load the flash
	tempParent = document.createElement("div");
	tempParent.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
	targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = this.getMovieElement();
	}
	
};

// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
	// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
	var classId = navigator.userAgent.indexOf('MSIE') + 1 ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : '';

	return ['<object ' + classId + ' id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				'<param name="wmode" value="', this.settings.button_window_mode, '" />',
				'<param name="movie" value="', this.settings.flash_url, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + this.getFlashVars() + '" />',
				'</object>'].join("");
};

// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
	// Build a string from the post param object
	var paramString = this.buildParamString();
	var httpSuccessString = this.settings.http_success.join(",");
	
	// Build the parameter string
	return ["movieName=", encodeURIComponent(this.movieName),
			"&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			"&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			"&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			"&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
			"&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
			"&amp;params=", encodeURIComponent(paramString),
			"&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			"&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			"&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			"&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			"&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			"&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			"&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			"&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			"&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			"&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			"&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			"&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			"&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			"&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			"&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			"&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
			"&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
		].join("");
};

// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
	if (this.movieElement == undefined) {
		this.movieElement = document.getElementById(this.movieName);
	}

	if (this.movieElement === null) {
		if (SWFUpload.debug) throw "Could not find Flash element";
	}
	
	return this.movieElement;
};

// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&amp;name=value"
SWFUpload.prototype.buildParamString = function () {
	var postParams = this.settings.post_params; 
	var paramStringPairs = [];

	if (typeof(postParams) === "object") {
		for (var name in postParams) {
			if (postParams.hasOwnProperty(name)) {
				paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
			}
		}
	}

	return paramStringPairs.join("&amp;");
};

// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
	try {
		// Make sure Flash is done before we try to remove it
		this.cancelUpload(null, false);
		

		// Remove the SWFUpload DOM nodes
		var movieElement = null;
		movieElement = this.getMovieElement();
		
		if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
			for (var i in movieElement) {
				try {
					if (typeof(movieElement[i]) === "function") {
						movieElement[i] = null;
					}
				} catch (ex1) {}
			}

			// Remove the Movie Element from the page
			try {
				movieElement.parentNode.removeChild(movieElement);
			} catch (ex) {}
		}
		
		// Remove IE form fix reference
		window[this.movieName] = null;

		// Destroy other references
		SWFUpload.instances[this.movieName] = null;
		delete SWFUpload.instances[this.movieName];

		this.movieElement = null;
		this.settings = null;
		this.customSettings = null;
		this.eventQueue = null;
		this.movieName = null;
		
		
		return true;
	} catch (ex2) {
		return false;
	}
};


// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
	this.debug(
		[
			"---SWFUpload Instance Info---\n",
			"Version: ", SWFUpload.version, "\n",
			"Movie Name: ", this.movieName, "\n",
			"Settings:\n",
			"\t", "upload_url:               ", this.settings.upload_url, "\n",
			"\t", "flash_url:                ", this.settings.flash_url, "\n",
			"\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			"\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
			"\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
			"\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",
			"\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			"\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			"\t", "file_types:               ", this.settings.file_types, "\n",
			"\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			"\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			"\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			"\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			"\t", "debug:                    ", this.settings.debug.toString(), "\n",

			"\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			"\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			"\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
			"\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			"\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			"\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			"\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			"\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			"\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			"\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			"\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			"\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			"Event Handlers:\n",
			"\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			"\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			"\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			"\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			"\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			"\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			"\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			"\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			"\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		].join("")
	);
};

/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
	the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
    if (value == undefined) {
        return (this.settings[name] = default_value);
    } else {
        return (this.settings[name] = value);
	}
};

// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
    if (this.settings[name] != undefined) {
        return this.settings[name];
	}

    return "";
};



// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
	argumentArray = argumentArray || [];
	
	var movieElement = this.getMovieElement();
	var returnValue, returnString;

	// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
	try {
		returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
		returnValue = eval(returnString);
	} catch (ex) {
		if (SWFUpload.debug) throw "Call to " + functionName + " failed";
	}
	
	// Unescape file post param values
	if (returnValue != undefined && typeof returnValue.post === "object") {
		returnValue = this.unescapeFilePostParams(returnValue);
	}

	return returnValue;
};

/* *****************************
	-- Flash control methods --
	Your UI should use these
	to operate SWFUpload
   ***************************** */

// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear.  This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
	this.callFlash("SelectFile");
};

// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
	this.callFlash("SelectFiles");
};


// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID 
SWFUpload.prototype.startUpload = function (fileID) {
	this.callFlash("StartUpload", [fileID]);
};

// Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
	if (triggerErrorEvent !== false) {
		triggerErrorEvent = true;
	}
	this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};

// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
	this.callFlash("StopUpload");
};

/* ************************
 * Settings methods
 *   These methods change the SWFUpload settings.
 *   SWFUpload settings should not be changed directly on the settings object
 *   since many of the settings need to be passed to Flash in order to take
 *   effect.
 * *********************** */

// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
	return this.callFlash("GetStats");
};

// Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
// change the statistics but you can.  Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
	this.callFlash("SetStats", [statsObject]);
};

// Public: getFile retrieves a File object by ID or Index.  If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
	if (typeof(fileID) === "number") {
		return this.callFlash("GetFileByIndex", [fileID]);
	} else {
		return this.callFlash("GetFile", [fileID]);
	}
};

// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID.  If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
	return this.callFlash("AddFileParam", [fileID, name, value]);
};

// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
	this.callFlash("RemoveFileParam", [fileID, name]);
};

// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
	this.settings.upload_url = url.toString();
	this.callFlash("SetUploadURL", [url]);
};

// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
	this.settings.post_params = paramsObject;
	this.callFlash("SetPostParams", [paramsObject]);
};

// Public: addPostParam adds post name/value pair.  Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
	this.settings.post_params[name] = value;
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
	delete this.settings.post_params[name];
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
	this.settings.file_types = types;
	this.settings.file_types_description = description;
	this.callFlash("SetFileTypes", [types, description]);
};

// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
	this.settings.file_size_limit = fileSizeLimit;
	this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};

// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
	this.settings.file_upload_limit = fileUploadLimit;
	this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};

// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
	this.settings.file_queue_limit = fileQueueLimit;
	this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};

// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
	this.settings.file_post_name = filePostName;
	this.callFlash("SetFilePostName", [filePostName]);
};

// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
	this.settings.use_query_string = useQueryString;
	this.callFlash("SetUseQueryString", [useQueryString]);
};

// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
	this.settings.requeue_on_error = requeueOnError;
	this.callFlash("SetRequeueOnError", [requeueOnError]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
	if (typeof http_status_codes === "string") {
		http_status_codes = http_status_codes.replace(" ", "").split(",");
	}
	
	this.settings.http_success = http_status_codes;
	this.callFlash("SetHTTPSuccess", [http_status_codes]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
	this.settings.assume_success_timeout = timeout_seconds;
	this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};

// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
	this.settings.debug_enabled = debugEnabled;
	this.callFlash("SetDebugEnabled", [debugEnabled]);
};

// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
	if (buttonImageURL == undefined) {
		buttonImageURL = "";
	}
	
	this.settings.button_image_url = buttonImageURL;
	this.callFlash("SetButtonImageURL", [buttonImageURL]);
};

// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
	this.settings.button_width = width;
	this.settings.button_height = height;
	
	var movie = this.getMovieElement();
	if (movie != undefined) {
		movie.style.width = width + "px";
		movie.style.height = height + "px";
	}
	
	this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
	this.settings.button_text = html;
	this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
	this.settings.button_text_top_padding = top;
	this.settings.button_text_left_padding = left;
	this.callFlash("SetButtonTextPadding", [left, top]);
};

// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
	this.settings.button_text_style = css;
	this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
	this.settings.button_disabled = isDisabled;
	this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
	this.settings.button_action = buttonAction;
	this.callFlash("SetButtonAction", [buttonAction]);
};

// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
	this.settings.button_cursor = cursor;
	this.callFlash("SetButtonCursor", [cursor]);
};

/* *******************************
	Flash Event Interfaces
	These functions are used by Flash to trigger the various
	events.
	
	All these functions a Private.
	
	Because the ExternalInterface library is buggy the event calls
	are added to a queue and the queue then executed by a setTimeout.
	This ensures that events are executed in a determinate order and that
	the ExternalInterface bugs are avoided.
******************************* */

SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop
	
	if (argumentArray == undefined) {
		argumentArray = [];
	} else if (!(argumentArray instanceof Array)) {
		argumentArray = [argumentArray];
	}
	
	var self = this;
	if (typeof this.settings[handlerName] === "function") {
		// Queue the event
		this.eventQueue.push(function () {
			this.settings[handlerName].apply(this, argumentArray);
		});
		
		// Execute the next queued event
		setTimeout(function () {
			self.executeNextEvent();
		}, 0);
		
	} else if (this.settings[handlerName] !== null) {
		if (SWFUpload.debug) throw "Event handler " + handlerName + " is unknown or is not a function";
	}
};

// Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop

	var  f = this.eventQueue ? this.eventQueue.shift() : null;
	if (typeof(f) === "function") {
		f.apply(this);
	}
};

// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
	var reg = /[$]([0-9a-f]{4})/i;
	var unescapedPost = {};
	var uk;

	if (file != undefined) {
		for (var k in file.post) {
			if (file.post.hasOwnProperty(k)) {
				uk = k;
				var match;
				while ((match = reg.exec(uk)) !== null) {
					uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
				}
				unescapedPost[uk] = file.post[k];
			}
		}

		file.post = unescapedPost;
	}

	return file;
};

// Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
SWFUpload.prototype.testExternalInterface = function () {
	try {
		return this.callFlash("TestExternalInterface");
	} catch (ex) {
		return false;
	}
};

// Private: This event is called by Flash when it has finished loading. Don't modify this.
// Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
SWFUpload.prototype.flashReady = function () {
	// Check that the movie element is loaded correctly with its ExternalInterface methods defined
	var movieElement = this.getMovieElement();

	if (!movieElement) {
		this.debug("Flash called back ready but the flash movie can't be found.");
		return;
	}

	this.cleanUp(movieElement);

	this.queueEvent("swfupload_loaded_handler");
};

// Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
// This function is called by Flash each time the ExternalInterface functions are created.
SWFUpload.prototype.cleanUp = function (movieElement) {
	// Pro-actively unhook all the Flash functions
	try {
		if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
			for (var key in movieElement) {
				try {
					if (typeof(movieElement[key]) === "function") {
						movieElement[key] = null;
					}
				} catch (ex) {
				}
			}
		}
	} catch (ex1) {
	
	}

	// Fix Flashes own cleanup code so if the SWFMovie was removed from the page
	// it doesn't display errors.
	window["__flash__removeCallback"] = function (instance, name) {
		try {
			if (instance) {
				instance[name] = null;
			}
		} catch (flashEx) {
		
		}
	};

};


/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
	this.queueEvent("file_dialog_start_handler");
};


/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queued_handler", file);
};


/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};

/* Called after the file dialog has closed and the selected files have been queued.
	You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
	this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};

SWFUpload.prototype.uploadStart = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("return_upload_start_handler", file);
};

SWFUpload.prototype.returnUploadStart = function (file) {
	var returnValue;
	if (typeof this.settings.upload_start_handler === "function") {
		file = this.unescapeFilePostParams(file);
		returnValue = this.settings.upload_start_handler.call(this, file);
	} else if (this.settings.upload_start_handler != undefined) {
		if (SWFUpload.debug) throw "upload_start_handler must be a function";
	}

	// Convert undefined to true so if nothing is returned from the upload_start_handler it is
	// interpretted as 'true'.
	if (returnValue === undefined) {
		returnValue = true;
	}
	
	returnValue = !!returnValue;
	
	this.callFlash("ReturnUploadStart", [returnValue]);
};



SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};

SWFUpload.prototype.uploadError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};

SWFUpload.prototype.uploadComplete = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_complete_handler", file);
};

/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
   internal debug console.  You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
	this.queueEvent("debug_handler", message);
};


/* **********************************
	Debug Console
	The debug console is a self contained, in page location
	for debug message to be sent.  The Debug Console adds
	itself to the body if necessary.

	The console is automatically scrolled as messages appear.
	
	If you are using your own debug handler or when you deploy to production and
	have debug disabled you can remove these functions to reduce the file size
	and complexity.
********************************** */
   
// Private: debugMessage is the default debug_handler.  If you want to print debug messages
// call the debug() function.  When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
	if (this.settings.debug) {
		var exceptionMessage, exceptionValues = [];

		// Check for an exception object and print it nicely
		if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
			for (var key in message) {
				if (message.hasOwnProperty(key)) {
					exceptionValues.push(key + ": " + message[key]);
				}
			}
			exceptionMessage = exceptionValues.join("\n") || "";
			exceptionValues = exceptionMessage.split("\n");
			exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
			SWFUpload.Console.writeLine(exceptionMessage);
		} else {
			SWFUpload.Console.writeLine(message);
		}
	}
};

SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
	var console, documentForm;

	try {
		console = document.getElementById("SWFUpload_Console");

		if (!console) {
			documentForm = document.createElement("form");
			document.getElementsByTagName("body")[0].appendChild(documentForm);

			console = document.createElement("textarea");
			console.id = "SWFUpload_Console";
			console.style.fontFamily = "monospace";
			console.setAttribute("wrap", "off");
			console.wrap = "off";
			console.style.overflow = "auto";
			console.style.width = "700px";
			console.style.height = "350px";
			console.style.margin = "5px";
			documentForm.appendChild(console);
		}

		console.value += message + "\n";

		console.scrollTop = console.scrollHeight - console.clientHeight;
	} catch (ex) {
		alert("Exception: " + ex.name + " Message: " + ex.message);
	}
};
;

/* file-end: js/swfupload/swfupload.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/swfupload/swfobject.js 
*/

/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();;

/* file-end: js/swfupload/swfobject.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/swfupload/swfupload.queue.js 
*/

/*
	Queue Plug-in
	
	Features:
		*Adds a cancelQueue() method for cancelling the entire queue.
		*All queued files are uploaded when startUpload() is called.
		*If false is returned from uploadComplete then the queue upload is stopped.
		 If false is not returned (strict comparison) then the queue upload is continued.
		*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
		 Set the event handler with the queue_complete_handler setting.
		
	*/

var SWFUpload;
if (typeof(SWFUpload) === "function") {
	SWFUpload.queue = {};
	
	SWFUpload.prototype.initSettings = (function (oldInitSettings) {
		return function () {
			if (typeof(oldInitSettings) === "function") {
				oldInitSettings.call(this);
			}
			
			this.queueSettings = {};
			
			this.queueSettings.queue_cancelled_flag = false;
			this.queueSettings.queue_upload_count = 0;
			
			this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
			this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
			this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
			this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
			
			this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
		};
	})(SWFUpload.prototype.initSettings);

	SWFUpload.prototype.startUpload = function (fileID) {
		this.queueSettings.queue_cancelled_flag = false;
		this.callFlash("StartUpload", [fileID]);
	};

	SWFUpload.prototype.cancelQueue = function () {
		this.queueSettings.queue_cancelled_flag = true;
		this.stopUpload();
		
		var stats = this.getStats();
		while (stats.files_queued > 0) {
			this.cancelUpload();
			stats = this.getStats();
		}
	};
	
	SWFUpload.queue.uploadStartHandler = function (file) {
		var returnValue;
		if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
			returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
		}
		
		// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
		returnValue = (returnValue === false) ? false : true;
		
		this.queueSettings.queue_cancelled_flag = !returnValue;

		return returnValue;
	};
	
	SWFUpload.queue.uploadCompleteHandler = function (file) {
		var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
		var continueUpload;
		
		if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
			this.queueSettings.queue_upload_count++;
		}

		if (typeof(user_upload_complete_handler) === "function") {
			continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
		} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
			// If the file was stopped and re-queued don't restart the upload
			continueUpload = false;
		} else {
			continueUpload = true;
		}
		
		if (continueUpload) {
			var stats = this.getStats();
			if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
				this.startUpload();
			} else if (this.queueSettings.queue_cancelled_flag === false) {
				this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
				this.queueSettings.queue_upload_count = 0;
			} else {
				this.queueSettings.queue_cancelled_flag = false;
				this.queueSettings.queue_upload_count = 0;
			}
		}
	};
};

/* file-end: js/swfupload/swfupload.queue.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.fotki.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/core/string.js 
*/

;(function () {
    'use strict';

    LJ.define('LJ.String');

   /**
     * Add leading zeros to number until it will have correct length
     * @param  {*}      str     Any string or value that will be stringified
     * @param  {Number} length  Needed length
     * @param  {String} symbol  Symbol for padding
     * @return {String}         Padded value
     *
     * @example
     * var padded = LJ.string.pad('hello', 8, ' '); // => '   hello';
     */
    LJ.String.pad = function (str, length, symbol) {
        str = str.toString();

        if (typeof length === 'undefined') {
            throw new Error('You should provide padding string length');
        }

        if (typeof symbol === 'undefined') {
            throw new Error('You should provide padding symbol');
        }

        if (str.length >= length) {
            return str;
        }

        while (str.length < length) {
            str = symbol + str;
        }

        return str.length === length ? str : str.slice(-length);
    };

    /**
     * Capitalize string
     * @param  {String} str String to be capitalized
     * @return {String}     Capitalized string
     *
     * @example
     * LJ.String.capitalize('HELLO'); // => "Hello"
     */
    LJ.String.capitalize = function (str) {
        var length;

        if (typeof str !== 'string') {
            throw new Error('You should provide string as argument');
        }

        length = str.length;

        if (length === 0) {
            return str;
        } else if (length === 1) {
            return str.toUpperCase();
        } else {
            return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
        }
    };

    /**
     * Add http:// if not present
     * @param  {String} str Input string
     *
     * @return {String}     Link with default protocol (http://) if needed
     */
    LJ.String.linkify = function(str) {
        var rxLink = new RegExp('^(?:([a-zA-Z]+):)?//'),
            alternative = /^[a-zA-Z]+:/, // mailto:
            rxEmptyProtocol = /^:\/\//;  // ://yandex.ru

        var defaultProtocol = alternative.test(str) ? '' : 'http://';

        return rxLink.test(str) ?
            str :
            defaultProtocol + (rxEmptyProtocol.test(str) ? str.replace('://', '') : str);
    };
}());
;

/* file-end: js/core/string.js 
----------------------------------------------------------------------------------*/

/**
 * @author dmitry.petrov@sup.com (Dmitry Petrov)
 * @fileoverview Library function to deal with new photohosting
 */
(function($) {
  'use strict';

  /**
   * @name $.fotki
   * @namespace Library should encapsulate all operations on photos
   * and albums on the new photos.
   */
  $.fotki = $.fotki || {
    /**
     * @type Boolean
     */
    options: {
      selectors: {
      },
      classNames: {
      },
      urls: {
        sendDataTo: '/__rpc_fotki_imgs?func=update_photos',
        getAlbum: '/__rpc_fotki_imgs?func=get_photos'
      },
      tmpl: {
        htmlImg: '<img alt="{photo_title}" border="0" title="{photo_title}" src="{photo_src}"{size} />',
        linkOpen: '<a href="{photo_link}" target="_blank">',
        linkClose: '</a>'
      }
    },

    _selector: function(name) { return this.options.selectors[name]; },
    _className: function(name) { return this.options.classNames[name]; }
  };

  /** @lends $.fotki */
  $.extend($.fotki, {
    /**
     * Generate array with html markup for photos.
     *
     * @param {Array.Object|Object} data photos data. Function uses only photo_id and photo_title fields. If
     *     param is not an array, we assume, that we should render a single photo, and all data is in this object.
     * @param {string} size Desired size of the photos. The string comes as multiple attributes for img tag.
     * @param {Object=} If data is an array, then this parameter is used and required. Array contains urls
     * of images, keys are photo ids.
     */
    makePhotosHTML: function(data, size, resizedUrls) {
      var resultHtml = [],
          photoData,
          photoTemplate = this.options.tmpl.htmlImg,

          index,
          length,
          html;

      /* single image */
      if ( !data.length ) {
        data.size = size;

        photoData = photoTemplate.supplant(data);

        if (data.hasOwnProperty('photo_link') && data.photo_link !== '') {
          photoData = this.options.tmpl.linkOpen.supplant(data) + photoData + this.options.tmpl.linkClose;
        }
        resultHtml.push(photoData);
        return resultHtml;
      }

      for (index = 0, length = data.length; index < length; index++) {
        photoData = data[index] || {};
        photoData.photo_src = resizedUrls[photoData.photo_id];
        photoData.photo_title = photoData.photo_title || '';
        photoData.size = size;

        html = photoTemplate.supplant(photoData);

        if (photoData.hasOwnProperty('photo_link') && photoData.photo_link !== '') {
          html = this.options.tmpl.linkOpen.supplant(photoData) + html + this.options.tmpl.linkClose;
        }

        resultHtml.push(html);
      }

      return resultHtml;
    },

    /**
     * Updated generator of photos html
     * @param  {Object[]} resizesData       Photos data from server after resizing.
     * @param {Array}     data              Photos data. Contains src and title,
     *                                        Notice: only title is needed
     * @param {Object}    params            Additional params from sizeSelect
     * @param {String}    params.type       Selected value in the sizeList, e.g. 300/custom/original
     * @param {String}    params.attributes String with width and height attributes (for image tag),
     *                                        e.g. "width='300' height='200'"
     *
     * @return {String[]} Array of html strings to insert
     */
    photosHTML: function (resizesData, data, params) {
      var size = 'width="{width}" height="{height}"',
          insertOriginalLink = params.insertOriginalLink,
          imgTmpl = '<img src="{src}" alt="{title}" title="{title}" {attributes} />',
          imgWithLinkTmpl = '<a href="{url}" target="_blank">' + imgTmpl + '</a>';

      return data.map(function (photoData) {
        var id = photoData.photo_id,
            title = photoData.photo_title,
            data = resizesData[id] || {},
            obj;

        obj = {
          id: id,
          title: title,

          // if user provided link - insert it, otherwise check params.insertOriginalLink
          // and insert original image url if needed: #LJSUP-15091
          url: photoData.photo_link || (insertOriginalLink ? data.photo_orig : null),
          src: data.image_url,

          // if type is 'custom' we need to provide attributes from sizeList,
          // not from the server
          attributes: params.type === 'custom' ?
                      params.attributes.trim() :
                      size.supplant({width: data.width, height: data.height})
        };

        if (obj.url) {
          // add protocol to link if it hasn't been provided
          obj.url = LJ.String.linkify(obj.url);
          return imgWithLinkTmpl.supplant(obj);
        } else {
          return imgTmpl.supplant(obj);
        }

        return (obj.url ? imgWithLinkTmpl : imgTmpl).supplant(obj);
      });
    },

    /**
     * Get array of urls of photos with some size. This is a part of fotki API extracted from lj.photouploader.
     *     All the API should be there in the future.
     *
     * @param {Array} photoData Array with photos data. The only used field is photo_id
     * @param {Function} callback Callback is fired, when data comes from the server.
     * @param {string='original'} size The desired size of images.
     */
    getImgUrls: function(photoData, callback, size) {
      var request = {
        type: 'add',
        required_size: size || 'original'
      };

      photoData = photoData || [];
      request.photos_data = photoData.map(function(el) { return { photo_id: el.photo_id}; });

      $.ajax(this.options.urls.sendDataTo, {
        type: 'POST',
        data : {
          data_to_update: JSON.stringify(request)
        },
        dataType: 'json',
        success: function(response) {
          var resizedUrls = response.result;

          if (resizedUrls) {
            callback(resizedUrls);
          }
        }
      });
    },

    /**
     * Get array of photos from specified album.
     *
     * @param {number} album_id Album id.
     * @param {Function} callback Callback is fired, when data comes from the server.
     * @param {number=} offset The offset to count the photos in the album. Default is 0.
     * @param {string='original'} size The desired size of images.
     * @param {number=} count The number of photos to retrieve.
     */
    getAlbumContents: function(album_id, callback, offset, size, count) {
      var request = {
        album_id: parseInt(album_id, 10) || 0
      };

      if (arguments.length >= 3) {
        request.start = parseInt(offset, 10) || 0;
      }

      if (arguments.length >= 4) {
        request.required_size = size;
      }

      if (arguments.length >= 5) {
        request.count = parseInt(count, 10) || 0;
      }

      $.ajax(this.options.urls.getAlbum, {
        type: 'GET',
        data : request,
        dataType: 'json',
        success: callback
      });
    }
  });

}(jQuery));
;

/* file-end: js/jquery/jquery.fotki.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/jquery/fotki/jquery.lj.sizeSelect.js 
*/

;(function($) {
	"use strict";

	var ml = LJ.ml;

	$.widget( 'lj.sizeSelect', $.lj.basicWidget, {
		options: {
			render: true, //if flag is false then component tries to build markup by itself

			selectors: {
				sizeList: '.b-pics-size-list',
				customSizeList: '.b-pics-custom-options',
				customWidthField: '#image-width',
				customHeightField: '#image-height',
				backToDefaultSize: '.b-pics-back-to-default'
			},

			classNames: {
				container: 'b-pics-side-options'
			},

			tmpl: {
				header: '<label for="select-resize" class="b-pics-size-label">{fotki.album.resize.to.post}</label>' + 
							'<select class="b-pics-size-list select-resize">',
				common: '<option value="{size}">{text}</option>',
				selected: '<option selected="selected" value="{size}">{text}</option>',
				last: '<option value="{size}">{text}</option>{text}</option>',
				footer: '</select>' +
					'<div class="b-pics-custom-options">' +
						'<input id="image-width" class="b-pics-input-custom-text text-field" type="text" placeholder="{fotki.album.resize.width}" />' +
						'<input id="image-height" class="b-pics-input-custom-text text-field" type="text" placeholder="{fotki.album.resize.height}" />' +
						'<a class="b-pics-back-to-default" href="#">{fotki.album.default.sizes}</a>' +
					'</div>'
			},

			ml: {
				resize: 'fotki.album.custom.size'
			},

			// predefined sizes from server
			sizeData: [],
			// current value
			value: 'original',
			// default value that will be set on reset
			defaultValue: 'original'
		},

		_create: function() {
			var that = this;
			$.lj.basicWidget.prototype._create.call( this );

			// list of available sizes
			this._sizes = [];

			// save predefined sizes
			this.options.sizesData.forEach(function ( sizeData ) {
				var size = sizeData.size.toString();
				that._sizes.push( size );
				if ( sizeData.is_default ) {
					that.options.defaultValue = size;
				}
			});

			// add 'custom' size to the list of available sizes
			this._sizes.push('custom');

			if (this.options.render) {
				this._createNodes();
			}

			this.element.addClass( this._cl('container') );
			this._el('customWidthField').labeledPlaceholder();
			this._el('customHeightField').labeledPlaceholder();

			this._bindControls();
			this.reset();
		},

		_createNodes: function() {
			var that = this,
				tmpl = this.options.tmpl,
				sizeList = [];

			// header
			sizeList.push(tmpl.header);
			// list items
			sizeList.push(
				this.options.sizesData.map(function (sizeData) {
					return tmpl[sizeData.is_default ? 'selected' : 'common'].supplant(sizeData);
				})
			);
			// last, <custom> list item
			sizeList.push(
				tmpl.last.supplant({
					text: this._ml('resize'),
					size: 'custom'
				})
			);
			// footer
			sizeList.push(tmpl.footer);
			this.element.html(sizeList.join(' ').supplant(Site.ml_text));
		},

		_bindControls: function() {
			$.lj.basicWidget.prototype._bindControls.call( this );

			this.element.on('change', this._s('sizeList'), this._change.bind(this));
			this.element.on('click', this._s('backToDefaultSize'), this._backFromCustom.bind(this));
		},

		/**
		 * Reset widget state to default
		 */
		reset: function() {
			this._clearCustomFields();
			this._setOption('value', 'default');
		},

		/**
		 * Set currently selected value as default
		 */
		updateDefault: function () {
			this._setOption('defaultValue', this.options.value);
		},

		/**
		 * Currently selected value in the list
		 */
		selectedValue: function() {
			return this.options.value;
		},

		/**
		 * Width and heght attributes string
		 * @return {String} String with width/height attributes for image, or empty string (if width/height is empty)
		 */
		attributes: function () {
			var width,
				height,
				result,
				value = this.options.value;

			if (value === 'custom') {
				width = $.trim( this._el('customWidthField').val() );
				height = $.trim( this._el('customHeightField').val() );
				result = width.length === 0 || isNaN(width) ? '' : ' width="' + width + '"';
				result += height.length === 0 || isNaN(height) ? '' : ' height="' + height + '"';
			} else {
				result = isNaN(value) ? '' : ' width="' + value + '"';
			}

			return result;
		},

		/**
		 * Size list change handler
		 * @param  {Object} e jQuery event object
		 */
		_change: function (e) {
			this._setOption('value', $(e.target).val());
		},

		/**
		 * Back to default size link click handler
		 * @param  {Object} e jQuery event object
		 */
		_backFromCustom: function (e) {
			e.preventDefault();
			this._setOption('value', 'original');
		},

		/**
		 * Reset custom width and height fields
		 */
		_clearCustomFields: function () {
			this._el('customWidthField').val('');
			this._el('customHeightField').val('');
		},

		/**
		 * Set value for the select box
		 * @param {String} value Value to be selected
		 */
		_setValue: function (value) {
			if (value === 'custom') {
				this._el('sizeList').hide();
				this._el('customSizeList').css('display', 'inline-block');
			} else {
				this._el('sizeList').val(value);
				// hide custom fields, if custom has been set before
				if (this.options.value === 'custom') {
					this._el('customSizeList').hide();
					this._el('sizeList').show();
				}
			}
			this.options.value = value;
		},

		_setOption: function (key, value) {
			if (value === undefined) {
				return;
			}

			switch (key) {
				case 'value':
					// support default
					if (value === 'default') {
						this._setValue(this.options.defaultValue);
					} else {
						// value should be a string
						value = value.toString();
						this._setValue( this._sizes.indexOf( value ) === -1 ? 'original' : value);
					}
					break;

				case 'defaultValue':
					// value should be a string
					value = value.toString();
					// Notice: defaultValue can't be set to custom.
					// If it's custom, it should be set to 'original'
					this.options.defaultValue = value === 'custom' || this._sizes.indexOf( value ) === -1 ? 'original' : value;
					break;
			}
		}
	});
}(jQuery));

;

/* file-end: js/jquery/fotki/jquery.lj.sizeSelect.js 
----------------------------------------------------------------------------------*/

/*global SWFUpload, swfobject */

/**
 * @author sergey.zhirkov@sup.com, b-vladi@cs-console.ru, dmitry.petrov@sup.com (Dmitry Petrov)
 * @fileoverview Upload photos dialog.
 */

/**
 * @name $.lj.photouploader
 * @requires $.ui.core, $.ui.widget, $.ui.sortable, $.lj.bubble, $.fotki, $.lj.sizeSelect.js,
 *  swfupload.js (http://demo.swfupload.org/Documentation/),
 *  swfobject.js
 * @class Photouploader widget. Widget is responsible for dealing with popup.
 * @example
 *  &lt;div class="with-page-content"&gt;
 *    ...
 *    &lt;a href="#" class="upload-control"&gt;Upload&lt;/a&gt;
 *  &lt;/div&gt;
 *  &lt;script&gt;
 *    $('div.with-page-content')
 *      .photouploader({
 *        selectors: {
 *          uploadButton: 'a.upload-control'
 *        }
 *      })
 *  &lt;/script&gt;
 *
 */
;(function($, window) {
  'use strict';

  /** @lends $.lj.photouploader.prototype */
  $.widget('lj.photouploader', {

    options: {
      // show link to original checkbox and field for url after uploading
      showLinkFields: true,

      // data that comes from server (in template)
      availableSpace: null,
      albumsData: null,
      sizesData: null,
      guid: null,
      state: 'begin', // 'begin' || 'processing' || 'end'
      _hideUploadTab: 'upload', // 'upload' || 'add' || 'paste' || 'list'
      progress: 0,
      showOn: false, // 'load' || false

      // if "true" will request required size of images from server and trigger
      // 'htmlready' event on element with html output (including "img" tags)
      htmlOutput: true,

      tracking_opendialog: '',
      tracking_photouploaded: '',

      urls: {
        uploadImagesTo: 'http://' + Site.picsUploadDomain + '/' + Site.remoteUser,
        uploaderSWF: Site.siteroot + '/js/swfupload/swfupload.swf',
        uploaderImage: Site.siteroot + '/img/buttons/browse.png?v=16958',
        spinnerImage: Site.siteroot + '/img/buttons/spinner.png?v=16898',
        sendDataTo: '/__rpc_fotki_imgs?func=update_photos',
        siteRoot: Site.siteroot
      },

      selectors: {
        faderNode: 'div.b-fader',

        popupContainer: 'body',
        closeControl: 'i.i-popup-close',

        headers: 'div.b-popup-state-container h2',

        uploadButton: '.b-pics-upload-control',
        postButton: '.b-pics-post-button',
        saveButton: '.b-pics-save-button',
        removeButton: '.i-thumb-close',
        addImagesControl: 'div.click-upload div',
        dataForm: '.b-pics-data-form',
        itemCheckbox: '#photo_cb_{id}',

        stateContainer: 'div.b-popup-state-container',
        uploadProgress: 'div.b-pics-upload',
        progressBar: 'div.b-pics-upload-progress-bar-inner',
        currentCounter: 'span.b-pics-current-image',
        totalCounter: 'span.b-pics-total-images',
        imageFilename: 'p.b-pics-upload-filename',

        pasteImageUrl: '#paste-image-url',
        pasteImageLink: '#paste-image-link',
        pasteImagePreview: 'span.b-pics-preview-pic',

        photoListWrapper: 'div.b-popup-pics-gallery',
        photoList: 'ul.b-popup-pics-gallery-list',
        listItem: 'li.pics-item-list',
        listNoPhotos: '.b-popup-pics-gallery-nophotos',
        firstSelectedListItem: 'li.pics-item-list > input:checked:first',
        uploadedItem: 'ul.b-popup-pics-gallery-list li.pics-item-upload',
        insertedItem: 'ul.b-popup-pics-gallery-list li.b-popup-pics-inserted',

        titleField: '.b-pics-title-field',
        descField: '.b-pics-desc-field',
        linkField: '.b-pics-link-field',

        albumCoverCheckbox: '.b-pics-checkbox input',
        newAlbumField: '.b-pics-submit-options .b-pics-input-text-album-name',
        newAlbumFieldWrapper: '.b-pics-submit-options .input-album-name-wrapper',
        albumList: '.b-pics-submit-options .b-pics-select',
        cancelCreateAlbumBtn: '.input-album-name-wrapper span.b-pics-decline-new-album',
        sizeList: '.b-pics-size-options',
        listPageAlbumList: '.b-pics-header-select-album .b-pics-select',
        // backToDefaultSize: '.b-pics-back-to-default',

        privacyBubble: '.b-pics-privacy-inner',
        privacyControl: '.b-pics-privacy-icon',
        privacyGroup: 'li',
        privacyIcon: '.b-pics-privacy-icon',

        preloaderElem: '.b-pics-preloader',

        availableNow: '.b-pics-available-now',

        uploadHeader: '.b-popup-pics-upload-header'
      },

      classNames: {
        statePrefix: 'b-pics-state-',
        typePrefix: 'b-popup-pics-',
        headerSuffix: '-header',
        withHtmlOutput: 'b-pics-with-output',
        withoutHtmlOutput: 'b-pics-without-output',
        showPasteOnly: 'b-popup-pics-paste-only',
        selectedItem: 'selected',
        currentTab: 'current-state',
        insertPhotosCountPrefix: 'b-popup-pics-add-',
        preloader: 'b-pics-preloader-visible',
        listPreloader: 'b-popup-pics-loading-more',
        privacy: {
          'allfriends': 'b-pics-privacy-icon-fr',
          'basic': 'b-pics-privacy-icon',
          'public': 'b-pics-privacy-icon-pb',
          'friends_': 'b-pics-privacy-icon-gr',
          'private': 'b-pics-privacy-icon-pr'
        },
        hideFirst : 'b-popup-pics-list-first',
        secondTab: 'b-popup-pics-list',
        firstTab: 'b-popup-pics-upload',
        stateBegin: 'b-pics-state-begin',
        showLinkFields: 'b-popup-pics-links'
      },

      templates: {
        photouploader: 'templates-Widgets-photouploader-photouploader',
        insertedItem: 'templates-Widgets-photouploader-insertedItem',
        uploadedItem: 'templates-Widgets-photouploader-uploadedItem',

        clickToUploadMessage: '<span class="click-upload-inner">{fotki.album.link.click.to.upload}</span>',
        uploadingMessage: '<span class="click-upload-inner">{fotki.album.uploading.message}</span>',
        previewImg: '<img src="{src}" class="b-pics-preview-image" />',
        fader: '<div class="b-fader" style="display: none;"></div>',
        albumList: {
          header: '<select class="b-pics-select">',
          empty: '<option></option>',
          common: '<option value="{album_id}">{album_title}</option>',
          selected: '<option value="{album_id}" selected="selected">{album_title}</option>',
          last: '<option>{fotki.album.create.new}</option>',
          footer: '</select>'
        },
        privacyList: {
          header: '<ul>',
          common: '<li data="{security}">{groupname}</li>',
          selected: '<li data="{security}" class="active">{groupname}</li>',
          footer: '</ul>'
        }
      }
    },


    // private methods

    _create: function() {
      var options = this.options;

      // store language vars that comes from server
      options.ml = Site.ml_text;

      // max-height of photos wrapper block. Will be calculated on photouploader show
      this._wrapperMaxHeight = null;

      this._hasFlash = ( (typeof swfobject === 'object') && swfobject.hasFlashPlayerVersion('9') );

      //this flag is used only on the list tab
      this._currentGalleryId = null;
      this._listPhotosById = [];

      this._makeNode();

      this.reset();

      //we show only paste url dialog if user has basic account or migration has not finished yet
      this._pasteOnly = ('ljphotoEnabled' in window) && (!window.ljphotoEnabled ||
        window.ljphotoMigrationStatus !== LJ.getConst('LJPHOTO_MIGRATION_FINISHED') ||
        !window.ljphotoUploadEnabled);

      if (options.type === 'upload') {
        this._initSWFUpload();

        /*
         * Fix for IE9
         * After swfupload initialization $.noData.object contains string
         */
        $.noData['object'] = true;
      }

      // set base options
      this._setOptions(options);
      this._bindEvents();

      if (options.showOn === 'load') {
        this.show();
      }

      // if flash is not available, remove first tab

      if ( !this._hasFlash ) {
        this._hideUploadTab();
      }

      this._initDropbox();
    },

    _initDropbox: function() {
      var photouploader = this,
        header = $('.b-popup-pics-dropbox');

      // Hide tab if we are not on update page
      if (!Site.page.fotki) {
        header.hide();
        return;
      }

      header.find('.b-pics-tab-dropbox').on('click', function() {
        if (!window.Dropbox) {
          LJ.dialogs.alert(LJ.ml('fotki.album.dropbox.error'));
          return;
        }

        if (!window.Dropbox.isBrowserSupported()) {
          LJ.dialogs.alert(LJ.ml('fotki.album.dropbox.not_supported'));
          return;
        }

        LJ.Track.event('Photouploader', 'Dropbox', 'Click');

        window.Dropbox.choose({
          linkType: 'preview',
          multiselect: true,

          success: function(files) {
            photouploader.element.trigger({
              type: 'htmlready',
              htmlStrings: files.map(function(file) {
                return '<img src="{url}">'.supplant({
                  url: file.link.replace('www.dropbox.com', 'dl.dropboxusercontent.com')
                });
              })
            });
            photouploader.hide();

            LJ.Track.event('Photouploader', 'Dropbox', 'Success');
          }
        });
      });

      LiveJournal.injectScript('https://www.dropbox.com/static/api/1/dropins.js').done(function() {
        if (window.Dropbox) {
          window.Dropbox.appKey = '7ye0n6mhwlsdh9u';
        }
      });
    },

    _hideUploadTab: function() {
      var cl = this.options.classNames;

      jQuery( this.options.selectors.uploadHeader ).css({ display: 'none' });
      this._stateContainer.removeClass( cl.firstTab ).addClass( cl.secondTab ).removeClass( cl.stateBegin );
    },

    _initSWFUpload: function() {
      var options = this.options,
        element = this.element,
        templates = options.templates,
        urls = options.urls;

      templates.clickToUploadMessage = templates.clickToUploadMessage.supplant(options.ml);
      templates.uploadingMessage = templates.uploadingMessage.supplant(options.ml);

      this._flashUploader = new SWFUpload({
          post_params: {
            form_auth: options.guid
          },
          upload_url: urls.uploadImagesTo,
          flash_url: urls.uploaderSWF,
          button_placeholder: this._addImagesControl.get(0),
          button_width: 141,
          button_height: 33,
          button_cursor: SWFUpload.CURSOR.HAND,
          button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
          button_text: '',
          prevent_swf_caching: false,

          file_types: '*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.tif;*.tiff',

          file_queued_handler: function() {
            var counters = {
                totalIndex: this.getStats().files_queued,
                currentIndex: 1
              };

            element.trigger('fileQueued', counters);
          },

          upload_start_handler: function(file) {
            var filename = file.name;

            element.trigger('uploadStart', filename);
          },

          upload_progress_handler: function(file, bytesLoaded, bytesTotal) {
            var percent = Math.ceil((bytesLoaded / bytesTotal) * 90) + '%';

            element.trigger('uploadProgress', percent);
          },

          upload_error_handler: function(file, errorCode, message) {
            var errorMessage = '';

            if (errorCode == '-220') {
              errorMessage = options.ml['fotki.album.upload.io.error'];
            } else {
              errorMessage = options.ml['fotki.album.upload.unknown.error'] +
                ': ' + errorCode + ', ' + message;
            }

            element.trigger('uploadProgress', '95%');
            element.trigger('fileUploaded', {
              status: 'error',
              result: errorMessage
            });
          },

          upload_success_handler: function(file, serverData) {
            // cut off the extra information about chunks
            var responseBody = serverData.match(/\{.*\}/);

            element.trigger('uploadProgress', '95%');

            if (responseBody) {
              serverData = responseBody[0];
              serverData = $.parseJSON(serverData);

              // filename without extension
              serverData.photo_title = file.name.match(/(.*?)\.[^\.]*$/)[1];

              element.trigger('fileUploaded', serverData);
            } else {
              element.trigger('fileUploaded', {
                status: 'error',
                result: options.ml['fotki.album.upload.unknown.error'] +
                  ': \n' + serverData
              });
            }

          }
        });
    },

    _makeNode: function() {
      var options = this.options,
        selectors = options.selectors,
        templates = options.templates,

        albumListTemplate = templates.albumList,
        albumList = [],
        albumsData = options.albumsData,
        currentAlbumId = options.albumId,

        privacyList = [],
        privacyData = options.privacyData,
        privacyListTemplate = templates.privacyList,
        groupTemplate = privacyListTemplate.common,
        group,

        popupNode, faderNode,
        i,l;

      if (options.type === 'upload') {
        albumList.push(albumListTemplate.header, albumListTemplate.footer);

        privacyList.push(privacyListTemplate.header);

        for (i = 0, l = privacyData.length; i < l; i++) {
          groupTemplate = (i === 0) ? privacyListTemplate.selected : privacyListTemplate.common;
          group = groupTemplate.supplant(privacyData[i]);
          privacyList.push(group);
        }

        privacyList.push(privacyListTemplate.footer);
      }

      faderNode = $(templates.fader).prependTo('body');

      // LJSUP-9765: An fascinaging opera bug - if the script is called inside the form and attempts to build
      // DOM through innerHTML field than it will strip form elements with the first call. The second
      // try will produce correct results.
      // Last checked in Opera 11.10 for linux, opera bug DSK-346265
      if (jQuery.browser.opera) {
        jQuery('<div><form></form></div>');
      }

      popupNode = LJ.UI.template(this.options.templates.photouploader, {
        showLinkFields: this.options.showLinkFields,
        albumList: albumList.join(' '),
        privacyList: privacyList.join(' '),
        availableSpace: options.availableSpace,
        siteRoot: options.urls.siteRoot,
        addToPostButtonText: LJ.ml(
          LJ.get('comments_page') ? 'fotki.album.comment.images' : 'fotki.album.post.images'
        )
      })
      .prependTo(selectors.popupContainer);

      this._closeControl = popupNode.find(selectors.closeControl);

      this._progressBar = popupNode.find(selectors.progressBar);
      this._addImagesControl = popupNode.find(selectors.addImagesControl);
      this._currentCounter = popupNode.find(selectors.currentCounter);
      this._totalCounter = popupNode.find(selectors.totalCounter);
      this._uploadProgress = popupNode.find(selectors.uploadProgress);
      this._imageFilename = popupNode.find(selectors.imageFilename);
      this._stateContainer = popupNode.find(selectors.stateContainer);
      this._photoListWrapper = popupNode.find(selectors.photoListWrapper);
      this._photoList = this._photoListWrapper.find(selectors.photoList);
      this._photoListNoPhotos = this._photoListWrapper.find(selectors.listNoPhotos);

      this._pasteImageUrl = popupNode.find(selectors.pasteImageUrl);
      this._pasteImageLink = popupNode.find(selectors.pasteImageLink);
      this._pasteImagePreview = popupNode.find(selectors.pasteImagePreview);

      this._titleField = popupNode
        .find(selectors.titleField)
          .labeledPlaceholder();

      this._descField = popupNode
        .find(selectors.descField)
          .labeledPlaceholder();

      this._linkField = popupNode
        .find(selectors.linkField)
        .labeledPlaceholder();

      this._newAlbumField = popupNode
        .find(selectors.newAlbumField)
          .labeledPlaceholder();

      this._newAlbumFieldWrapper = popupNode
        .find(selectors.newAlbumFieldWrapper);

      this._albumCoverCheckbox = popupNode.find(selectors.albumCoverCheckbox);

      this._albumList = popupNode.find(selectors.albumList);
      this._cancelCreateAlbumBtn = popupNode.find(selectors.cancelCreateAlbumBtn);

      this._listPageAlbumList = popupNode.find(selectors.listPageAlbumList);
      this._listPageAlbumList.html(this._getAlbumsData(options.albumsData));

      if (options.htmlOutput) {
        this._sizeList = popupNode.find(selectors.sizeList).sizeSelect({
          sizesData: options.sizesData
        });
      }

      this._customWidthField = popupNode
        .find(selectors.customWidthField)
        .labeledPlaceholder();

      this._customHeightField = popupNode
        .find(selectors.customHeightField)
        .labeledPlaceholder();

      // this._backToDefaultSize = popupNode.find(selectors.backToDefaultSize);
      this._preloaderElem = popupNode.find(selectors.preloaderElem);

      this._availableNow = popupNode.find(selectors.availableNow);

      this._privacyIcon = popupNode.find(selectors.privacyIcon);
      this._privacyBubble = popupNode.find(selectors.privacyBubble)
        .bubble({
          target: popupNode.find(selectors.privacyControl),
          showOn: 'click'
        });
      this._privacyGroups = this._privacyBubble.find(selectors.privacyGroup);

      // TODO: create universal function with loop to remove this HELL

      if (currentAlbumId || albumsData.length) {
        this._newAlbumFieldWrapper.hide();
      }

      this._popupNode = popupNode;
      this._faderNode = faderNode;

      this._originalLinkCheckbox = popupNode.find('#link-original');
    },

    /**
    * Adds items from array to photo list
    *
    * @param {Array} items
    */
    _addItems: function(items) {
      for (var i = 0, l = items.length; i < l; i++) {
        this.addItem(items[i]);
      }
    },

    /**
     * Load the gallery in the paste from gallery tab. The photos are not
     * cached now, so it can be improved in future.
     *
     * @param {string} album_id Album id.
     */
    _fillGallery: function(album_id) {
      var selectors = this.options.selectors;

      if (this._currentGalleryId !== album_id) {
        this._photoList.find(selectors.listItem).remove();
        this._currentGalleryId = album_id;
        this._listPhotosById = [];
        this._currentGalleryOffset = 0;
        this._currentGalleryLoading = false;
        this._currentGalleryFull = false;
        this._photoListNoPhotos.hide();
        this._fetchGallery();
      }
    },

    /**
     * Fetch more items in the list for current gallery. The function takes the
     * data from the _currentGalleryId, currentGalleryOffset to fetch the required
     * photos.
     */
    _fetchGallery: function() {
      var self = this,

          // Notice:
          // count is hardcoded and based on current amount if photos in a row: 5
          // and current photo item outer height: 151px
          countBasedOnWrapperSize = ( Math.floor( this._wrapperMaxHeight / 151 ) + 1 ) * 5,

          // 20 photos - min amount of photos to fetch
          count = Math.max(20, countBasedOnWrapperSize);

      if (this._currentGalleryLoading) {
        return;
      }

      this._currentGalleryLoading = true;
      this._stateContainer.addClass(this.options.classNames.listPreloader);


      $.fotki.getAlbumContents(this._currentGalleryId, function(items) {
        if (self.options.type !== 'list') { return; } //do not insert anything if we are in another tab

        self._currentGalleryLoading = false;
        self._currentGalleryOffset += items.length;
        self._stateContainer.removeClass(self.options.classNames.listPreloader);

        if (items.length === 0) {
          self._currentGalleryFull = true;

          if (self._currentGalleryOffset === 0) {
            self._photoListNoPhotos.show();
          }
        }

        self._addItems(items);
      }, this._currentGalleryOffset, 100, count);
    },

    _setOption: function(option, value) {
      var photouploader = this,
        options = this.options,
        classNames = options.classNames,
        statePrefix = classNames.statePrefix,
        insertPhotosLength, insertPhotosCount,
        html, albumListTemplate;

      switch (option) {
        case 'type':
          if (value === 'upload' && this._pasteOnly) {
            value = 'paste';
          }

          this._stateContainer
            .removeClass(classNames.typePrefix + options.type)
            .addClass(classNames.typePrefix + value);
          this._photoListNoPhotos.hide();

          switch (value) {
            case 'list':
              this._stateContainer
                .removeClass(classNames.statePrefix + options.state)
                .removeClass(classNames.listPreloader);

              this._fillGallery(this._listPageAlbumList.val());
              this._photoList.sortable('enable');
              break;

            case 'add':
              options.type = value;

              this._stateContainer.removeClass(classNames.statePrefix + options.state);
              this._setOption('htmlOutput', true);

              insertPhotosLength = options.insertPhotosData.length;

              if (insertPhotosLength === 1) {
                insertPhotosCount = 'one';
              } else if (insertPhotosLength > 1 && insertPhotosLength < 5) {
                insertPhotosCount = 'several';
              } else {
                insertPhotosCount = 'many';
              }

              this._setOption('insertPhotosCount', insertPhotosCount);
              this._addItems(options.insertPhotosData);
              this._photoList.sortable('refresh');
              if (insertPhotosLength > 1) {
                this._photoList.sortable('enable');
              }
              break;

            case 'upload':
              this._stateContainer.addClass(classNames.statePrefix + options.state);
              this._stateContainer
                .removeClass(classNames.insertPhotosCountPrefix + options.insertPhotosCount);
              break;

            case 'paste':
              if (this.options.type === 'upload') {
                if (this.options.state === 'processing') {
                  if (confirm(this.options.ml['fotki.album.stop.upload'])) {
                    this._flashUploader.cancelQueue();
                    this._setOption('state', 'end');
                  } else {
                    return this;
                  }
                }
              }

              if (this._pasteOnly) {
                this._stateContainer
                  .addClass(classNames.showPasteOnly);
              }

              break;
          }

          this.options.type = value;

          // only for pages with available sizeList selector
          // Notice: sizelist is not available on scrapbook, for example
          if (this._sizeList) {
            // update state of size selector
            // when we are in 'paste' mode - we should set 'original' value, and 'default' otherwise
            this._sizeList.sizeSelect('option', 'value', value === 'paste' ? 'original' : 'default');
          }

          break;

        case 'availableNow':
          this._availableNow.text(value);
          break;

        case 'insertPhotosCount':
          this._stateContainer
            .removeClass(classNames.insertPhotosCountPrefix + options.insertPhotosCount)
            .addClass(classNames.insertPhotosCountPrefix + value);
          break;

        case 'state':
          this._stateContainer.removeClass(statePrefix + options.state);
          options.state = value;

          if (options.type === 'upload') {
            switch (value) {
              case 'processing':
                this._flashUploader.setButtonDisabled(true);
                this._photoList.children().removeClass(classNames.selectedItem);
                photouploader.element.trigger({
                  type: 'uploading'
                });
                break;

              case 'end':
                this._flashUploader.setButtonDisabled(false);
                this._flashUploader.setButtonText(options.templates.buttonText);
                photouploader.element.trigger({
                  type: 'endupload'
                });

                if (this._changedPhotosById.length) {
                  this.index('last');
                } else {
                  value = 'begin';
                }
                break;
            }
          }

          this._stateContainer.addClass(statePrefix + value);
          break;

        case 'htmlOutput':
          this._stateContainer
            .toggleClass(classNames.withHtmlOutput, value)
            .toggleClass(classNames.withoutHtmlOutput, !value);
          break;

        case 'activeItem':
          if (options.activeItem) {
            options.activeItem.removeClass(options.classNames.selectedItem);
          }

          this._setOption('activeImg', value.find('img'));
          this._setOption('activeIndex', this._getIndex(value));

          if (options.state === 'end') {
            value.addClass(options.classNames.selectedItem);
            this.load();
          }
          break;

        case 'coverItem':
          if (value) {
            if (options.coverItem) {
              // remove old album cover
              this._changedPhotosById[ this._getIndex(options.coverItem) ].is_cover = 0;
            }
            // store new album cover
            this._changedPhotosById[ this._getIndex(value) ].is_cover = 1;
          }
          break;

        case 'showLinkFields':
          this._stateContainer
            .toggleClass( this.options.classNames.showLinkFields, value );
          break;

        case 'totalIndex':
          this._totalCounter.text(value);
          break;

        case 'currentIndex':
          if (value > options.totalIndex) {
            photouploader.element.one('thumbnailLoaded', function() {
              photouploader.element.trigger('uploadFinished');
            });
          } else {
            this._currentCounter.text(value);
          }
          break;

        case 'progress':
          if (!value) {
            this._progressBar.stop();
            this._progressBar.width(0);
          } else if (value > options.progress) {
            this._progressBar.stop();
            this._progressBar.animate({
              'width': value + '%'
            }, 'slow');
          }
          break;

        case 'filename':
          this._imageFilename.text(value);
          break;

        case 'albumsData':
          albumListTemplate = options.templates.albumList;

          html = this._getAlbumsData(value, options.albumId) +
            albumListTemplate.last.supplant(options.ml);

          this._albumList.html(html);
          break;
      }

      options[option] = value;
    },

    _getAlbumsData: function(data, selected) {
      var albumData,
        html = '',
        albumListTemplate = this.options.templates.albumList,
        commonAlbum = albumListTemplate.common,
        selectedAlbum = albumListTemplate.selected,
        i, l;

      selected = selected || null;

      for (i = 0, l = data.length; i < l; i++) {
        albumData = data[i];
        if (albumData.album_id === selected || (!selected && i === 0)) {
          html += selectedAlbum.supplant(albumData);
        } else {
          html += commonAlbum.supplant(albumData);
        }
      }

      return html;
    },

    /**
    * Saves changes in certain photo propery (stores it in a hash object)
    *
    * @param {string} propertyName
    * @param {string} value
    */
    _saveChanges: function(propertyName, value, index) {
      index = isNaN(index) ? this.options.activeIndex : index;
      var changedPhoto = this._changedPhotosById[index] || {};

      changedPhoto[propertyName] = value;

      if (propertyName === 'album_cover') {
        this._setOption('coverItem', index);
      }

      this._changedPhotosById[index] = changedPhoto;
    },

    /**
     * Take only selected photos from the list and paste them into the editor area.
     */
    _postFromList: function() {
      var cbSel = this.options.selectors.itemCheckbox,
        self = this,
        list = (this.options.type === 'list') ? this._listPhotosById : this._changedPhotosById;

      this._changedPhotosById = list.filter(function(item) {
        var checkbox = self._photoList.find(cbSel.supplant({ id: item.photo_id }));

        return checkbox.get(0).checked;
      });

      this._sendData('sendMany');
    },

    _bindEvents: function() {
      var photouploader = this,
        options = photouploader.options,
        selectors = options.selectors,
        classNames = options.classNames,
        privacyClassNames = classNames.privacy;

      this._photoList.sortable({
        disabled: true,
        stop: function () {
          photouploader.update();
        }
      }).disableSelection();

      this.element
        .bind('fileQueued', function(event, counters) {
          photouploader
            .updateCounters(counters)
            .startUpload();
        })
        .bind('uploadStart', function(event, filename) {
          photouploader.option({
            filename: filename
          });
          photouploader._setOption('progress', 0);
        })
        .bind('uploadProgress', function(event, percent) {
          photouploader.option('progress', percent.replace('%', ''));
        })
        .bind('fileUploaded', function(event, serverData) {
          var flashUploader = photouploader._flashUploader;

          if (serverData.status === 'error') {
            if (options.state === 'processing') {
              alert(
                Site.ml_text[serverData.result] ?
                Site.ml_text[serverData.result] :
                serverData.result
              );
              if (serverData.message) {
                console.log(serverData.message);
              }
            }

            photouploader._flashUploader.cancelQueue();

            if (!photouploader._changedPhotosById.length) {
              flashUploader.setButtonDisabled(false);
              flashUploader.setButtonImageURL(options.urls.uploaderImage);
            }

            photouploader._setOption('state', 'end');

            return false;
          }

          photouploader
            .updateCounters({
              currentIndex: parseInt(options.currentIndex, 10) + 1
            })
            .option('availableNow', serverData.availableNow)
            .addItem(serverData);
        })
        .bind('uploadFinished', function() {
          photouploader._touchPixel('photouploaded');
          photouploader._setOption('state', 'end');

        })
        .bind('endupload', function () {
          photouploader._photoList.sortable('enable').sortable('refresh');
        })
        .bind('uploading', function () {
          photouploader._photoList.sortable('disable');
        })
        .bind('removeitem', function () {
          photouploader._photoList.sortable('refresh');

          photouploader.update();
        })

        .delegate(selectors.uploadButton, 'click', function(event) {
          event.preventDefault();
          photouploader.show();
        });

      this._popupNode
        .delegate(selectors.uploadedItem, 'click', function(event) {
          var currentItem = $(this);

          event.preventDefault();

          if (options.state === 'processing') {
            return false;
          }

          photouploader.makeActive(currentItem);
        })
        .delegate(selectors.closeControl, 'click', function() {
          var closeWithoutSaving;

          if (
            options.state === 'processing' ||
            ( options.state === 'end' &&
              options.type === 'upload' &&
              photouploader._changedPhotosById.length )
          ) {
            closeWithoutSaving = confirm(options.ml['fotki.album.close.without.saving.confirm']);
            if (closeWithoutSaving) {
              photouploader.removeUploaded();
            } else {
              return false;
            }
          } else if (options.type === 'paste') {
            photouploader.removeUploaded();
          }

          photouploader.hide();
        })
        .delegate(selectors.dataForm, 'submit', function(event) {
          var photoSrc;

          event.preventDefault();
          if (photouploader.options.type === 'paste') {
            photouploader.removeUploaded();

            photoSrc = photouploader._pasteImageUrl.val();
            if (photoSrc) {
              photouploader.element.trigger({
                type: 'htmlready',
                htmlStrings: photouploader._makeHtml({
                  photo_link: photouploader._pasteImageLink.val(),
                  photo_title: '',
                  photo_src: photoSrc
                })
              });
            }

            photouploader.hide();
          } else if (photouploader.options.type === 'list') {
            // We don't remove uploaded photos when type is 'list'
            // cuz user can insert photo that uploaded before
            photouploader._postFromList();
          } else if (photouploader.options.type === 'upload') {
            photouploader._sendData('sendMany');
          } else {
            photouploader._postFromList();
          }
        })
        .delegate(selectors.titleField, 'change paste keyup', function() {
          var title = this.value;
          photouploader._saveChanges('photo_title', title);
          options.activeImg.attr('alt', title);
        })
        .delegate(selectors.descField, 'change paste keyup', function() {
          photouploader._saveChanges('photo_desc', this.value);
        })
        .delegate(selectors.linkField, 'change paste keyup', function() {
          photouploader._saveChanges('photo_link', this.value);
        })
        .delegate(selectors.albumCoverCheckbox, 'change', function() {
          var albumCover = ($(this).prop('checked')) ? 1 : 0;

          if (albumCover) {
            photouploader._setOption('coverItem', options.activeItem);
          } else {
            photouploader._saveChanges('is_cover', 0);
          }

        })
        .delegate(selectors.albumList, 'change', function() {
          if (photouploader._albumList.prop('selectedIndex') === photouploader._albumList.children().length - 1) {
            photouploader._newAlbumFieldWrapper.show();
            photouploader._newAlbumField.focus();
            $(this).hide();
          }
        })
        .delegate(selectors.cancelCreateAlbumBtn, 'click', function (event) {
          event.preventDefault();

          photouploader._albumList.show();
          photouploader._newAlbumFieldWrapper.hide();

          if (options.albumId) {
            photouploader._albumList.find('option[value=' + options.albumId + ']').prop('selected', true);
          } else {
            photouploader._albumList.find(':first').prop('selected', true);
          }
        })
        .delegate(selectors.removeButton, 'click', function(event) {
          event.preventDefault();
          event.stopPropagation();

          photouploader.removeItem($(this).closest(options.selectors.uploadedItem));
        })
        .delegate(selectors.headers, 'click', function(event) {
          event.preventDefault();
          event.stopPropagation();

          var type = $(this)
            .attr('class')
            .match(new RegExp(classNames.typePrefix + '(.+?)' + classNames.headerSuffix), 'i')[1];

          if (options.type !== type) {
            photouploader._setOption('type', type);
            this.className += ' ' + classNames.currentTab;
          }
        })
        .delegate(selectors.pasteImageUrl, 'keyup paste blur', (function (){
          var tempImage = new Image(),
            timer,
            src;

          tempImage.onload = function () {
            photouploader._pasteImagePreview.html(options.templates.previewImg.supplant({
              src: tempImage.src
            }));
          };

          tempImage.onerror = function () {
            photouploader._pasteImagePreview.html('');
          };

          function onTimeEnd() {
            if (src !== tempImage.src) {
              tempImage.src = src;
            }
          }

          return function () {
            clearTimeout(timer);
            timer = setTimeout(onTimeEnd, 500);
            src = this.value;
          };
        })());

      this._listPageAlbumList.change(function(ev) {
        if (photouploader._photoList.find(selectors.firstSelectedListItem).length === 0 ||
          confirm(LiveJournal.getLocalizedStr('fotki.album.change'))) {
          photouploader._fillGallery(this.value);
        } else {
          ev.preventDefault();
        }
      });

      this._photoListWrapper.bind('scroll', function() {
        var bottomPosition;

        if (
          options.type !== 'list' ||
          photouploader._currentGalleryFull ||
          photouploader._currentGalleryLoading
        ) {
          return;
        }

        bottomPosition = photouploader._photoListWrapper.scrollTop() +
                    photouploader._photoListWrapper.height();

        if (photouploader._photoList.height() - 200 < bottomPosition) {
          photouploader._fetchGallery();
        }
      });

      this._privacyBubble
        .delegate(selectors.privacyGroup, 'click', function() {
          var currentGroup = $(this),
            value = currentGroup.attr('data'),
            privacyClassName,
            privacyType;

          for (privacyType in privacyClassNames) {
            if (!privacyClassNames.hasOwnProperty(privacyType)) {
              continue;
            }

            if (value.indexOf(privacyType) === 0) {
              privacyClassName = privacyClassNames[privacyType];
              break;
            }
          }

          photouploader._privacyIcon
            .attr('class', privacyClassNames.basic)
            .addClass(privacyClassName);

          photouploader._privacyBubble
            .data('value', value)
            .bubble('hide');

          photouploader._privacyGroups.removeClass('active');

          currentGroup.addClass('active');
        });

      $(document)
        .bind('keydown', function(event) {
          // Escape
          if (event.which === 27) {
            photouploader._closeControl.trigger('click');
          }
        });
    },

    /**
    *   Serializes data to output data format (listed below):
    *   {
    *     photos_data: [
    *       {
    *         "photo_id": "1",
    *         "photo_title": "foo",
    *         "photo_desc": "bar",
    *         ...
    *       },
    *       {
    *         "photo_id": "2",
    *         "photo_title": "blabla",
    *         "is_deleted": "1"
    *         ...
    *       }
    *     ],
    *
    *     // if photos will be added to album that is already exist
    *     "album_id": "12345",
    *
    *     // if new album will be created
    *     "album_title": "My Album",
    *
    *     // required size of photos (to add to post) - if needed
    *     "required_size": "600",
    *
    *     // photo id to make redirect to or word "album" (if redirect to album needed)
    *     "redirect_to": "54321",
    *   }
    *
    * @param {string} action
    * @param {number} oneIndex
    */
    _serializeData: function(action /* 'sendOne', 'sendMany', 'removeAll' */, oneIndex) {
      var changedPhotosById = this._changedPhotosById,
        isNewAlbum = !!this._albumTitle,
        type = this.options.type,
        photoData = {}, photosData = [], changedData = {},
        albumField, albumValue,
        index, length,
        item;

      if (isNewAlbum) {
        albumField = 'album_title';
        albumValue = this._albumTitle;
      } else {
        albumField = 'album_id';
        albumValue = this._albumId;
      }

      if (action === 'sendMany' || action === 'removeAll') {
        for (index = 0, length = changedPhotosById.length; index < length; index++) {
          item = changedPhotosById[index];

          if (action === 'removeAll') {
            photoData = {
              photo_id: item.photo_id,
              is_deleted: 1
            };
          } else if (type === 'add') {
            photoData = {
              photo_id: item.photo_id
            };
          } else {
            photoData = item;
            delete photoData.photo_src;
          }

          photosData.push(photoData);
        }
      } else if (action === 'sendOne') {
        photosData.push(changedPhotosById[oneIndex]);
      }

      changedData.photos_data = photosData;

      if (type === 'upload') {
        changedData[albumField] = albumValue;
        changedData.privacy = this._privacy;
        changedData.action = this.options.action || 'upload';
      }

      if (action === 'sendMany') {
        if (this.options.htmlOutput) {
          changedData.required_size = this._requiredSize;
        } else {
          changedData.redirect_to = (photosData.length > 1) ? 'album' : photosData[0].photo_id;
        }
      }

      changedData.type = type;
      this._changedData = JSON.stringify(changedData);
    },

    /**
    * Serializes and sends data to server
    *
    * @param {string} action
    * @param {string} oneIndex
    */
    _sendData: function(action, oneIndex) {
      var photouploader = this;

      this._saveAlbum();
      this._saveSize();
      this._savePrivacy();

      this._togglePreloader('show');
      this._serializeData(action, oneIndex);

      $.ajax(this.options.urls.sendDataTo, {
        type: 'POST',
        data : {
          data_to_update: this._changedData
        },
        dataType: 'json',
        success: function(response) {
          var status = response.status;

          if (status === 'redirect') {
            window.location.href = response.url;
          } else {
            photouploader._togglePreloader('hide');

            if (response.resizes_data && response.result) {
              // update default size value before reset
              // (need to save it for next dialog opening #LJSUP-12849)
              photouploader._sizeList.sizeSelect('updateDefault');
              photouploader.element.trigger({
                type: 'htmlready',
                htmlStrings: photouploader._makeHtml(response.resizes_data)
              });
            }

            if (action === 'sendMany') {
              photouploader.hide();
            }

            if (response.new_album_id) {
              photouploader._addNewAlbumToList(response.new_album_id);
            }
          }
        }
      });
    },

    /**
    * Add new album to list (album just created by user)
    *
    * @param {string} newAlbumId
    */
    _addNewAlbumToList: function(newAlbumId) {
      var newAlbumItem = $(this.options.templates.albumList.common.supplant({
          album_id: newAlbumId,
          album_title: this._newAlbumField.val()
        })),
        children = this._albumList.children(),
        idx = children.length - 1;

      newAlbumItem.insertBefore(children.last());
      this._albumList.prop('selectedIndex', idx);

      this._newAlbumField.val('').focus();
      this._newAlbumFieldWrapper.hide();
    },

    /**
    * Makes HTML for "htmlready" (with required sizes of images)
    *
    * @param {Object} resizedUrls
    * @return {Array} resultHtml
    */
    _makeHtml: function(resizedUrls) {
      var data = this._changedPhotosById,
        // width and height attributes string for the image(s)
        attributes = this._sizeList.sizeSelect('attributes'),
        // selected value in the sizeList
        type = this._sizeList.sizeSelect('option', 'value');

      if (this.options.type === 'paste') {
        return $.fotki.makePhotosHTML(resizedUrls, attributes);
      } else {
        return $.fotki.photosHTML(resizedUrls, data, {
          type: type,
          attributes: attributes,
          insertOriginalLink: this._originalLinkCheckbox.is(':checked')
        });
      }
    },

    _togglePreloader: function(action) {
      this._preloaderElem
        .toggleClass(this.options.classNames.preloader, action === 'show');
    },

    _saveAlbum: function() {
      var albumSelectedIndex = this._albumList.prop('selectedIndex');

      // if last item in album select selected - we must create new album
      if (albumSelectedIndex === this._albumList.children().length - 1) {
        this._albumTitle = this._newAlbumField.val();
      // else put photos in existing album
      } else {
        this._albumTitle = '';
        this._albumId = this._albumList.val();
      }
    },

    _saveSize: function() {
      this._requiredSize = this._sizeList && this._sizeList.sizeSelect('selectedValue') || null;

      if (this._requiredSize === 'custom') {
        this._requiredSize = 'original';
      }
    },

    _savePrivacy: function() {
      this._privacy = this._privacyBubble.data('value') || 'public';
    },

    _updatePosition: function() {
      var leftPos = 0,
        wh;

      if ( $(window).width() < this._popupNode.width() ) {
        leftPos = -$(window).width()/2;
      } else {
        leftPos = - this._popupNode.width() / 2;
      }

      this._popupNode.css({
        left: leftPos,
        top: $(window).scrollTop() + ($(window).height() * 0.1)
      });

      wh = Math.floor($(window).height() * 0.6);
      if (wh < 300) {
        wh = 300;
      }

      // save wrapper max-height
      this._wrapperMaxHeight = wh;

      this._photoListWrapper.css({
        maxHeight: wh
      });
    },

    /**
     * Show the photouploader dialog.
     */
    show: function() {
      var self = this;

      // uncheck original link url checkbox on show
      this._originalLinkCheckbox.prop('checked', false);

      this._faderNode.show();
      this._touchPixel('opendialog');

      if (this.options.type === 'add' && this.options.insertPhotosCount === 'one') {
        this._photoList.find('img').bind('load', function () {
          self._updatePosition();
          self._popupNode.show();
        });
      } else {
        this._updatePosition();
        this._popupNode.show();
      }

      if ( !this._hasFlash ) {
        this._hideUploadTab();

        // explicitly change type option
        if (this.options.type === 'upload') {
          this._setOption('type', 'list');
        }
      }

      return this;
    },

    /**
     * Hide the photouploader dialog.
     */
    hide: function() {
      this.reset();
      this._faderNode.hide();
      this._popupNode.hide();
      this._currentGalleryId = null;
      return this;
    },

    /**
     * Return the dialog to the initial state
     */
    reset: function() {
      this.element.unbind('htmlready');
      this._changedPhotosById = [];
      this._photoList.empty();
      this._pasteImagePreview.empty();
      this._pasteImageUrl.val('');
      this._pasteImageLink.val('');
      this._albumList.show();
      this._currentGalleryId = null;

      if (this.options.htmlOutput) {
        this._sizeList.sizeSelect('reset');
      }

      this._setOptions({
        state: 'begin',
        progress: 0,
        coverItem: null
      });

      return this;
    },

    /**
    * Loads photo data (title, desc, etc.) to the form fields
    */
    load: function() {
      var currentData = this._changedPhotosById[this.options.activeIndex];

      if (!currentData) {
        return this;
      }

      this._titleField.val(currentData.photo_title);
      this._descField.val(currentData.photo_desc);
      this._linkField.val(currentData.photo_link);
      this._albumCoverCheckbox.prop('checked', !!currentData.is_cover);

      this._titleField.trigger('focus');

      return this;
    },

    /**
    * Adds item (photo preview) to the photo list and stores base data
    * (id, src and title) in array (_changedPhotosById)
    *
    * @param {Object} item
    */
    addItem: function(item) {
      var photouploader = this,
        options = this.options,
        type = options.type,
        wrapper = this._photoListWrapper,
        newImageNode,
        newImage;

      switch (type) {
        case 'upload':
          // make image node
          newImageNode = LJ.UI.template(this.options.templates.uploadedItem, {
            photo_src: item.photo_src,
            type: type
          })
          .data('id', item.photo_id)
          .appendTo(this._photoList);

          newImage = new Image();

          // add callback to show new image node after load ends
          newImage.onload = function() {
            photouploader.index('last');
            photouploader._setOption(
              'insertPhotosCount',
              photouploader._changedPhotosById.length <= 5 ? 'several' : 'many'
            );

            if ($.browser.opera) {
              newImageNode.show();
            } else {
              newImageNode.fadeIn('fast');
            }

            wrapper.scrollTop(wrapper[0].scrollHeight);

            photouploader.element.trigger('thumbnailLoaded');
          };

          newImage.src = item.photo_src;

          break;
        case 'list':
          newImageNode = LJ.UI.template(this.options.templates.insertedItem, {
            photo_url:  item.photo_url,
            type: type,
            photo_id: item.photo_id,
            checked: ''
          })
          .data('id', item.photo_id)
          .appendTo(this._photoList);

          this._listPhotosById.push({
            photo_id: item.photo_id,
            photo_src: item.photo_url,
            photo_title: item.photo_title
          });

          //this node should not appear between changed photos
          return;
        case 'add':
          newImageNode = LJ.UI.template(this.options.templates.insertedItem, {
            photo_url:  item.photo_url,
            type: type,
            photo_id: item.photo_id,
            checked: ' checked="checked"'
          })
          .data('id', item.photo_id)
          .appendTo(this._photoList);

          break;
      }

      wrapper.scrollTop(wrapper[0].scrollHeight);

      this._changedPhotosById.push({
        photo_id: item.photo_id,
        photo_src: item.photo_src,
        photo_title: item.photo_title
      });

      return this;
    },

    updateCounters: function(counters) {
      this._setOptions(counters);

      return this;
    },

    startUpload: function() {
      this._setOption('state', 'processing');
      this._flashUploader.startUpload();


      return this;
    },

    makeActive: function(item) {
      this._setOption('activeItem', item);

      return this;
    },

    /**
    * Removes all uploaded photos from photo list and from server
    * When we upload photos, but do not post them
    */
    removeUploaded: function () {
      if ( this._changedPhotosById.length ) {
        this._sendData('removeAll');
      }
    },

    /**
    * Remove certain item from photo list (and from server) than shift photo list
    * and reset (if there are no items left in the list)
    * @function
    *
    * @param {jQuery} item Node of the image in the list to be removed.
    */
    removeItem: (function () {
      function onFadeOut (widget, item, index) {
        var length = widget._changedPhotosById.length,
          options = widget.options;

        $(item).remove();

        if (length === 0) {
          widget.reset();

          switch (options.type) {
            case 'upload':
              widget._setOption('state', 'begin');
              widget._stateContainer.removeClass(
                options.classNames.insertPhotosCountPrefix + options.insertPhotosCount
              );
            break;
            case 'add':
              widget.hide();
            break;
          }
        } else {
          widget._setOption('insertPhotosCount', length <= 5 ? 'several' : 'many');
        }

        if (index === options.activeIndex) {
          widget.index(index === length ? -1 : 0);
        }

        widget.element.trigger({
          type: 'removeitem'
        });
      }

      return function(item) {
        var photouploader = this,
          options = this.options,
          currentIndex = this._getIndex(item);

        switch (options.type) {
          case 'upload':
            this._saveChanges('is_deleted', 1, currentIndex);
            this._sendData('sendOne', currentIndex);
          break;
        }

        this._changedPhotosById.splice(currentIndex, 1);

        if ($.browser.opera) {
          onFadeOut(photouploader, item, currentIndex);
        } else {
          item.fadeOut('fast', function() {
            onFadeOut(photouploader, item, currentIndex);
          });
        }

        return this;
      };
    })(),

    /**
     * Update widget internal data structures when user reorders photos
     * by drag n drop. Should be private.
     */
    update: function(){
      var list,
          item,
          items = {},
          photouploader = this;

      if (this.options.type === 'list') {
        list = this._listPhotosById;
      } else {
        list = this._changedPhotosById;
      }

      while (item = list.shift()) {
        items[item.photo_id] = item;
      }

      this._photoList.children(':visible').each(function(){
        list.push(items[$(this).data('id')]);
        if (photouploader.options.type !== 'list') {
          if($(this).hasClass('selected')){
            photouploader._setOption('activeItem', $(this));
          }
        }
      });
    },

    /**
     * Set the currently selected item in the dialog on the upload tab.
     */
    index: function(value) {
      var nextIndex = this.options.activeIndex + value,
        items = this._photoList.children(':visible'),
        lastIndex = (items.length === 0) ? 0 : items.length - 1;

      if (value === 'first' || nextIndex > lastIndex) {
        nextIndex = 0;
        value = 'first';
      } else if (value === 'last' || nextIndex < 0) {
        nextIndex = lastIndex;
        value = 'last';
      }

      this.makeActive(items.eq(nextIndex));
    },

    /**
     * Get element index in the photolist (between visible items)
     * @param  {jQuery} element jQuery item element
     * @return {Number}         Item index
     */
    _getIndex: function (element) {
      return this._photoList
        .children(':visible')
        .index(element);
    },

    _touchPixel: function(name) {
      var prop = 'tracking_' + name,
        url = this.options[prop],
        pixel;

      if (url && url.length > 0) {
        pixel = new Image();
        pixel.src = url + '&__rnd__' + Math.random();
      }
    }

  });

})(jQuery, this);

/**
* Event is fired when user presses "Add to Post" button
* in the dialog.
*
* @name $.lj.photouploader#htmlready
*
* @param {jQuery.Event} event jQuery event object. The object has custom htmlStrings
*
*      @param {jQuery.Event} event jQuery event object. The object has custom htmlStrings
*           property, that holds the array with image tags of photos to be pasted
*      property, that holds the array with image tags of photos to be pasted.
*
* @event
*/
;

/* file-end: js/jquery/jquery.lj.photouploader.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.lj.ljcut.js 
*/

/**
 * @author Valeriy Vasin (valeriy.vasin@sup.com)
 * @name $.lj.ljcut
 * @requires $.ui.core, $.ui.widget, $.lj.basicWidget, LJ
 * @class The widget is responsible for expanding cuts
 */
;(function ($) {
	"use strict";

	$.widget('lj.ljcut', $.lj.basicWidget, {
		options: {
			// journal identifier (comes from server)
			journalid: null,
			// post identifier (comes from server)
			ditemid: null,
			// cut identifier inside of the post (comes from server)
			cutid: null,
			// server request param: use placeholders or not (1 or 0). Comes from server
			placeholders: 0,

			selectors: {
				expand: '.ljcut-link-expand',
				collapse: '.ljcut-link-collapse'
			},
			classNames: {
				preloader: 'ljcut-link-expanding',
				expanded: 'ljcut-expanded'
			}
		},

		_create: function () {
			$.lj.basicWidget.prototype._create.apply(this);

			// jQuery element that will contain loaded content of the cut
			this.content = null;
			// test OS for Mac
			this._isMac = (/Mac/).test(navigator.userAgent);
			// $.browser.opera is deprecated
			this._isOpera = (/Opera/.test(navigator.userAgent));

			this._bindControls();
		},

		_bindControls: function () {
			$.lj.basicWidget.prototype._bindControls.apply(this);

			this.element.on('click', this._s('expand'), this._expand.bind(this));
			this.element.on('click', this._s('collapse'), this._collapse.bind(this));
			$(document).on('keydown', this._shortcuts.bind(this));
		},

		/**
		 * Shortcuts handler
		 * @param  {Object} e jQuery event object
		 */
		_shortcuts: function (e) {
			var ctrl = (this._isMac && this._isOpera) ? e.metaKey : e.ctrlKey,
				alt = e.altKey;

			if (!ctrl || !alt) {
				return;
			}

			switch (e.which) {
				// expand: ctrl + alt + "+"
				case 61: // FireFox, IE
					// fall through
				case 187: // Opera, Chrome, Safari
					this.expand();
					break;

				// collapse: ctrl + alt + "-"
				case 173: // FireFox
					// fall through
				case 31: // Opera Mac
					// fall through
				case 109: // Opera Windows
					// fall through
				case 189: // Chrome, Safari
					this.collapse();
					break;

				// no default
			}
			e.preventDefault();
		},

		/**
		 * Show or hide preloader
		 * @param  {Boolean} state Preloader state: True (show) or False (hide)
		 */
		_togglePreloader: function (state) {
			this.element.toggleClass( this._cl('preloader'), state );
		},

		/**
		 * Toggle content state
		 * @param  {Boolean} state State of content: expand (true) or collapse (false)
		 */
		_toggleContent: function (state, callback) {
			var that = this;

			if (this.locked() || !this.content) {
				return;
			}

			this._lock();
			if (typeof callback !== 'function') {
				callback = $.noop;
			}

			that.element.toggleClass( that._cl('expanded'), state );
			if (state) {
				this.content.slideDown('fast', function () {
					that._trigger('show', null, that);
					callback();
					that._unlock();
				});
			} else {
				this.content.slideUp(50, function () {
					that._trigger('hide', null, that);
					callback();
					that._unlock();
				});
			}
		},

		/**
		 * Request server for the cut content
		 * @param  {Object} data Data that is needed for request
		 */
		_requestContent: function (data) {
			var that = this;

			this._lock();
			this._togglePreloader(true);
			LJ.Api.call('event.get_lj_cut', data, function (response) {
				that.content = $('<div />', { html: response.text }).hide();
				that.element.after( that.content );
				that._unlock();
				that._togglePreloader(false);

				// add handlers after content becomes visible
				that._toggleContent(true, that._addHandlers.bind(that));

				// statistic
				if (response.counter_image_url) {
					LJ.Stat.addCounter(response.counter_image_url);
				}
			});
		},

		/**
		 * Provide dynamic behavior for the content (javascript handlers)
		 * @private
		 */
		_addHandlers: function () {
			this.content.ljLikes();
		},

		/**
		 * Expand content
		 */
		expand: function () {
			if ( this.locked() ) {
				return;
			}
			if ( this.content ) {
				this._toggleContent(true);
			} else {
				this._requestContent({
					journalid: this.options.journalid,
					ditemid: this.options.ditemid,
					cutid: this.options.cutid,
					placeholders: this.options.placeholders
				});
			}
		},

		/**
		 * Collapse content (for external usage)
		 */
		collapse: function () {
			if ( !this.locked() ) {
				this._toggleContent(false);
			}
		},

		/**
		 * Expand link click handler
		 * @param  {Object} e jQuery event object
		 */
		_expand: function (e) {
			// open link in new tab
			if (e.metaKey || e.ctrlKey) {
				return true;
			}
			e.preventDefault();
			this.expand();
		},

		/**
		 * Collapse link click handler
		 * @param  {Object} e jQuery event object
		 */
		_collapse: function (e) {
			// open link in new tab
			if (e.metaKey || e.ctrlKey) {
				return true;
			}
			e.preventDefault();
			this.collapse();
		}
	});
}(jQuery));
;

/* file-end: js/jquery/jquery.lj.ljcut.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/entry/main.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/lib/angular/1.2.0-rc.2/angular.min.js 
*/

/*
 AngularJS v1.2.0-rc.2
 (c) 2010-2012 Google, Inc. http://angularjs.org
 License: MIT
*/
(function(Y,T,s){'use strict';function P(a){return function(){var b=arguments[0],c,b="["+(a?a+":":"")+b+"] http://errors.angularjs.org/undefined/"+(a?a+"/":"")+b;for(c=1;c<arguments.length;c++)b=b+(1==c?"?":"&")+"p"+(c-1)+"="+encodeURIComponent("function"==typeof arguments[c]?arguments[c].toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof arguments[c]?"undefined":"string"!=typeof arguments[c]?JSON.stringify(arguments[c]):arguments[c]);return Error(b)}}function kb(a){if(null==a||va(a))return!1;
var b=a.length;return 1===a.nodeType&&b?!0:D(a)||!B(a)&&(0===b||"number"===typeof b&&0<b&&b-1 in a)}function q(a,b,c){var d;if(a)if(B(a))for(d in a)"prototype"!=d&&("length"!=d&&"name"!=d&&a.hasOwnProperty(d))&&b.call(c,a[d],d);else if(a.forEach&&a.forEach!==q)a.forEach(b,c);else if(kb(a))for(d=0;d<a.length;d++)b.call(c,a[d],d);else for(d in a)a.hasOwnProperty(d)&&b.call(c,a[d],d);return a}function Fb(a){var b=[],c;for(c in a)a.hasOwnProperty(c)&&b.push(c);return b.sort()}function Bc(a,b,c){for(var d=
Fb(a),e=0;e<d.length;e++)b.call(c,a[d[e]],d[e]);return d}function Gb(a){return function(b,c){a(c,b)}}function Ta(){for(var a=ha.length,b;a;){a--;b=ha[a].charCodeAt(0);if(57==b)return ha[a]="A",ha.join("");if(90==b)ha[a]="0";else return ha[a]=String.fromCharCode(b+1),ha.join("")}ha.unshift("0");return ha.join("")}function Hb(a,b){b?a.$$hashKey=b:delete a.$$hashKey}function E(a){var b=a.$$hashKey;q(arguments,function(b){b!==a&&q(b,function(b,c){a[c]=b})});Hb(a,b);return a}function V(a){return parseInt(a,
10)}function Cc(a,b){return E(new (E(function(){},{prototype:a})),b)}function A(){}function wa(a){return a}function $(a){return function(){return a}}function M(a){return"undefined"==typeof a}function z(a){return"undefined"!=typeof a}function U(a){return null!=a&&"object"==typeof a}function H(a){return"string"==typeof a}function lb(a){return"number"==typeof a}function Ea(a){return"[object Date]"==Ua.apply(a)}function D(a){return"[object Array]"==Ua.apply(a)}function B(a){return"function"==typeof a}
function mb(a){return"[object RegExp]"==Ua.apply(a)}function va(a){return a&&a.document&&a.location&&a.alert&&a.setInterval}function Dc(a){return a&&(a.nodeName||a.on&&a.find)}function Ec(a,b,c){var d=[];q(a,function(a,g,h){d.push(b.call(c,a,g,h))});return d}function Va(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c<a.length;c++)if(b===a[c])return c;return-1}function Fa(a,b){var c=Va(a,b);0<=c&&a.splice(c,1);return b}function da(a,b){if(va(a)||a&&a.$evalAsync&&a.$watch)throw Wa("cpws");if(b){if(a===
b)throw Wa("cpi");if(D(a))for(var c=b.length=0;c<a.length;c++)b.push(da(a[c]));else{c=b.$$hashKey;q(b,function(a,c){delete b[c]});for(var d in a)b[d]=da(a[d]);Hb(b,c)}}else(b=a)&&(D(a)?b=da(a,[]):Ea(a)?b=new Date(a.getTime()):mb(a)?b=RegExp(a.source):U(a)&&(b=da(a,{})));return b}function Fc(a,b){b=b||{};for(var c in a)a.hasOwnProperty(c)&&"$$"!==c.substr(0,2)&&(b[c]=a[c]);return b}function xa(a,b){if(a===b)return!0;if(null===a||null===b)return!1;if(a!==a&&b!==b)return!0;var c=typeof a,d;if(c==typeof b&&
"object"==c)if(D(a)){if(!D(b))return!1;if((c=a.length)==b.length){for(d=0;d<c;d++)if(!xa(a[d],b[d]))return!1;return!0}}else{if(Ea(a))return Ea(b)&&a.getTime()==b.getTime();if(mb(a)&&mb(b))return a.toString()==b.toString();if(a&&a.$evalAsync&&a.$watch||b&&b.$evalAsync&&b.$watch||va(a)||va(b)||D(b))return!1;c={};for(d in a)if("$"!==d.charAt(0)&&!B(a[d])){if(!xa(a[d],b[d]))return!1;c[d]=!0}for(d in b)if(!c.hasOwnProperty(d)&&"$"!==d.charAt(0)&&b[d]!==s&&!B(b[d]))return!1;return!0}return!1}function nb(a,
b){var c=2<arguments.length?ta.call(arguments,2):[];return!B(b)||b instanceof RegExp?b:c.length?function(){return arguments.length?b.apply(a,c.concat(ta.call(arguments,0))):b.apply(a,c)}:function(){return arguments.length?b.apply(a,arguments):b.call(a)}}function Gc(a,b){var c=b;/^\$+/.test(a)?c=s:va(b)?c="$WINDOW":b&&T===b?c="$DOCUMENT":b&&(b.$evalAsync&&b.$watch)&&(c="$SCOPE");return c}function oa(a,b){return"undefined"===typeof a?s:JSON.stringify(a,Gc,b?"  ":null)}function Ib(a){return H(a)?JSON.parse(a):
a}function Ga(a){a&&0!==a.length?(a=J(""+a),a=!("f"==a||"0"==a||"false"==a||"no"==a||"n"==a||"[]"==a)):a=!1;return a}function ia(a){a=w(a).clone();try{a.html("")}catch(b){}var c=w("<div>").append(a).html();try{return 3===a[0].nodeType?J(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(b,a){return"<"+J(a)})}catch(d){return J(c)}}function Jb(a){try{return decodeURIComponent(a)}catch(b){}}function Kb(a){var b={},c,d;q((a||"").split("&"),function(a){a&&(c=a.split("="),d=Jb(c[0]),z(d)&&(a=z(c[1])?
Jb(c[1]):!0,b[d]?D(b[d])?b[d].push(a):b[d]=[b[d],a]:b[d]=a))});return b}function Lb(a){var b=[];q(a,function(a,d){D(a)?q(a,function(a){b.push(ua(d,!0)+(!0===a?"":"="+ua(a,!0)))}):b.push(ua(d,!0)+(!0===a?"":"="+ua(a,!0)))});return b.length?b.join("&"):""}function ob(a){return ua(a,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function ua(a,b){return encodeURIComponent(a).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,b?"%20":"+")}
function Hc(a,b){function c(a){a&&d.push(a)}var d=[a],e,g,h=["ng:app","ng-app","x-ng-app","data-ng-app"],f=/\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;q(h,function(b){h[b]=!0;c(T.getElementById(b));b=b.replace(":","\\:");a.querySelectorAll&&(q(a.querySelectorAll("."+b),c),q(a.querySelectorAll("."+b+"\\:"),c),q(a.querySelectorAll("["+b+"]"),c))});q(d,function(b){if(!e){var a=f.exec(" "+b.className+" ");a?(e=b,g=(a[2]||"").replace(/\s+/g,",")):q(b.attributes,function(a){!e&&h[a.name]&&(e=b,g=a.value)})}});
e&&b(e,g?[g]:[])}function Mb(a,b){var c=function(){a=w(a);if(a.injector()){var c=a[0]===T?"document":ia(a);throw Wa("btstrpd",c);}b=b||[];b.unshift(["$provide",function(b){b.value("$rootElement",a)}]);b.unshift("ng");c=Nb(b);c.invoke(["$rootScope","$rootElement","$compile","$injector","$animate",function(b,a,c,d,e){b.$apply(function(){a.data("$injector",d);c(a)(b)});e.enabled(!0)}]);return c},d=/^NG_DEFER_BOOTSTRAP!/;if(Y&&!d.test(Y.name))return c();Y.name=Y.name.replace(d,"");Ha.resumeBootstrap=
function(a){q(a,function(a){b.push(a)});c()}}function pb(a,b){b=b||"_";return a.replace(Ic,function(a,d){return(d?b:"")+a.toLowerCase()})}function qb(a,b,c){if(!a)throw Wa("areq",b||"?",c||"required");return a}function Ia(a,b,c){c&&D(a)&&(a=a[a.length-1]);qb(B(a),b,"not a function, got "+(a&&"object"==typeof a?a.constructor.name||"Object":typeof a));return a}function rb(a,b,c){if(!b)return a;b=b.split(".");for(var d,e=a,g=b.length,h=0;h<g;h++)d=b[h],a&&(a=(e=a)[d]);return!c&&B(a)?nb(e,a):a}function Jc(a){function b(a,
b,e){return a[b]||(a[b]=e())}return b(b(a,"angular",Object),"module",function(){var a={};return function(d,e,g){e&&a.hasOwnProperty(d)&&(a[d]=null);return b(a,d,function(){function a(c,d,e){return function(){b[e||"push"]([c,d,arguments]);return m}}if(!e)throw P("$injector")("nomod",d);var b=[],c=[],l=a("$injector","invoke"),m={_invokeQueue:b,_runBlocks:c,requires:e,name:d,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide","service"),value:a("$provide","value"),
constant:a("$provide","constant","unshift"),animation:a("$animateProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider","directive"),config:l,run:function(a){c.push(a);return this}};g&&l(g);return m})}})}function Ja(a){return a.replace(Kc,function(a,c,d,e){return e?d.toUpperCase():d}).replace(Lc,"Moz$1")}function sb(a,b,c,d){function e(a){var e=c&&a?[this.filter(a)]:[this],k=b,l,m,p,n,t,r;if(!d||null!=a)for(;e.length;)for(l=
e.shift(),m=0,p=l.length;m<p;m++)for(n=w(l[m]),k?n.triggerHandler("$destroy"):k=!k,t=0,n=(r=n.children()).length;t<n;t++)e.push(ya(r[t]));return g.apply(this,arguments)}var g=ya.fn[a],g=g.$original||g;e.$original=g;ya.fn[a]=e}function S(a){if(a instanceof S)return a;if(!(this instanceof S)){if(H(a)&&"<"!=a.charAt(0))throw tb("nosel");return new S(a)}if(H(a)){var b=T.createElement("div");b.innerHTML="<div>&#160;</div>"+a;b.removeChild(b.firstChild);ub(this,b.childNodes);w(T.createDocumentFragment()).append(this)}else ub(this,
a)}function vb(a){return a.cloneNode(!0)}function Ka(a){Ob(a);var b=0;for(a=a.childNodes||[];b<a.length;b++)Ka(a[b])}function Pb(a,b,c,d){if(z(d))throw tb("offargs");var e=ja(a,"events");ja(a,"handle")&&(M(b)?q(e,function(b,c){wb(a,c,b);delete e[c]}):q(b.split(" "),function(b){M(c)?(wb(a,b,e[b]),delete e[b]):Fa(e[b]||[],c)}))}function Ob(a,b){var c=a[Xa],d=La[c];d&&(b?delete La[c].data[b]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),Pb(a)),delete La[c],a[Xa]=s))}function ja(a,b,c){var d=
a[Xa],d=La[d||-1];if(z(c))d||(a[Xa]=d=++Mc,d=La[d]={}),d[b]=c;else return d&&d[b]}function Qb(a,b,c){var d=ja(a,"data"),e=z(c),g=!e&&z(b),h=g&&!U(b);d||h||ja(a,"data",d={});if(e)d[b]=c;else if(g){if(h)return d&&d[b];E(d,b)}else return d}function Ya(a,b){return-1<(" "+a.className+" ").replace(/[\n\t]/g," ").indexOf(" "+b+" ")}function Rb(a,b){b&&q(b.split(" "),function(b){a.className=aa((" "+a.className+" ").replace(/[\n\t]/g," ").replace(" "+aa(b)+" "," "))})}function Sb(a,b){b&&q(b.split(" "),function(b){Ya(a,
b)||(a.className=aa(a.className+" "+aa(b)))})}function ub(a,b){if(b){b=b.nodeName||!z(b.length)||va(b)?[b]:b;for(var c=0;c<b.length;c++)a.push(b[c])}}function Tb(a,b){return Za(a,"$"+(b||"ngController")+"Controller")}function Za(a,b,c){a=w(a);for(9==a[0].nodeType&&(a=a.find("html"));a.length;){if((c=a.data(b))!==s)return c;a=a.parent()}}function Ub(a,b){var c=$a[b.toLowerCase()];return c&&Vb[a.nodeName]&&c}function Nc(a,b){var c=function(c,e){c.preventDefault||(c.preventDefault=function(){c.returnValue=
!1});c.stopPropagation||(c.stopPropagation=function(){c.cancelBubble=!0});c.target||(c.target=c.srcElement||T);if(M(c.defaultPrevented)){var g=c.preventDefault;c.preventDefault=function(){c.defaultPrevented=!0;g.call(c)};c.defaultPrevented=!1}c.isDefaultPrevented=function(){return c.defaultPrevented||!1==c.returnValue};q(b[e||c.type],function(b){b.call(a,c)});8>=Q?(c.preventDefault=null,c.stopPropagation=null,c.isDefaultPrevented=null):(delete c.preventDefault,delete c.stopPropagation,delete c.isDefaultPrevented)};
c.elem=a;return c}function za(a){var b=typeof a,c;"object"==b&&null!==a?"function"==typeof(c=a.$$hashKey)?c=a.$$hashKey():c===s&&(c=a.$$hashKey=Ta()):c=a;return b+":"+c}function Ma(a){q(a,this.put,this)}function Wb(a){var b,c;"function"==typeof a?(b=a.$inject)||(b=[],a.length&&(c=a.toString().replace(Oc,""),c=c.match(Pc),q(c[1].split(Qc),function(a){a.replace(Rc,function(a,c,d){b.push(d)})})),a.$inject=b):D(a)?(c=a.length-1,Ia(a[c],"fn"),b=a.slice(0,c)):Ia(a,"fn",!0);return b}function Nb(a){function b(a){return function(b,
c){if(U(b))q(b,Gb(a));else return a(b,c)}}function c(a,b){if(B(b)||D(b))b=p.instantiate(b);if(!b.$get)throw Na("pget",a);return m[a+f]=b}function d(a,b){return c(a,{$get:b})}function e(a){var b=[];q(a,function(a){if(!l.get(a)){l.put(a,!0);try{if(H(a)){var c=Oa(a);b=b.concat(e(c.requires)).concat(c._runBlocks);for(var d=c._invokeQueue,c=0,f=d.length;c<f;c++){var k=d[c],g=p.get(k[0]);g[k[1]].apply(g,k[2])}}else B(a)?b.push(p.invoke(a)):D(a)?b.push(p.invoke(a)):Ia(a,"module")}catch(h){throw D(a)&&(a=
a[a.length-1]),h.message&&(h.stack&&-1==h.stack.indexOf(h.message))&&(h=h.message+"\n"+h.stack),Na("modulerr",a,h.stack||h.message||h);}}});return b}function g(a,b){function c(d){if(a.hasOwnProperty(d)){if(a[d]===h)throw Na("cdep",k.join(" <- "));return a[d]}try{return k.unshift(d),a[d]=h,a[d]=b(d)}finally{k.shift()}}function d(a,b,e){var k=[],f=Wb(a),g,p,h;p=0;for(g=f.length;p<g;p++){h=f[p];if("string"!==typeof h)throw Na("itkn",h);k.push(e&&e.hasOwnProperty(h)?e[h]:c(h))}a.$inject||(a=a[g]);switch(b?
-1:k.length){case 0:return a();case 1:return a(k[0]);case 2:return a(k[0],k[1]);case 3:return a(k[0],k[1],k[2]);case 4:return a(k[0],k[1],k[2],k[3]);case 5:return a(k[0],k[1],k[2],k[3],k[4]);case 6:return a(k[0],k[1],k[2],k[3],k[4],k[5]);case 7:return a(k[0],k[1],k[2],k[3],k[4],k[5],k[6]);case 8:return a(k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7]);case 9:return a(k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7],k[8]);case 10:return a(k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7],k[8],k[9]);default:return a.apply(b,
k)}}return{invoke:d,instantiate:function(a,b){var c=function(){},e;c.prototype=(D(a)?a[a.length-1]:a).prototype;c=new c;e=d(a,c,b);return U(e)?e:c},get:c,annotate:Wb,has:function(b){return m.hasOwnProperty(b+f)||a.hasOwnProperty(b)}}}var h={},f="Provider",k=[],l=new Ma,m={$provide:{provider:b(c),factory:b(d),service:b(function(a,b){return d(a,["$injector",function(a){return a.instantiate(b)}])}),value:b(function(a,b){return d(a,$(b))}),constant:b(function(a,b){m[a]=b;n[a]=b}),decorator:function(a,
b){var c=p.get(a+f),d=c.$get;c.$get=function(){var a=t.invoke(d,c);return t.invoke(b,null,{$delegate:a})}}}},p=m.$injector=g(m,function(){throw Na("unpr",k.join(" <- "));}),n={},t=n.$injector=g(n,function(a){a=p.get(a+f);return t.invoke(a.$get,a)});q(e(a),function(a){t.invoke(a||A)});return t}function Sc(){var a=!0;this.disableAutoScrolling=function(){a=!1};this.$get=["$window","$location","$rootScope",function(b,c,d){function e(a){var b=null;q(a,function(a){b||"a"!==J(a.nodeName)||(b=a)});return b}
function g(){var a=c.hash(),d;a?(d=h.getElementById(a))?d.scrollIntoView():(d=e(h.getElementsByName(a)))?d.scrollIntoView():"top"===a&&b.scrollTo(0,0):b.scrollTo(0,0)}var h=b.document;a&&d.$watch(function(){return c.hash()},function(){d.$evalAsync(g)});return g}]}function Tc(a,b,c,d){function e(a){try{a.apply(null,ta.call(arguments,1))}finally{if(r--,0===r)for(;y.length;)try{y.pop()()}catch(b){c.error(b)}}}function g(a,b){(function ab(){q(x,function(a){a()});R=b(ab,a)})()}function h(){N!=f.url()&&
(N=f.url(),q(F,function(a){a(f.url())}))}var f=this,k=b[0],l=a.location,m=a.history,p=a.setTimeout,n=a.clearTimeout,t={};f.isMock=!1;var r=0,y=[];f.$$completeOutstandingRequest=e;f.$$incOutstandingRequestCount=function(){r++};f.notifyWhenNoOutstandingRequests=function(a){q(x,function(a){a()});0===r?a():y.push(a)};var x=[],R;f.addPollFn=function(a){M(R)&&g(100,p);x.push(a);return a};var N=l.href,u=b.find("base"),v=null;f.url=function(a,b){if(a){if(N!=a)return N=a,d.history?b?m.replaceState(null,"",
a):(m.pushState(null,"",a),u.attr("href",u.attr("href"))):b?(l.replace(a),v=a):(l.href=a,v=null),f}else return v||l.href.replace(/%27/g,"'")};var F=[],I=!1;f.onUrlChange=function(b){if(!I){if(d.history)w(a).on("popstate",h);if(d.hashchange)w(a).on("hashchange",h);else f.addPollFn(h);I=!0}F.push(b);return b};f.baseHref=function(){var a=u.attr("href");return a?a.replace(/^https?\:\/\/[^\/]*/,""):""};var Z={},ba="",W=f.baseHref();f.cookies=function(a,b){var d,e,f,g;if(a)b===s?k.cookie=escape(a)+"=;path="+
W+";expires=Thu, 01 Jan 1970 00:00:00 GMT":H(b)&&(d=(k.cookie=escape(a)+"="+escape(b)+";path="+W).length+1,4096<d&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"));else{if(k.cookie!==ba)for(ba=k.cookie,d=ba.split("; "),Z={},f=0;f<d.length;f++)e=d[f],g=e.indexOf("="),0<g&&(a=unescape(e.substring(0,g)),Z[a]===s&&(Z[a]=unescape(e.substring(g+1))));return Z}};f.defer=function(a,b){var c;r++;c=p(function(){delete t[c];e(a)},b||0);t[c]=!0;return c};
f.defer.cancel=function(a){return t[a]?(delete t[a],n(a),e(A),!0):!1}}function Vc(){this.$get=["$window","$log","$sniffer","$document",function(a,b,c,d){return new Tc(a,d,b,c)}]}function Wc(){this.$get=function(){function a(a,d){function e(a){a!=p&&(n?n==a&&(n=a.n):n=a,g(a.n,a.p),g(a,p),p=a,p.n=null)}function g(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(a in b)throw P("$cacheFactory")("iid",a);var h=0,f=E({},d,{id:a}),k={},l=d&&d.capacity||Number.MAX_VALUE,m={},p=null,n=null;return b[a]={put:function(a,
b){var c=m[a]||(m[a]={key:a});e(c);if(!M(b))return a in k||h++,k[a]=b,h>l&&this.remove(n.key),b},get:function(a){var b=m[a];if(b)return e(b),k[a]},remove:function(a){var b=m[a];b&&(b==p&&(p=b.p),b==n&&(n=b.n),g(b.n,b.p),delete m[a],delete k[a],h--)},removeAll:function(){k={};h=0;m={};p=n=null},destroy:function(){m=f=k=null;delete b[a]},info:function(){return E({},f,{size:h})}}}var b={};a.info=function(){var a={};q(b,function(b,e){a[e]=b.info()});return a};a.get=function(a){return b[a]};return a}}
function Xc(){this.$get=["$cacheFactory",function(a){return a("templates")}]}function Xb(a){var b={},c="Directive",d=/^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,e=/(([\d\w\-_]+)(?:\:([^;]+))?;?)/,g=/^\s*(https?|ftp|mailto|file):/,h=/^\s*(https?|ftp|file):|data:image\//,f=/^(on[a-z]*|formaction)$/;this.directive=function l(d,e){H(d)?(qb(e,"directiveFactory"),b.hasOwnProperty(d)||(b[d]=[],a.factory(d+c,["$injector","$exceptionHandler",function(a,c){var e=[];q(b[d],function(b){try{var f=a.invoke(b);B(f)?
f={compile:$(f)}:!f.compile&&f.link&&(f.compile=$(f.link));f.priority=f.priority||0;f.name=f.name||d;f.require=f.require||f.controller&&f.name;f.restrict=f.restrict||"A";e.push(f)}catch(g){c(g)}});return e}])),b[d].push(e)):q(d,Gb(l));return this};this.aHrefSanitizationWhitelist=function(a){return z(a)?(g=a,this):g};this.imgSrcSanitizationWhitelist=function(a){return z(a)?(h=a,this):h};this.$get=["$injector","$interpolate","$exceptionHandler","$http","$templateCache","$parse","$controller","$rootScope",
"$document","$sce","$$urlUtils","$animate",function(a,m,p,n,t,r,y,x,R,N,u,v){function F(a,b,c,d){a instanceof w||(a=w(a));q(a,function(b,c){3==b.nodeType&&b.nodeValue.match(/\S+/)&&(a[c]=w(b).wrap("<span></span>").parent()[0])});var e=Z(a,b,a,c,d);return function(b,c){qb(b,"scope");for(var d=c?Pa.clone.call(a):a,f=0,g=d.length;f<g;f++){var p=d[f];1!=p.nodeType&&9!=p.nodeType||d.eq(f).data("$scope",b)}I(d,"ng-scope");c&&c(d,b);e&&e(b,d,d);return d}}function I(a,b){try{a.addClass(b)}catch(c){}}function Z(a,
b,c,d,e){function f(a,c,d,e){var p,h,m,l,n,t,r,C=[];n=0;for(t=c.length;n<t;n++)C.push(c[n]);r=n=0;for(t=g.length;n<t;r++)h=C[r],c=g[n++],p=g[n++],c?(c.scope?(m=a.$new(U(c.scope)),w(h).data("$scope",m)):m=a,(l=c.transclude)||!e&&b?c(p,m,h,d,function(b){return function(c){var d=a.$new();d.$$transcluded=!0;return b(d,c).on("$destroy",nb(d,d.$destroy))}}(l||b)):c(p,m,h,s,e)):p&&p(a,h.childNodes,s,e)}for(var g=[],p,h,l,m=0;m<a.length;m++)h=new xb,p=ba(a[m],[],h,0==m?d:s,e),h=(p=p.length?ka(p,a[m],h,b,
c):null)&&p.terminal||!a[m].childNodes||!a[m].childNodes.length?null:Z(a[m].childNodes,p?p.transclude:b),g.push(p),g.push(h),l=l||p||h;return l?f:null}function ba(a,b,c,f,g){var p=c.$attr,h;switch(a.nodeType){case 1:G(b,la(Aa(a).toLowerCase()),"E",f,g);var m,l,n;h=a.attributes;for(var t=0,r=h&&h.length;t<r;t++){var C,y,Z;m=h[t];if(!Q||8<=Q||m.specified)l=m.name,n=la(l),A.test(n)&&(l=n.substr(6).toLowerCase()),-1!=(Z=n.lastIndexOf("Start"))&&Z==n.length-5&&(C=l,y=l.substr(0,l.length-5)+"end",l=l.substr(0,
l.length-6)),n=la(l.toLowerCase()),p[n]=l,c[n]=m=aa(Q&&"href"==l?decodeURIComponent(a.getAttribute(l,2)):m.value),Ub(a,n)&&(c[n]=!0),pa(a,b,m,n),G(b,n,"A",f,g,C,y)}a=a.className;if(H(a)&&""!==a)for(;h=e.exec(a);)n=la(h[2]),G(b,n,"C",f,g)&&(c[n]=aa(h[3])),a=a.substr(h.index+h[0].length);break;case 3:K(b,a.nodeValue);break;case 8:try{if(h=d.exec(a.nodeValue))n=la(h[1]),G(b,n,"M",f,g)&&(c[n]=aa(h[2]))}catch(I){}}b.sort(L);return b}function W(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ga("uterdir",
b,c);1==a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return w(d)}function ea(a,b,c){return function(d,e,f,g){e=W(e[0],b,c);return a(d,e,f,g)}}function ka(a,b,c,d,e,f){function g(a,b,c,d){a&&(c&&(a=ea(a,c,d)),a.require=u.require,t.push(a));b&&(c&&(b=ea(b,c,d)),b.require=u.require,Z.push(b))}function h(a,b){var c,d="data",e=!1;if(H(a)){for(;"^"==(c=a.charAt(0))||"?"==c;)a=a.substr(1),"^"==c&&(d="inheritedData"),e=e||"?"==c;c=b[d]("$"+
a+"Controller");if(!c&&!e)throw ga("ctreq",a,R);}else D(a)&&(c=[],q(a,function(a){c.push(h(a,b))}));return c}function l(a,d,e,f,g){var n,C,u,I,x;n=b===e?c:Fc(c,new xb(w(e),c.$attr));C=n.$$element;if(v){var K=/^\s*([@=&])(\??)\s*(\w*)\s*$/,F=d.$parent||d;q(v.scope,function(a,b){var c=a.match(K)||[],e=c[3]||b,f="?"==c[2],c=c[1],g,h,p;d.$$isolateBindings[b]=c+e;switch(c){case "@":n.$observe(e,function(a){d[b]=a});n.$$observers[e].$$scope=F;n[e]&&(d[b]=m(n[e])(F));break;case "=":if(f&&!n[e])break;h=r(n[e]);
p=h.assign||function(){g=d[b]=h(F);throw ga("nonassign",n[e],v.name);};g=d[b]=h(F);d.$watch(function(){var a=h(F);a!==d[b]&&(a!==g?g=d[b]=a:p(F,a=g=d[b]));return a});break;case "&":h=r(n[e]);d[b]=function(a){return h(F,a)};break;default:throw ga("iscp",v.name,b,a);}})}pa&&q(pa,function(a){var b={$scope:d,$element:C,$attrs:n,$transclude:g},c;x=a.controller;"@"==x&&(x=n[a.name]);c=y(x,b);C.data("$"+a.name+"Controller",c);a.controllerAs&&(b.$scope[a.controllerAs]=c)});f=0;for(u=t.length;f<u;f++)try{I=
t[f],I(d,C,n,I.require&&h(I.require,C))}catch(G){p(G,ia(C))}a&&a(d,e.childNodes,s,g);f=0;for(u=Z.length;f<u;f++)try{I=Z[f],I(d,C,n,I.require&&h(I.require,C))}catch(ba){p(ba,ia(C))}}for(var n=-Number.MAX_VALUE,t=[],Z=[],x=null,v=null,G=null,K=c.$$element=w(b),u,R,O,N,qa=d,pa,ka,L=0,ma=a.length;L<ma;L++){u=a[L];var A=u.$$start,z=u.$$end;A&&(K=W(b,A,z));O=s;if(n>u.priority)break;if(O=u.scope)C("isolated scope",v,u,K),U(O)&&(I(K,"ng-isolate-scope"),v=u),I(K,"ng-scope"),x=x||u;R=u.name;if(O=u.controller)pa=
pa||{},C("'"+R+"' controller",pa[R],u,K),pa[R]=u;if(O=u.transclude)C("transclusion",N,u,K),N=u,n=u.priority,"element"==O?(O=W(b,A,z),K=c.$$element=w(T.createComment(" "+R+": "+c[R]+" ")),b=K[0],bb(e,w(ta.call(O,0)),b),qa=F(O,d,n,f&&f.name)):(O=w(vb(b)).contents(),K.html(""),qa=F(O,d));if(u.template)if(C("template",G,u,K),G=u,O=B(u.template)?u.template(K,c):u.template,O=Yb(O),u.replace){f=u;O=w("<div>"+aa(O)+"</div>").contents();b=O[0];if(1!=O.length||1!==b.nodeType)throw ga("tplrt",R,"");bb(e,K,b);
ma={$attr:{}};a=a.concat(ba(b,a.splice(L+1,a.length-(L+1)),ma));ab(c,ma);ma=a.length}else K.html(O);if(u.templateUrl)C("template",G,u,K),G=u,u.replace&&(f=u),l=Uc(a.splice(L,a.length-L),l,K,c,e,qa),ma=a.length;else if(u.compile)try{ka=u.compile(K,c,qa),B(ka)?g(null,ka,A,z):ka&&g(ka.pre,ka.post,A,z)}catch(E){p(E,ia(K))}u.terminal&&(l.terminal=!0,n=Math.max(n,u.priority))}l.scope=x&&x.scope;l.transclude=N&&qa;return l}function G(d,e,f,g,h,n,m){if(e===h)return null;h=null;if(b.hasOwnProperty(e)){var t;
e=a.get(e+c);for(var r=0,C=e.length;r<C;r++)try{t=e[r],(g===s||g>t.priority)&&-1!=t.restrict.indexOf(f)&&(n&&(t=Cc(t,{$$start:n,$$end:m})),d.push(t),h=t)}catch(u){p(u)}}return h}function ab(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;q(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});q(b,function(b,f){"class"==f?(I(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?e.attr("style",e.attr("style")+";"+b):"$"==f.charAt(0)||a.hasOwnProperty(f)||
(a[f]=b,d[f]=c[f])})}function Uc(a,b,c,d,e,f){var g=[],h,p,l=c[0],m=a.shift(),r=E({},m,{controller:null,templateUrl:null,transclude:null,scope:null,replace:null}),C=B(m.templateUrl)?m.templateUrl(c,d):m.templateUrl;c.html("");n.get(N.getTrustedResourceUrl(C),{cache:t}).success(function(n){var t;n=Yb(n);if(m.replace){n=w("<div>"+aa(n)+"</div>").contents();t=n[0];if(1!=n.length||1!==t.nodeType)throw ga("tplrt",m.name,C);n={$attr:{}};bb(e,c,t);ba(t,a,n);ab(d,n)}else t=l,c.html(n);a.unshift(r);h=ka(a,
t,d,f,c,m);q(e,function(a,b){a==t&&(e[b]=c[0])});for(p=Z(c[0].childNodes,f);g.length;){n=g.shift();var u=g.shift(),y=g.shift(),I=g.shift(),x=c[0];u!==l&&(x=vb(t),bb(y,w(u),x));h(b(p,n,x,e,I),n,x,e,I)}g=null}).error(function(a,b,c,d){throw ga("tpload",d.url);});return function(a,c,d,e,f){g?(g.push(c),g.push(d),g.push(e),g.push(f)):h(function(){b(p,c,d,e,f)},c,d,e,f)}}function L(a,b){return b.priority-a.priority}function C(a,b,c,d){if(b)throw ga("multidir",b.name,c.name,a,ia(d));}function K(a,b){var c=
m(b,!0);c&&a.push({priority:0,compile:$(function(a,b){var d=b.parent(),e=d.data("$binding")||[];e.push(c);I(d.data("$binding",e),"ng-binding");a.$watch(c,function(a){b[0].nodeValue=a})})})}function O(a,b){if("xlinkHref"==b||"IMG"!=Aa(a)&&("src"==b||"ngSrc"==b))return N.RESOURCE_URL}function pa(a,b,c,d){var e=m(c,!0);if(e){if("multiple"===d&&"SELECT"===Aa(a))throw ga("selmulti",ia(a));b.push({priority:100,compile:$(function(b,c,g){c=g.$$observers||(g.$$observers={});if(f.test(d))throw ga("nodomevents");
if(e=m(g[d],!0,O(a,d)))g[d]=e(b),(c[d]||(c[d]=[])).$$inter=!0,(g.$$observers&&g.$$observers[d].$$scope||b).$watch(e,function(a){g.$set(d,a)})})})}}function bb(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g<h;g++)if(a[g]==d){a[g++]=c;h=g+e-1;for(var p=a.length;g<p;g++,h++)h<p?a[g]=a[h]:delete a[g];a.length-=e-1;break}f&&f.replaceChild(c,d);a=T.createDocumentFragment();a.appendChild(d);c[w.expando]=d[w.expando];d=1;for(e=b.length;d<e;d++)f=b[d],w(f).remove(),a.appendChild(f),
delete b[d];b[0]=c;b.length=1}var xb=function(a,b){this.$$element=a;this.$attr=b||{}};xb.prototype={$normalize:la,$addClass:function(a){a&&0<a.length&&v.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&v.removeClass(this.$$element,a)},$set:function(a,b,c,d){function e(a,b){var c=[],d=a.split(/\s+/),f=b.split(/\s+/),g=0;a:for(;g<d.length;g++){for(var h=d[g],p=0;p<f.length;p++)if(h==f[p])continue a;c.push(h)}return c}if("class"==a)b=b||"",c=this.$$element.attr("class")||"",this.$removeClass(e(c,
b).join(" ")),this.$addClass(e(b,c).join(" "));else{var f=Ub(this.$$element[0],a);f&&(this.$$element.prop(a,b),d=f);this[a]=b;d?this.$attr[a]=d:(d=this.$attr[a])||(this.$attr[a]=d=pb(a,"-"));f=Aa(this.$$element);if("A"===f&&"href"===a||"IMG"===f&&"src"===a)if(!Q||8<=Q)f=u.resolve(b),""!==f&&("href"===a&&!f.match(g)||"src"===a&&!f.match(h))&&(this[a]=b="unsafe:"+f);!1!==c&&(null===b||b===s?this.$$element.removeAttr(d):this.$$element.attr(d,b))}(c=this.$$observers)&&q(c[a],function(a){try{a(b)}catch(c){p(c)}})},
$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers={}),e=d[a]||(d[a]=[]);e.push(b);x.$evalAsync(function(){e.$$inter||b(c[a])});return b}};R[0].createElement("a");var ma=m.startSymbol(),qa=m.endSymbol(),Yb="{{"==ma||"}}"==qa?wa:function(a){return a.replace(/\{\{/g,ma).replace(/}}/g,qa)},A=/^ngAttr[A-Z]/;return F}]}function la(a){return Ja(a.replace(Yc,""))}function Zc(){var a={},b=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(b,d){U(b)?E(a,b):a[b]=d};this.$get=["$injector","$window",
function(c,d){return function(e,g){var h,f,k;H(e)&&(h=e.match(b),f=h[1],k=h[3],e=a.hasOwnProperty(f)?a[f]:rb(g.$scope,f,!0)||rb(d,f,!0),Ia(e,f,!0));h=c.instantiate(e,g);if(k){if(!g||"object"!=typeof g.$scope)throw P("$controller")("noscp",f||e.name,k);g.$scope[k]=h}return h}}]}function $c(){this.$get=["$window",function(a){return w(a.document)}]}function ad(){this.$get=["$log",function(a){return function(b,c){a.error.apply(a,arguments)}}]}function Zb(a){var b={},c,d,e;if(!a)return b;q(a.split("\n"),
function(a){e=a.indexOf(":");c=J(aa(a.substr(0,e)));d=aa(a.substr(e+1));c&&(b[c]=b[c]?b[c]+(", "+d):d)});return b}function $b(a){var b=U(a)?a:s;return function(c){b||(b=Zb(a));return c?b[J(c)]||null:b}}function ac(a,b,c){if(B(c))return c(a,b);q(c,function(c){a=c(a,b)});return a}function bd(){var a=/^\s*(\[|\{[^\{])/,b=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d={"Content-Type":"application/json;charset=utf-8"},e=this.defaults={transformResponse:[function(d){H(d)&&(d=d.replace(c,""),a.test(d)&&b.test(d)&&(d=Ib(d)));
return d}],transformRequest:[function(a){return U(a)&&"[object File]"!==Ua.apply(a)?oa(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:d,put:d,patch:d},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"},g=this.interceptors=[],h=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector","$$urlUtils",function(a,b,c,d,p,n,t){function r(a){function c(a){var b=E({},a,{data:ac(a.data,a.headers,d.transformResponse)});return 200<=
a.status&&300>a.status?b:p.reject(b)}var d={transformRequest:e.transformRequest,transformResponse:e.transformResponse},f=function(a){function b(a){var c;q(a,function(b,d){B(b)&&(c=b(),null!=c?a[d]=c:delete a[d])})}var c=e.headers,d=E({},a.headers),f,g,c=E({},c.common,c[J(a.method)]);b(c);b(d);a:for(f in c){a=J(f);for(g in d)if(J(g)===a)continue a;d[f]=c[f]}return d}(a);E(d,a);d.headers=f;d.method=Ba(d.method);(a=t.isSameOrigin(d.url)?b.cookies()[d.xsrfCookieName||e.xsrfCookieName]:s)&&(f[d.xsrfHeaderName||
e.xsrfHeaderName]=a);var g=[function(a){f=a.headers;var b=ac(a.data,$b(f),a.transformRequest);M(a.data)&&q(f,function(a,b){"content-type"===J(b)&&delete f[b]});M(a.withCredentials)&&!M(e.withCredentials)&&(a.withCredentials=e.withCredentials);return y(a,b,f).then(c,c)},s],h=p.when(d);for(q(N,function(a){(a.request||a.requestError)&&g.unshift(a.request,a.requestError);(a.response||a.responseError)&&g.push(a.response,a.responseError)});g.length;){a=g.shift();var n=g.shift(),h=h.then(a,n)}h.success=
function(a){h.then(function(b){a(b.data,b.status,b.headers,d)});return h};h.error=function(a){h.then(null,function(b){a(b.data,b.status,b.headers,d)});return h};return h}function y(b,c,g){function k(a,b,c){y&&(200<=a&&300>a?y.put(s,[a,b,Zb(c)]):y.remove(s));h(b,a,c);d.$$phase||d.$apply()}function h(a,c,d){c=Math.max(c,0);(200<=c&&300>c?l.resolve:l.reject)({data:a,status:c,headers:$b(d),config:b})}function n(){var a=Va(r.pendingRequests,b);-1!==a&&r.pendingRequests.splice(a,1)}var l=p.defer(),t=l.promise,
y,q,s=x(b.url,b.params);r.pendingRequests.push(b);t.then(n,n);(b.cache||e.cache)&&(!1!==b.cache&&"GET"==b.method)&&(y=U(b.cache)?b.cache:U(e.cache)?e.cache:R);if(y)if(q=y.get(s),z(q)){if(q.then)return q.then(n,n),q;D(q)?h(q[1],q[0],da(q[2])):h(q,200,{})}else y.put(s,t);M(q)&&a(b.method,s,c,k,g,b.timeout,b.withCredentials,b.responseType);return t}function x(a,b){if(!b)return a;var c=[];Bc(b,function(a,b){null!=a&&a!=s&&(D(a)||(a=[a]),q(a,function(a){U(a)&&(a=oa(a));c.push(ua(b)+"="+ua(a))}))});return a+
(-1==a.indexOf("?")?"?":"&")+c.join("&")}var R=c("$http"),N=[];q(g,function(a){N.unshift(H(a)?n.get(a):n.invoke(a))});q(h,function(a,b){var c=H(a)?n.get(a):n.invoke(a);N.splice(b,0,{response:function(a){return c(p.when(a))},responseError:function(a){return c(p.reject(a))}})});r.pendingRequests=[];(function(a){q(arguments,function(a){r[a]=function(b,c){return r(E(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){q(arguments,function(a){r[a]=function(b,c,d){return r(E(d||{},
{method:a,url:b,data:c}))}})})("post","put");r.defaults=e;return r}]}function cd(){this.$get=["$browser","$window","$document",function(a,b,c){return dd(a,ed,a.defer,b.angular.callbacks,c[0],b.location.protocol.replace(":",""))}]}function dd(a,b,c,d,e,g){function h(a,b){var c=e.createElement("script"),d=function(){e.body.removeChild(c);b&&b()};c.type="text/javascript";c.src=a;Q?c.onreadystatechange=function(){/loaded|complete/.test(c.readyState)&&d()}:c.onload=c.onerror=d;e.body.appendChild(c);return d}
return function(e,k,l,m,p,n,t,r){function y(){R=-1;u&&u();v&&v.abort()}function x(b,d,e,f){var h=(k.match(bc)||["",g])[1];F&&c.cancel(F);u=v=null;d="file"==h?e?200:404:d;b(1223==d?204:d,e,f);a.$$completeOutstandingRequest(A)}var R;a.$$incOutstandingRequestCount();k=k||a.url();if("jsonp"==J(e)){var s="_"+(d.counter++).toString(36);d[s]=function(a){d[s].data=a};var u=h(k.replace("JSON_CALLBACK","angular.callbacks."+s),function(){d[s].data?x(m,200,d[s].data):x(m,R||-2);delete d[s]})}else{var v=new b;
v.open(e,k,!0);q(p,function(a,b){a&&v.setRequestHeader(b,a)});v.onreadystatechange=function(){if(4==v.readyState){var a=v.getAllResponseHeaders(),b="Cache-Control Content-Language Content-Type Expires Last-Modified Pragma".split(" ");a||(a="",q(b,function(b){var c=v.getResponseHeader(b);c&&(a+=b+": "+c+"\n")}));x(m,R||v.status,v.responseType?v.response:v.responseText,a)}};t&&(v.withCredentials=!0);r&&(v.responseType=r);v.send(l||"")}if(0<n)var F=c(y,n);else n&&n.then&&n.then(y)}}function fd(){var a=
"{{",b="}}";this.startSymbol=function(b){return b?(a=b,this):a};this.endSymbol=function(a){return a?(b=a,this):b};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function g(g,l,m){for(var p,n,t=0,r=[],y=g.length,x=!1,q=[];t<y;)-1!=(p=g.indexOf(a,t))&&-1!=(n=g.indexOf(b,p+h))?(t!=p&&r.push(g.substring(t,p)),r.push(t=c(x=g.substring(p+h,n))),t.exp=x,t=n+f,x=!0):(t!=y&&r.push(g.substring(t)),t=y);(y=r.length)||(r.push(""),y=1);if(m&&1<r.length)throw cc("noconcat",g);if(!l||x)return q.length=
y,t=function(a){try{for(var b=0,c=y,f;b<c;b++)"function"==typeof(f=r[b])&&(f=f(a),f=m?e.getTrusted(m,f):e.valueOf(f),null==f||f==s?f="":"string"!=typeof f&&(f=oa(f))),q[b]=f;return q.join("")}catch(h){a=cc("interr",g,h.toString()),d(a)}},t.exp=g,t.parts=r,t}var h=a.length,f=b.length;g.startSymbol=function(){return a};g.endSymbol=function(){return b};return g}]}function gd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,
posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM",
"PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(a){return 1===a?"one":"other"}}}}function dc(a){a=a.split("/");for(var b=a.length;b--;)a[b]=ob(a[b]);return a.join("/")}function ec(a,b){var c=bc.exec(a);b.$$protocol=c[1];b.$$host=c[3];b.$$port=V(c[5])||hd[c[1]]||null}function fc(a,b){var c=gc.exec(a);b.$$path=decodeURIComponent(c[1]);b.$$search=
Kb(c[3]);b.$$hash=decodeURIComponent(c[5]||"");b.$$path&&"/"!=b.$$path.charAt(0)&&(b.$$path="/"+b.$$path)}function na(a,b,c){return 0==b.indexOf(a)?b.substr(a.length):c}function Qa(a){var b=a.indexOf("#");return-1==b?a:a.substr(0,b)}function yb(a){return a.substr(0,Qa(a).lastIndexOf("/")+1)}function hc(a,b){this.$$html5=!0;b=b||"";var c=yb(a);this.$$parse=function(a){var b={};ec(a,b);var g=na(c,a);if(!H(g))throw zb("ipthprfx",a,c);fc(g,b);E(this,b);this.$$path||(this.$$path="/");this.$$compose()};
this.$$compose=function(){var a=Lb(this.$$search),b=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=dc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$rewrite=function(d){var e;if((e=na(a,d))!==s)return d=e,(e=na(b,e))!==s?c+(na("/",e)||e):a+d;if((e=na(c,d))!==s)return c+e;if(c==d+"/")return c}}function Ab(a,b){var c=yb(a);ec(a,this);this.$$parse=function(d){var e=na(a,d)||na(c,d),e="#"==e.charAt(0)?na(b,e):this.$$html5?e:"";if(!H(e))throw zb("ihshprfx",d,b);fc(e,this);this.$$compose()};
this.$$compose=function(){var c=Lb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=dc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=a+(this.$$url?b+this.$$url:"")};this.$$rewrite=function(b){if(Qa(a)==Qa(b))return b}}function ic(a,b){this.$$html5=!0;Ab.apply(this,arguments);var c=yb(a);this.$$rewrite=function(d){var e;if(a==Qa(d))return d;if(e=na(c,d))return a+b+e;if(c===d+"/")return c}}function cb(a){return function(){return this[a]}}function jc(a,b){return function(c){if(M(c))return this[a];
this[a]=b(c);this.$$compose();return this}}function id(){var a="",b=!1;this.hashPrefix=function(b){return z(b)?(a=b,this):a};this.html5Mode=function(a){return z(a)?(b=a,this):b};this.$get=["$rootScope","$browser","$sniffer","$rootElement",function(c,d,e,g){function h(a){c.$broadcast("$locationChangeSuccess",f.absUrl(),a)}var f,k=d.baseHref(),l=d.url();b?(k=l.substring(0,l.indexOf("/",l.indexOf("//")+2))+(k||"/"),e=e.history?hc:ic):(k=Qa(l),e=Ab);f=new e(k,"#"+a);f.$$parse(f.$$rewrite(l));g.on("click",
function(a){if(!a.ctrlKey&&!a.metaKey&&2!=a.which){for(var b=w(a.target);"a"!==J(b[0].nodeName);)if(b[0]===g[0]||!(b=b.parent())[0])return;var e=b.prop("href"),h=f.$$rewrite(e);e&&(!b.attr("target")&&h&&!a.isDefaultPrevented())&&(a.preventDefault(),h!=d.url()&&(f.$$parse(h),c.$apply(),Y.angular["ff-684208-preventDefault"]=!0))}});f.absUrl()!=l&&d.url(f.absUrl(),!0);d.onUrlChange(function(a){f.absUrl()!=a&&(c.$broadcast("$locationChangeStart",a,f.absUrl()).defaultPrevented?d.url(f.absUrl()):(c.$evalAsync(function(){var b=
f.absUrl();f.$$parse(a);h(b)}),c.$$phase||c.$digest()))});var m=0;c.$watch(function(){var a=d.url(),b=f.$$replace;m&&a==f.absUrl()||(m++,c.$evalAsync(function(){c.$broadcast("$locationChangeStart",f.absUrl(),a).defaultPrevented?f.$$parse(a):(d.url(f.absUrl(),b),h(a))}));f.$$replace=!1;return m});return f}]}function jd(){var a=!0,b=this;this.debugEnabled=function(b){return z(b)?(a=b,this):a};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?
"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||A;return e.apply?function(){var a=[];q(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){a&&c.apply(b,arguments)}}()}}]}function ra(a,b){if("constructor"===a)throw Ra("isecfld",b);return a}function kc(a,
b){if(a&&a.constructor===a)throw Ra("isecfn",b);return a}function kd(a,b){function c(a){return-1!=a.indexOf(x)}function d(b){b=b||1;return r+b<a.length?a.charAt(r+b):!1}function e(a){return"0"<=a&&"9">=a}function g(a){return" "==a||"\r"==a||"\t"==a||"\n"==a||"\v"==a||"\u00a0"==a}function h(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"==a||"$"==a}function f(a){return"-"==a||"+"==a||e(a)}function k(b,c,d){d=d||r;c=z(c)?"s "+c+"-"+r+" ["+a.substring(c,d)+"]":" "+d;throw Ra("lexerr",b,c,a);}function l(){for(var b=
"",c=r;r<a.length;){var g=J(a.charAt(r));if("."==g||e(g))b+=g;else{var h=d();if("e"==g&&f(h))b+=g;else if(f(g)&&h&&e(h)&&"e"==b.charAt(b.length-1))b+=g;else if(!f(g)||h&&e(h)||"e"!=b.charAt(b.length-1))break;else k("Invalid exponent")}r++}b*=1;n.push({index:c,text:b,json:!0,fn:function(){return b}})}function m(){for(var c="",d=r,f,k,p,m;r<a.length;){m=a.charAt(r);if("."==m||h(m)||e(m))"."==m&&(f=r),c+=m;else break;r++}if(f)for(k=r;k<a.length;){m=a.charAt(k);if("("==m){p=c.substr(f-d+1);c=c.substr(0,
f-d);r=k;break}if(g(m))k++;else break}d={index:d,text:c};if(Sa.hasOwnProperty(c))d.fn=d.json=Sa[c];else{var l=lc(c,b,a);d.fn=E(function(a,b){return l(a,b)},{assign:function(b,d){return db(b,c,d,a)}})}n.push(d);p&&(n.push({index:f,text:".",json:!1}),n.push({index:f+1,text:p,json:!1}))}function p(b){var c=r;r++;for(var d="",e=b,f=!1;r<a.length;){var g=a.charAt(r),e=e+g;if(f)"u"==g?(g=a.substring(r+1,r+5),g.match(/[\da-f]{4}/i)||k("Invalid unicode escape [\\u"+g+"]"),r+=4,d+=String.fromCharCode(parseInt(g,
16))):d=(f=ld[g])?d+f:d+g,f=!1;else if("\\"==g)f=!0;else{if(g==b){r++;n.push({index:c,text:e,string:d,json:!0,fn:function(){return d}});return}d+=g}r++}k("Unterminated quote",c)}for(var n=[],t,r=0,y=[],x,q=":";r<a.length;){x=a.charAt(r);if(c("\"'"))p(x);else if(e(x)||c(".")&&e(d()))l();else if(h(x))m(),-1!="{,".indexOf(q)&&("{"==y[0]&&(t=n[n.length-1]))&&(t.json=-1==t.text.indexOf("."));else if(c("(){}[].,;:?"))n.push({index:r,text:x,json:-1!=":[,".indexOf(q)&&c("{[")||c("}]:,")}),c("{[")&&y.unshift(x),
c("}]")&&y.shift(),r++;else if(g(x)){r++;continue}else{var s=x+d(),u=s+d(2),v=Sa[x],F=Sa[s],I=Sa[u];I?(n.push({index:r,text:u,fn:I}),r+=3):F?(n.push({index:r,text:s,fn:F}),r+=2):v?(n.push({index:r,text:x,fn:v,json:-1!="[,:".indexOf(q)&&c("+-")}),r+=1):k("Unexpected next character ",r,r+1)}q=x}return n}function md(a,b,c,d){function e(b,c){throw Ra("syntax",c.text,b,c.index+1,a,a.substring(c.index));}function g(){if(0===ea.length)throw Ra("ueoe",a);return ea[0]}function h(a,b,c,d){if(0<ea.length){var e=
ea[0],f=e.text;if(f==a||f==b||f==c||f==d||!(a||b||c||d))return e}return!1}function f(a,c,d,f){return(a=h(a,c,d,f))?(b&&!a.json&&e("is not valid json",a),ea.shift(),a):!1}function k(a){f(a)||e("is unexpected, expecting ["+a+"]",h())}function l(a,b){return E(function(c,d){return a(c,d,b)},{constant:b.constant})}function m(a,b,c){return E(function(d,e){return a(d,e)?b(d,e):c(d,e)},{constant:a.constant&&b.constant&&c.constant})}function p(a,b,c){return E(function(d,e){return b(d,e,a,c)},{constant:a.constant&&
c.constant})}function n(){for(var a=[];;)if(0<ea.length&&!h("}",")",";","]")&&a.push(L()),!f(";"))return 1==a.length?a[0]:function(b,c){for(var d,e=0;e<a.length;e++){var f=a[e];f&&(d=f(b,c))}return d}}function t(){for(var a=f(),b=c(a.text),d=[];;)if(a=f(":"))d.push(z());else{var e=function(a,c,e){e=[e];for(var f=0;f<d.length;f++)e.push(d[f](a,c));return b.apply(a,e)};return function(){return e}}}function r(){var a=y(),b,c;if(f("?")){b=r();if(c=f(":"))return m(a,b,r());e("expected :",c)}else return a}
function y(){for(var a=x(),b;;)if(b=f("||"))a=p(a,b.fn,x());else return a}function x(){var a=q(),b;if(b=f("&&"))a=p(a,b.fn,x());return a}function q(){var a=N(),b;if(b=f("==","!=","===","!=="))a=p(a,b.fn,q());return a}function N(){var a;a=u();for(var b;b=f("+","-");)a=p(a,b.fn,u());if(b=f("<",">","<=",">="))a=p(a,b.fn,N());return a}function u(){for(var a=v(),b;b=f("*","/","%");)a=p(a,b.fn,v());return a}function v(){var a;return f("+")?F():(a=f("-"))?p(ba,a.fn,v()):(a=f("!"))?l(a.fn,v()):F()}function F(){var a;
if(f("("))a=L(),k(")");else if(f("["))a=I();else if(f("{"))a=w();else{var b=f();(a=b.fn)||e("not a primary expression",b);b.json&&(a.constant=a.literal=!0)}for(var c;b=f("(","[",".");)"("===b.text?(a=G(a,c),c=null):"["===b.text?(c=a,a=D(a)):"."===b.text?(c=a,a=H(a)):e("IMPOSSIBLE");return a}function I(){var a=[],b=!0;if("]"!=g().text){do{var c=z();a.push(c);c.constant||(b=!1)}while(f(","))}k("]");return E(function(b,c){for(var d=[],e=0;e<a.length;e++)d.push(a[e](b,c));return d},{literal:!0,constant:b})}
function w(){var a=[],b=!0;if("}"!=g().text){do{var c=f(),c=c.string||c.text;k(":");var d=z();a.push({key:c,value:d});d.constant||(b=!1)}while(f(","))}k("}");return E(function(b,c){for(var d={},e=0;e<a.length;e++){var f=a[e];d[f.key]=f.value(b,c)}return d},{literal:!0,constant:b})}var ba=$(0),W,ea=kd(a,d),z=function(){var b=r(),c,d;return(d=f("="))?(b.assign||e("implies assignment but ["+a.substring(0,d.index)+"] can not be assigned to",d),c=r(),function(a,d){return b.assign(a,c(a,d),d)}):b},G=function(a,
b){var c=[];if(")"!=g().text){do c.push(z());while(f(","))}k(")");return function(d,e){for(var f=[],g=b?b(d,e):d,h=0;h<c.length;h++)f.push(c[h](d,e));h=a(d,e,g)||A;if((f=h.apply?h.apply(g,f):h(f[0],f[1],f[2],f[3],f[4]))&&f.then){var k=f;"$$v"in f||(k.$$v=s,k.then(function(a){k.$$v=a}));f=f.$$v}return f}},H=function(b){var c=f().text,e=lc(c,d,a);return E(function(a,c,d){return e(d||b(a,c),c)},{assign:function(d,e,f){return db(b(d,f),c,e,a)}})},D=function(b){var c=z();k("]");return E(function(d,e){var f=
b(d,e),g=c(d,e),h;if(!f)return s;(f=kc(f[g],a))&&f.then&&(h=f,"$$v"in f||(h.$$v=s,h.then(function(a){h.$$v=a})),f=f.$$v);return f},{assign:function(d,e,f){var g=c(d,f);return kc(b(d,f),a)[g]=e}})},L=function(){for(var a=z(),b;;)if(b=f("|"))a=p(a,b.fn,t());else return a};b?(z=y,G=H=D=L=function(){e("is not valid json",{text:a,index:0})},W=F()):W=n();0!==ea.length&&e("is an unexpected token",ea[0]);W.literal=!!W.literal;W.constant=!!W.constant;return W}function db(a,b,c,d){b=b.split(".");for(var e,
g=0;1<b.length;g++){e=ra(b.shift(),d);var h=a[e];h||(h={},a[e]=h);a=h;a.then&&("$$v"in a||function(a){a.then(function(b){a.$$v=b})}(a),a.$$v===s&&(a.$$v={}),a=a.$$v)}e=ra(b.shift(),d);return a[e]=c}function mc(a,b,c,d,e,g){ra(a,g);ra(b,g);ra(c,g);ra(d,g);ra(e,g);return function(g,f){var k=f&&f.hasOwnProperty(a)?f:g,l;if(null===k||k===s)return k;(k=k[a])&&k.then&&("$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!b||null===k||k===s)return k;(k=k[b])&&k.then&&("$$v"in k||(l=k,l.$$v=
s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!c||null===k||k===s)return k;(k=k[c])&&k.then&&("$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!d||null===k||k===s)return k;(k=k[d])&&k.then&&("$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!e||null===k||k===s)return k;(k=k[e])&&k.then&&("$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);return k}}function lc(a,b,c){if(Bb.hasOwnProperty(a))return Bb[a];var d=a.split("."),e=d.length;if(b)b=6>e?mc(d[0],d[1],
d[2],d[3],d[4],c):function(a,b){var g=0,l;do l=mc(d[g++],d[g++],d[g++],d[g++],d[g++],c)(a,b),b=s,a=l;while(g<e);return l};else{var g="var l, fn, p;\n";q(d,function(a,b){ra(a,c);g+="if(s === null || s === undefined) return s;\nl=s;\ns="+(b?"s":'((k&&k.hasOwnProperty("'+a+'"))?k:s)')+'["'+a+'"];\nif (s && s.then) {\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n'});g+="return s;";b=Function("s","k",g);b.toString=function(){return g}}return Bb[a]=
b}function nd(){var a={};this.$get=["$filter","$sniffer",function(b,c){return function(d){switch(typeof d){case "string":return a.hasOwnProperty(d)?a[d]:a[d]=md(d,!1,b,c.csp);case "function":return d;default:return A}}}]}function od(){this.$get=["$rootScope","$exceptionHandler",function(a,b){return pd(function(b){a.$evalAsync(b)},b)}]}function pd(a,b){function c(a){return a}function d(a){return h(a)}var e=function(){var f=[],k,l;return l={resolve:function(b){if(f){var c=f;f=s;k=g(b);c.length&&a(function(){for(var a,
b=0,d=c.length;b<d;b++)a=c[b],k.then(a[0],a[1],a[2])})}},reject:function(a){l.resolve(h(a))},notify:function(b){if(f){var c=f;f.length&&a(function(){for(var a,d=0,e=c.length;d<e;d++)a=c[d],a[2](b)})}},promise:{then:function(a,g,h){var l=e(),r=function(d){try{l.resolve((B(a)?a:c)(d))}catch(e){l.reject(e),b(e)}},y=function(a){try{l.resolve((B(g)?g:d)(a))}catch(c){l.reject(c),b(c)}},x=function(a){try{l.notify((B(h)?h:c)(a))}catch(d){b(d)}};f?f.push([r,y,x]):k.then(r,y,x);return l.promise},"catch":function(a){return this.then(null,
a)},"finally":function(a){function b(a,c){var d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,f){var g=null;try{g=(a||c)()}catch(h){return b(h,!1)}return g&&B(g.then)?g.then(function(){return b(e,f)},function(a){return b(a,!1)}):b(e,f)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}}}},g=function(b){return b&&B(b.then)?b:{then:function(c){var d=e();a(function(){d.resolve(c(b))});return d.promise}}},h=function(c){return{then:function(g,h){var m=e();a(function(){try{m.resolve((B(h)?
h:d)(c))}catch(a){m.reject(a),b(a)}});return m.promise}}};return{defer:e,reject:h,when:function(f,k,l,m){var p=e(),n,t=function(a){try{return(B(k)?k:c)(a)}catch(d){return b(d),h(d)}},r=function(a){try{return(B(l)?l:d)(a)}catch(c){return b(c),h(c)}},y=function(a){try{return(B(m)?m:c)(a)}catch(d){b(d)}};a(function(){g(f).then(function(a){n||(n=!0,p.resolve(g(a).then(t,r,y)))},function(a){n||(n=!0,p.resolve(r(a)))},function(a){n||p.notify(y(a))})});return p.promise},all:function(a){var b=e(),c=0,d=D(a)?
[]:{};q(a,function(a,e){c++;g(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise}}}function qd(){var a=10,b=P("$rootScope");this.digestTtl=function(b){arguments.length&&(a=b);return a};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(c,d,e,g){function h(){this.$id=Ta();this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=
null;this["this"]=this.$root=this;this.$$destroyed=!1;this.$$asyncQueue=[];this.$$postDigestQueue=[];this.$$listeners={};this.$$isolateBindings={}}function f(a){if(m.$$phase)throw b("inprog",m.$$phase);m.$$phase=a}function k(a,b){var c=e(a);Ia(c,b);return c}function l(){}h.prototype={constructor:h,$new:function(a){a?(a=new h,a.$root=this.$root,a.$$asyncQueue=this.$$asyncQueue,a.$$postDigestQueue=this.$$postDigestQueue):(a=function(){},a.prototype=this,a=new a,a.$id=Ta());a["this"]=a;a.$$listeners=
{};a.$parent=this;a.$$watchers=a.$$nextSibling=a.$$childHead=a.$$childTail=null;a.$$prevSibling=this.$$childTail;this.$$childHead?this.$$childTail=this.$$childTail.$$nextSibling=a:this.$$childHead=this.$$childTail=a;return a},$watch:function(a,b,c){var d=k(a,"watch"),e=this.$$watchers,f={fn:b,last:l,get:d,exp:a,eq:!!c};if(!B(b)){var g=k(b||A,"listener");f.fn=function(a,b,c){g(c)}}if("string"==typeof a&&d.constant){var h=f.fn;f.fn=function(a,b,c){h.call(this,a,b,c);Fa(e,f)}}e||(e=this.$$watchers=[]);
e.unshift(f);return function(){Fa(e,f)}},$watchCollection:function(a,b){var c=this,d,f,g=0,h=e(a),k=[],l={},m=0;return this.$watch(function(){f=h(c);var a,b;if(U(f))if(kb(f))for(d!==k&&(d=k,m=d.length=0,g++),a=f.length,m!==a&&(g++,d.length=m=a),b=0;b<a;b++)d[b]!==f[b]&&(g++,d[b]=f[b]);else{d!==l&&(d=l={},m=0,g++);a=0;for(b in f)f.hasOwnProperty(b)&&(a++,d.hasOwnProperty(b)?d[b]!==f[b]&&(g++,d[b]=f[b]):(m++,d[b]=f[b],g++));if(m>a)for(b in g++,d)d.hasOwnProperty(b)&&!f.hasOwnProperty(b)&&(m--,delete d[b])}else d!==
f&&(d=f,g++);return g},function(){b(f,d,c)})},$digest:function(){var c,e,g,h,k=this.$$asyncQueue,q=this.$$postDigestQueue,s,N,u=a,v,F=[],I,z;f("$digest");do{N=!1;for(v=this;k.length;)try{v.$eval(k.shift())}catch(ba){d(ba)}do{if(h=v.$$watchers)for(s=h.length;s--;)try{(c=h[s])&&((e=c.get(v))!==(g=c.last)&&!(c.eq?xa(e,g):"number"==typeof e&&"number"==typeof g&&isNaN(e)&&isNaN(g)))&&(N=!0,c.last=c.eq?da(e):e,c.fn(e,g===l?e:g,v),5>u&&(I=4-u,F[I]||(F[I]=[]),z=B(c.exp)?"fn: "+(c.exp.name||c.exp.toString()):
c.exp,z+="; newVal: "+oa(e)+"; oldVal: "+oa(g),F[I].push(z)))}catch(W){d(W)}if(!(h=v.$$childHead||v!==this&&v.$$nextSibling))for(;v!==this&&!(h=v.$$nextSibling);)v=v.$parent}while(v=h);if(N&&!u--)throw m.$$phase=null,b("infdig",a,oa(F));}while(N||k.length);for(m.$$phase=null;q.length;)try{q.shift()()}catch(w){d(w)}},$destroy:function(){if(m!=this&&!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;a.$$childHead==this&&(a.$$childHead=this.$$nextSibling);a.$$childTail==
this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null}},$eval:function(a,b){return e(a)(this,b)},$evalAsync:function(a){m.$$phase||m.$$asyncQueue.length||g.defer(function(){m.$$asyncQueue.length&&m.$digest()});this.$$asyncQueue.push(a)},$$postDigest:function(a){this.$$postDigestQueue.push(a)},
$apply:function(a){try{return f("$apply"),this.$eval(a)}catch(b){d(b)}finally{m.$$phase=null;try{m.$digest()}catch(c){throw d(c),c;}}},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);return function(){c[Va(c,b)]=null}},$emit:function(a,b){var c=[],e,f=this,g=!1,h={name:a,targetScope:f,stopPropagation:function(){g=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},k=[h].concat(ta.call(arguments,1)),l,m;do{e=f.$$listeners[a]||c;h.currentScope=
f;l=0;for(m=e.length;l<m;l++)if(e[l])try{if(e[l].apply(null,k),g)return h}catch(q){d(q)}else e.splice(l,1),l--,m--;f=f.$parent}while(f);return h},$broadcast:function(a,b){var c=this,e=this,f={name:a,targetScope:this,preventDefault:function(){f.defaultPrevented=!0},defaultPrevented:!1},g=[f].concat(ta.call(arguments,1)),h,k;do{c=e;f.currentScope=c;e=c.$$listeners[a]||[];h=0;for(k=e.length;h<k;h++)if(e[h])try{e[h].apply(null,g)}catch(l){d(l)}else e.splice(h,1),h--,k--;if(!(e=c.$$childHead||c!==this&&
c.$$nextSibling))for(;c!==this&&!(e=c.$$nextSibling);)c=c.$parent}while(c=e);return f}};var m=new h;return m}]}function rd(){this.SCE_CONTEXTS=fa;var a=["self"],b=[];this.resourceUrlWhitelist=function(b){arguments.length&&(a=b);return a};this.resourceUrlBlacklist=function(a){arguments.length&&(b=a);return b};this.$get=["$log","$document","$injector","$$urlUtils",function(c,d,e,g){function h(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=
function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var f=function(a){throw Ca("unsafe");};e.has("$sanitize")&&(f=e.get("$sanitize"));var k=h(),l={};l[fa.HTML]=h(k);l[fa.CSS]=h(k);l[fa.URL]=h(k);l[fa.JS]=h(k);l[fa.RESOURCE_URL]=h(l[fa.URL]);return{trustAs:function(a,b){var c=l.hasOwnProperty(a)?l[a]:null;if(!c)throw Ca("icontext",a,b);if(null===b||b===s||""===b)return b;if("string"!==typeof b)throw Ca("itype",a);return new c(b)},
getTrusted:function(c,d){if(null===d||d===s||""===d)return d;var e=l.hasOwnProperty(c)?l[c]:null;if(e&&d instanceof e)return d.$$unwrapTrustedValue();if(c===fa.RESOURCE_URL){var e=g.resolve(d.toString(),!0),h,k,q=!1;h=0;for(k=a.length;h<k;h++)if("self"===a[h]?g.isSameOrigin(e):e.href.match(a[h])){q=!0;break}if(q)for(h=0,k=b.length;h<k;h++)if("self"===b[h]?g.isSameOrigin(e):e.href.match(b[h])){q=!1;break}if(q)return d;throw Ca("insecurl",d.toString());}if(c===fa.HTML)return f(d);throw Ca("unsafe");
},valueOf:function(a){return a instanceof k?a.$$unwrapTrustedValue():a}}}]}function sd(){var a=!0;this.enabled=function(b){arguments.length&&(a=!!b);return a};this.$get=["$parse","$document","$sceDelegate",function(b,c,d){if(a&&Q&&(c=c[0].documentMode,c!==s&&8>c))throw Ca("iequirks");var e=da(fa);e.isEnabled=function(){return a};e.trustAs=d.trustAs;e.getTrusted=d.getTrusted;e.valueOf=d.valueOf;a||(e.trustAs=e.getTrusted=function(a,b){return b},e.valueOf=wa);e.parseAs=function(a,c){var d=b(c);return d.literal&&
d.constant?d:function(b,c){return e.getTrusted(a,d(b,c))}};var g=e.parseAs,h=e.getTrusted,f=e.trustAs;Ha.forEach(fa,function(a,b){var c=J(b);e[Ja("parse_as_"+c)]=function(b){return g(a,b)};e[Ja("get_trusted_"+c)]=function(b){return h(a,b)};e[Ja("trust_as_"+c)]=function(b){return f(a,b)}});return e}]}function td(){this.$get=["$window","$document",function(a,b){var c={},d=V((/android (\d+)/.exec(J((a.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((a.navigator||{}).userAgent),g=b[0]||{},h,f=/^(Moz|webkit|O|ms)(?=[A-Z])/,
k=g.body&&g.body.style,l=!1,m=!1;if(k){for(var p in k)if(l=f.exec(p)){h=l[0];h=h.substr(0,1).toUpperCase()+h.substr(1);break}h||(h="WebkitOpacity"in k&&"webkit");l=!!("transition"in k||h+"Transition"in k);m=!!("animation"in k||h+"Animation"in k);!d||l&&m||(l=H(g.body.style.webkitTransition),m=H(g.body.style.webkitAnimation))}return{history:!(!a.history||!a.history.pushState||4>d||e),hashchange:"onhashchange"in a&&(!g.documentMode||7<g.documentMode),hasEvent:function(a){if("input"==a&&9==Q)return!1;
if(M(c[a])){var b=g.createElement("div");c[a]="on"+a in b}return c[a]},csp:g.securityPolicy?g.securityPolicy.isActive:!1,vendorPrefix:h,transitions:l,animations:m}}]}function ud(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",function(a,b,c,d){function e(e,f,k){var l=c.defer(),m=l.promise,p=z(k)&&!k;f=b.defer(function(){try{l.resolve(e())}catch(b){l.reject(b),d(b)}finally{delete g[m.$$timeoutId]}p||a.$apply()},f);m.$$timeoutId=f;g[f]=l;return m}var g={};e.cancel=function(a){return a&&
a.$$timeoutId in g?(g[a.$$timeoutId].reject("canceled"),delete g[a.$$timeoutId],b.defer.cancel(a.$$timeoutId)):!1};return e}]}function vd(){this.$get=[function(){function a(a,c){var g=a;11>=Q&&(b.setAttribute("href",g),g=b.href);b.setAttribute("href",g);return c?{href:b.href,protocol:b.protocol,host:b.host}:b.href}var b=T.createElement("a"),c=a(Y.location.href,!0);return{resolve:a,isSameOrigin:function(b){b="string"===typeof b?a(b,!0):b;return b.protocol===c.protocol&&b.host===c.host}}}]}function wd(){this.$get=
$(Y)}function nc(a){function b(b,e){return a.factory(b+c,e)}var c="Filter";this.register=b;this.$get=["$injector",function(a){return function(b){return a.get(b+c)}}];b("currency",oc);b("date",pc);b("filter",xd);b("json",yd);b("limitTo",zd);b("lowercase",Ad);b("number",qc);b("orderBy",rc);b("uppercase",Bd)}function xd(){return function(a,b,c){if(!D(a))return a;var d=[];d.check=function(a){for(var b=0;b<d.length;b++)if(!d[b](a))return!1;return!0};switch(typeof c){case "function":break;case "boolean":if(!0==
c){c=function(a,b){return Ha.equals(a,b)};break}default:c=function(a,b){b=(""+b).toLowerCase();return-1<(""+a).toLowerCase().indexOf(b)}}var e=function(a,b){if("string"==typeof b&&"!"===b.charAt(0))return!e(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if("$"!==d.charAt(0)&&e(a[d],b))return!0}return!1;case "array":for(d=0;d<a.length;d++)if(e(a[d],b))return!0;return!1;default:return!1}};
switch(typeof b){case "boolean":case "number":case "string":b={$:b};case "object":for(var g in b)"$"==g?function(){if(b[g]){var a=g;d.push(function(c){return e(c,b[a])})}}():function(){if("undefined"!=typeof b[g]){var a=g;d.push(function(c){return e(rb(c,a),b[a])})}}();break;case "function":d.push(b);break;default:return a}for(var h=[],f=0;f<a.length;f++){var k=a[f];d.check(k)&&h.push(k)}return h}}function oc(a){var b=a.NUMBER_FORMATS;return function(a,d){M(d)&&(d=b.CURRENCY_SYM);return sc(a,b.PATTERNS[1],
b.GROUP_SEP,b.DECIMAL_SEP,2).replace(/\u00A4/g,d)}}function qc(a){var b=a.NUMBER_FORMATS;return function(a,d){return sc(a,b.PATTERNS[0],b.GROUP_SEP,b.DECIMAL_SEP,d)}}function sc(a,b,c,d,e){if(isNaN(a)||!isFinite(a))return"";var g=0>a;a=Math.abs(a);var h=a+"",f="",k=[],l=!1;if(-1!==h.indexOf("e")){var m=h.match(/([\d\.]+)e(-?)(\d+)/);m&&"-"==m[2]&&m[3]>e+1?h="0":(f=h,l=!0)}if(l)0<e&&(-1<a&&1>a)&&(f=a.toFixed(e));else{h=(h.split(tc)[1]||"").length;M(e)&&(e=Math.min(Math.max(b.minFrac,h),b.maxFrac));
h=Math.pow(10,e);a=Math.round(a*h)/h;a=(""+a).split(tc);h=a[0];a=a[1]||"";var l=0,m=b.lgSize,p=b.gSize;if(h.length>=m+p)for(var l=h.length-m,n=0;n<l;n++)0===(l-n)%p&&0!==n&&(f+=c),f+=h.charAt(n);for(n=l;n<h.length;n++)0===(h.length-n)%m&&0!==n&&(f+=c),f+=h.charAt(n);for(;a.length<e;)a+="0";e&&"0"!==e&&(f+=d+a.substr(0,e))}k.push(g?b.negPre:b.posPre);k.push(f);k.push(g?b.negSuf:b.posSuf);return k.join("")}function Cb(a,b,c){var d="";0>a&&(d="-",a=-a);for(a=""+a;a.length<b;)a="0"+a;c&&(a=a.substr(a.length-
b));return d+a}function X(a,b,c,d){c=c||0;return function(e){e=e["get"+a]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Cb(e,b,d)}}function eb(a,b){return function(c,d){var e=c["get"+a](),g=Ba(b?"SHORT"+a:a);return d[g][e]}}function pc(a){function b(a){var b;if(b=a.match(c)){a=new Date(0);var g=0,h=0,f=b[8]?a.setUTCFullYear:a.setFullYear,k=b[8]?a.setUTCHours:a.setHours;b[9]&&(g=V(b[9]+b[10]),h=V(b[9]+b[11]));f.call(a,V(b[1]),V(b[2])-1,V(b[3]));g=V(b[4]||0)-g;h=V(b[5]||0)-h;f=V(b[6]||0);b=Math.round(1E3*
parseFloat("0."+(b[7]||0)));k.call(a,g,h,f,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e){var g="",h=[],f,k;e=e||"mediumDate";e=a.DATETIME_FORMATS[e]||e;H(c)&&(c=Cd.test(c)?V(c):b(c));lb(c)&&(c=new Date(c));if(!Ea(c))return c;for(;e;)(k=Dd.exec(e))?(h=h.concat(ta.call(k,1)),e=h.pop()):(h.push(e),e=null);q(h,function(b){f=Ed[b];g+=f?f(c,a.DATETIME_FORMATS):b.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}
function yd(){return function(a){return oa(a,!0)}}function zd(){return function(a,b){if(!D(a)&&!H(a))return a;b=V(b);if(H(a))return b?0<=b?a.slice(0,b):a.slice(b,a.length):"";var c=[],d,e;b>a.length?b=a.length:b<-a.length&&(b=-a.length);0<b?(d=0,e=b):(d=a.length+b,e=a.length);for(;d<e;d++)c.push(a[d]);return c}}function rc(a){return function(b,c,d){function e(a,b){return Ga(b)?function(b,c){return a(c,b)}:a}if(!D(b)||!c)return b;c=D(c)?c:[c];c=Ec(c,function(b){var c=!1,d=b||wa;if(H(b)){if("+"==b.charAt(0)||
"-"==b.charAt(0))c="-"==b.charAt(0),b=b.substring(1);d=a(b)}return e(function(a,b){var c;c=d(a);var e=d(b),f=typeof c,g=typeof e;f==g?("string"==f&&(c=c.toLowerCase(),e=e.toLowerCase()),c=c===e?0:c<e?-1:1):c=f<g?-1:1;return c},c)});for(var g=[],h=0;h<b.length;h++)g.push(b[h]);return g.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(0!==e)return e}return 0},d))}}function sa(a){B(a)&&(a={link:a});a.restrict=a.restrict||"AC";return $(a)}function uc(a,b){function c(b,c){c=c?"-"+pb(c,
"-"):"";a.removeClass((b?fb:gb)+c).addClass((b?gb:fb)+c)}var d=this,e=a.parent().controller("form")||hb,g=0,h=d.$error={},f=[];d.$name=b.name||b.ngForm;d.$dirty=!1;d.$pristine=!0;d.$valid=!0;d.$invalid=!1;e.$addControl(d);a.addClass(Da);c(!0);d.$addControl=function(a){f.push(a);a.$name&&!d.hasOwnProperty(a.$name)&&(d[a.$name]=a)};d.$removeControl=function(a){a.$name&&d[a.$name]===a&&delete d[a.$name];q(h,function(b,c){d.$setValidity(c,!0,a)});Fa(f,a)};d.$setValidity=function(a,b,f){var p=h[a];if(b)p&&
(Fa(p,f),p.length||(g--,g||(c(b),d.$valid=!0,d.$invalid=!1),h[a]=!1,c(!0,a),e.$setValidity(a,!0,d)));else{g||c(b);if(p){if(-1!=Va(p,f))return}else h[a]=p=[],g++,c(!1,a),e.$setValidity(a,!1,d);p.push(f);d.$valid=!1;d.$invalid=!0}};d.$setDirty=function(){a.removeClass(Da).addClass(ib);d.$dirty=!0;d.$pristine=!1;e.$setDirty()};d.$setPristine=function(){a.removeClass(ib).addClass(Da);d.$dirty=!1;d.$pristine=!0;q(f,function(a){a.$setPristine()})}}function ca(a){return M(a)||""===a||null===a||a!==a}function jb(a,
b,c,d,e,g){var h=function(){var e=b.val();Ga(c.ngTrim||"T")&&(e=aa(e));d.$viewValue!==e&&a.$apply(function(){d.$setViewValue(e)})};if(e.hasEvent("input"))b.on("input",h);else{var f,k=function(){f||(f=g.defer(function(){h();f=null}))};b.on("keydown",function(a){a=a.keyCode;91===a||(15<a&&19>a||37<=a&&40>=a)||k()});b.on("change",h);if(e.hasEvent("paste"))b.on("paste cut",k)}d.$render=function(){b.val(ca(d.$viewValue)?"":d.$viewValue)};var l=c.ngPattern,m=function(a,b){if(ca(b)||a.test(b))return d.$setValidity("pattern",
!0),b;d.$setValidity("pattern",!1);return s};l&&((e=l.match(/^\/(.*)\/([gim]*)$/))?(l=RegExp(e[1],e[2]),e=function(a){return m(l,a)}):e=function(c){var d=a.$eval(l);if(!d||!d.test)throw P("ngPattern")("noregexp",l,d,ia(b));return m(d,c)},d.$formatters.push(e),d.$parsers.push(e));if(c.ngMinlength){var p=V(c.ngMinlength);e=function(a){if(!ca(a)&&a.length<p)return d.$setValidity("minlength",!1),s;d.$setValidity("minlength",!0);return a};d.$parsers.push(e);d.$formatters.push(e)}if(c.ngMaxlength){var n=
V(c.ngMaxlength);e=function(a){if(!ca(a)&&a.length>n)return d.$setValidity("maxlength",!1),s;d.$setValidity("maxlength",!0);return a};d.$parsers.push(e);d.$formatters.push(e)}}function Db(a,b){a="ngClass"+a;return function(){return{restrict:"AC",link:function(c,d,e){function g(a){if(!0===b||c.$index%2===b)f&&!xa(a,f)&&e.$removeClass(h(f)),e.$addClass(h(a));f=da(a)}function h(a){if(D(a))return a.join(" ");if(U(a)){var b=[];q(a,function(a,c){a&&b.push(c)});return b.join(" ")}return a}var f=s;c.$watch(e[a],
g,!0);e.$observe("class",function(b){g(c.$eval(e[a]))});"ngClass"!==a&&c.$watch("$index",function(d,f){var g=d&1;g!==f&1&&(g===b?(g=c.$eval(e[a]),e.$addClass(h(g))):(g=c.$eval(e[a]),e.$removeClass(h(g))))})}}}}var J=function(a){return H(a)?a.toLowerCase():a},Ba=function(a){return H(a)?a.toUpperCase():a},Q,w,ya,ta=[].slice,Fd=[].push,Ua=Object.prototype.toString,Wa=P("ng"),Ha=Y.angular||(Y.angular={}),Oa,Aa,ha=["0","0","0"];Q=V((/msie (\d+)/.exec(J(navigator.userAgent))||[])[1]);isNaN(Q)&&(Q=V((/trident\/.*; rv:(\d+)/.exec(J(navigator.userAgent))||
[])[1]));A.$inject=[];wa.$inject=[];var aa=function(){return String.prototype.trim?function(a){return H(a)?a.trim():a}:function(a){return H(a)?a.replace(/^\s*/,"").replace(/\s*$/,""):a}}();Aa=9>Q?function(a){a=a.nodeName?a:a[0];return a.scopeName&&"HTML"!=a.scopeName?Ba(a.scopeName+":"+a.nodeName):a.nodeName}:function(a){return a.nodeName?a.nodeName:a[0].nodeName};var Ic=/[A-Z]/g,Gd={full:"1.2.0-rc.2",major:1,minor:2,dot:0,codeName:"barehand-atomsplitting"},La=S.cache={},Xa=S.expando="ng-"+(new Date).getTime(),
Mc=1,vc=Y.document.addEventListener?function(a,b,c){a.addEventListener(b,c,!1)}:function(a,b,c){a.attachEvent("on"+b,c)},wb=Y.document.removeEventListener?function(a,b,c){a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent("on"+b,c)},Kc=/([\:\-\_]+(.))/g,Lc=/^moz([A-Z])/,tb=P("jqLite"),Pa=S.prototype={ready:function(a){function b(){c||(c=!0,a())}var c=!1;"complete"===T.readyState?setTimeout(b):(this.on("DOMContentLoaded",b),S(Y).on("load",b))},toString:function(){var a=[];q(this,function(b){a.push(""+
b)});return"["+a.join(", ")+"]"},eq:function(a){return 0<=a?w(this[a]):w(this[this.length+a])},length:0,push:Fd,sort:[].sort,splice:[].splice},$a={};q("multiple selected checked disabled readOnly required open".split(" "),function(a){$a[J(a)]=a});var Vb={};q("input select option textarea button form details".split(" "),function(a){Vb[Ba(a)]=!0});q({data:Qb,inheritedData:Za,scope:function(a){return Za(a,"$scope")},controller:Tb,injector:function(a){return Za(a,"$injector")},removeAttr:function(a,b){a.removeAttribute(b)},
hasClass:Ya,css:function(a,b,c){b=Ja(b);if(z(c))a.style[b]=c;else{var d;8>=Q&&(d=a.currentStyle&&a.currentStyle[b],""===d&&(d="auto"));d=d||a.style[b];8>=Q&&(d=""===d?s:d);return d}},attr:function(a,b,c){var d=J(b);if($a[d])if(z(c))c?(a[b]=!0,a.setAttribute(b,d)):(a[b]=!1,a.removeAttribute(d));else return a[b]||(a.attributes.getNamedItem(b)||A).specified?d:s;else if(z(c))a.setAttribute(b,c);else if(a.getAttribute)return a=a.getAttribute(b,2),null===a?s:a},prop:function(a,b,c){if(z(c))a[b]=c;else return a[b]},
text:function(){function a(a,d){var e=b[a.nodeType];if(M(d))return e?a[e]:"";a[e]=d}var b=[];9>Q?(b[1]="innerText",b[3]="nodeValue"):b[1]=b[3]="textContent";a.$dv="";return a}(),val:function(a,b){if(M(b)){if("SELECT"===Aa(a)&&a.multiple){var c=[];q(a.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return a.value}a.value=b},html:function(a,b){if(M(b))return a.innerHTML;for(var c=0,d=a.childNodes;c<d.length;c++)Ka(d[c]);a.innerHTML=b}},function(a,b){S.prototype[b]=
function(b,d){var e,g;if((2==a.length&&a!==Ya&&a!==Tb?b:d)===s){if(U(b)){for(e=0;e<this.length;e++)if(a===Qb)a(this[e],b);else for(g in b)a(this[e],g,b[g]);return this}e=a.$dv;g=e==s?Math.min(this.length,1):this.length;for(var h=0;h<g;h++){var f=a(this[h],b,d);e=e?e+f:f}return e}for(e=0;e<this.length;e++)a(this[e],b,d);return this}});q({removeData:Ob,dealoc:Ka,on:function b(c,d,e,g){if(z(g))throw tb("onargs");var h=ja(c,"events"),f=ja(c,"handle");h||ja(c,"events",h={});f||ja(c,"handle",f=Nc(c,h));
q(d.split(" "),function(d){var g=h[d];if(!g){if("mouseenter"==d||"mouseleave"==d){var m=T.body.contains||T.body.compareDocumentPosition?function(b,c){var d=9===b.nodeType?b.documentElement:b,e=c&&c.parentNode;return b===e||!!(e&&1===e.nodeType&&(d.contains?d.contains(e):b.compareDocumentPosition&&b.compareDocumentPosition(e)&16))}:function(b,c){if(c)for(;c=c.parentNode;)if(c===b)return!0;return!1};h[d]=[];b(c,{mouseleave:"mouseout",mouseenter:"mouseover"}[d],function(b){var c=b.relatedTarget;c&&(c===
this||m(this,c))||f(b,d)})}else vc(c,d,f),h[d]=[];g=h[d]}g.push(e)})},off:Pb,replaceWith:function(b,c){var d,e=b.parentNode;Ka(b);q(new S(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,b);d=c})},children:function(b){var c=[];q(b.childNodes,function(b){1===b.nodeType&&c.push(b)});return c},contents:function(b){return b.childNodes||[]},append:function(b,c){q(new S(c),function(c){1!==b.nodeType&&11!==b.nodeType||b.appendChild(c)})},prepend:function(b,c){if(1===b.nodeType){var d=b.firstChild;
q(new S(c),function(c){b.insertBefore(c,d)})}},wrap:function(b,c){c=w(c)[0];var d=b.parentNode;d&&d.replaceChild(c,b);c.appendChild(b)},remove:function(b){Ka(b);var c=b.parentNode;c&&c.removeChild(b)},after:function(b,c){var d=b,e=b.parentNode;q(new S(c),function(b){e.insertBefore(b,d.nextSibling);d=b})},addClass:Sb,removeClass:Rb,toggleClass:function(b,c,d){M(d)&&(d=!Ya(b,c));(d?Sb:Rb)(b,c)},parent:function(b){return(b=b.parentNode)&&11!==b.nodeType?b:null},next:function(b){if(b.nextElementSibling)return b.nextElementSibling;
for(b=b.nextSibling;null!=b&&1!==b.nodeType;)b=b.nextSibling;return b},find:function(b,c){return b.getElementsByTagName(c)},clone:vb,triggerHandler:function(b,c,d){c=(ja(b,"events")||{})[c];d=d||{preventDefault:A,stopPropagation:A};q(c,function(c){c.call(b,d)})}},function(b,c){S.prototype[c]=function(c,e,g){for(var h,f=0;f<this.length;f++)h==s?(h=b(this[f],c,e,g),h!==s&&(h=w(h))):ub(h,b(this[f],c,e,g));return h==s?this:h};S.prototype.bind=S.prototype.on;S.prototype.unbind=S.prototype.off});Ma.prototype=
{put:function(b,c){this[za(b)]=c},get:function(b){return this[za(b)]},remove:function(b){var c=this[b=za(b)];delete this[b];return c}};var Pc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,Qc=/,/,Rc=/^\s*(_?)(\S+?)\1\s*$/,Oc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Na=P("$injector"),Hd=P("$animate"),Id=["$provide",function(b){this.$$selectors={};this.register=function(c,d){var e=c+"-animation";if(c&&"."!=c.charAt(0))throw Hd("notcsel",c);this.$$selectors[c.substr(1)]=e;b.factory(e,d)};this.$get=["$timeout",function(b){return{enter:function(d,
e,g,h){g=g&&g[g.length-1];var f=e&&e[0]||g&&g.parentNode,k=g&&g.nextSibling||null;q(d,function(b){f.insertBefore(b,k)});h&&b(h,0,!1)},leave:function(d,e){d.remove();e&&b(e,0,!1)},move:function(b,c,g,h){this.enter(b,c,g,h)},addClass:function(d,e,g){e=H(e)?e:D(e)?e.join(" "):"";d.addClass(e);g&&b(g,0,!1)},removeClass:function(d,e,g){e=H(e)?e:D(e)?e.join(" "):"";d.removeClass(e);g&&b(g,0,!1)},enabled:A}}]}],ga=P("$compile");Xb.$inject=["$provide"];var Yc=/^(x[\:\-_]|data[\:\-_])/i,ed=Y.XMLHttpRequest||
function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(b){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(c){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(d){}throw P("$httpBackend")("noxhr");},cc=P("$interpolate"),bc=/^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,gc=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,hd={http:80,https:443,ftp:21},zb=P("$location");ic.prototype=Ab.prototype=hc.prototype={$$html5:!1,$$replace:!1,absUrl:cb("$$absUrl"),
url:function(b,c){if(M(b))return this.$$url;var d=gc.exec(b);d[1]&&this.path(decodeURIComponent(d[1]));(d[2]||d[1])&&this.search(d[3]||"");this.hash(d[5]||"",c);return this},protocol:cb("$$protocol"),host:cb("$$host"),port:cb("$$port"),path:jc("$$path",function(b){return"/"==b.charAt(0)?b:"/"+b}),search:function(b,c){switch(arguments.length){case 0:return this.$$search;case 1:if(H(b))this.$$search=Kb(b);else if(U(b))this.$$search=b;else throw zb("isrcharg");break;default:c==s||null==c?delete this.$$search[b]:
this.$$search[b]=c}this.$$compose();return this},hash:jc("$$hash",wa),replace:function(){this.$$replace=!0;return this}};var Ra=P("$parse"),Sa={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:A,"+":function(b,c,d,e){d=d(b,c);e=e(b,c);return z(d)?z(e)?d+e:d:z(e)?e:s},"-":function(b,c,d,e){d=d(b,c);e=e(b,c);return(z(d)?d:0)-(z(e)?e:0)},"*":function(b,c,d,e){return d(b,c)*e(b,c)},"/":function(b,c,d,e){return d(b,c)/e(b,c)},"%":function(b,c,d,e){return d(b,
c)%e(b,c)},"^":function(b,c,d,e){return d(b,c)^e(b,c)},"=":A,"===":function(b,c,d,e){return d(b,c)===e(b,c)},"!==":function(b,c,d,e){return d(b,c)!==e(b,c)},"==":function(b,c,d,e){return d(b,c)==e(b,c)},"!=":function(b,c,d,e){return d(b,c)!=e(b,c)},"<":function(b,c,d,e){return d(b,c)<e(b,c)},">":function(b,c,d,e){return d(b,c)>e(b,c)},"<=":function(b,c,d,e){return d(b,c)<=e(b,c)},">=":function(b,c,d,e){return d(b,c)>=e(b,c)},"&&":function(b,c,d,e){return d(b,c)&&e(b,c)},"||":function(b,c,d,e){return d(b,
c)||e(b,c)},"&":function(b,c,d,e){return d(b,c)&e(b,c)},"|":function(b,c,d,e){return e(b,c)(b,c,d(b,c))},"!":function(b,c,d){return!d(b,c)}},ld={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},Bb={},Ca=P("$sce"),fa={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"};nc.$inject=["$provide"];oc.$inject=["$locale"];qc.$inject=["$locale"];var tc=".",Ed={yyyy:X("FullYear",4),yy:X("FullYear",2,0,!0),y:X("FullYear",1),MMMM:eb("Month"),MMM:eb("Month",!0),MM:X("Month",2,1),M:X("Month",
1,1),dd:X("Date",2),d:X("Date",1),HH:X("Hours",2),H:X("Hours",1),hh:X("Hours",2,-12),h:X("Hours",1,-12),mm:X("Minutes",2),m:X("Minutes",1),ss:X("Seconds",2),s:X("Seconds",1),sss:X("Milliseconds",3),EEEE:eb("Day"),EEE:eb("Day",!0),a:function(b,c){return 12>b.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(b){b=-1*b.getTimezoneOffset();return b=(0<=b?"+":"")+(Cb(Math[0<b?"floor":"ceil"](b/60),2)+Cb(Math.abs(b%60),2))}},Dd=/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,Cd=
/^\d+$/;pc.$inject=["$locale"];var Ad=$(J),Bd=$(Ba);rc.$inject=["$parse"];var Jd=$({restrict:"E",compile:function(b,c){8>=Q&&(c.href||c.name||c.$set("href",""),b.append(T.createComment("IE fix")));return function(b,c){c.on("click",function(b){c.attr("href")||b.preventDefault()})}}}),Eb={};q($a,function(b,c){if("multiple"!=b){var d=la("ng-"+c);Eb[d]=function(){return{priority:100,compile:function(){return function(b,g,h){b.$watch(h[d],function(b){h.$set(c,!!b)})}}}}}});q(["src","srcset","href"],function(b){var c=
la("ng-"+b);Eb[c]=function(){return{priority:99,link:function(d,e,g){g.$observe(c,function(c){c&&(g.$set(b,c),Q&&e.prop(b,g[b]))})}}}});var hb={$addControl:A,$removeControl:A,$setValidity:A,$setDirty:A,$setPristine:A};uc.$inject=["$element","$attrs","$scope"];var wc=function(b){return["$timeout",function(c){var d={name:"form",restrict:"E",controller:uc,compile:function(){return{pre:function(b,d,h,f){if(!h.action){var k=function(b){b.preventDefault?b.preventDefault():b.returnValue=!1};vc(d[0],"submit",
k);d.on("$destroy",function(){c(function(){wb(d[0],"submit",k)},0,!1)})}var l=d.parent().controller("form"),m=h.name||h.ngForm;m&&db(b,m,f,m);if(l)d.on("$destroy",function(){l.$removeControl(f);m&&db(b,m,s,m);E(f,hb)})}}}};return b?E(da(d),{restrict:"EAC"}):d}]},Kd=wc(),Ld=wc(!0),Md=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,Nd=/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/,Od=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,xc={text:jb,number:function(b,c,d,e,
g,h){jb(b,c,d,e,g,h);e.$parsers.push(function(b){var c=ca(b);if(c||Od.test(b))return e.$setValidity("number",!0),""===b?null:c?b:parseFloat(b);e.$setValidity("number",!1);return s});e.$formatters.push(function(b){return ca(b)?"":""+b});if(d.min){var f=parseFloat(d.min);b=function(b){if(!ca(b)&&b<f)return e.$setValidity("min",!1),s;e.$setValidity("min",!0);return b};e.$parsers.push(b);e.$formatters.push(b)}if(d.max){var k=parseFloat(d.max);d=function(b){if(!ca(b)&&b>k)return e.$setValidity("max",!1),
s;e.$setValidity("max",!0);return b};e.$parsers.push(d);e.$formatters.push(d)}e.$formatters.push(function(b){if(ca(b)||lb(b))return e.$setValidity("number",!0),b;e.$setValidity("number",!1);return s})},url:function(b,c,d,e,g,h){jb(b,c,d,e,g,h);b=function(b){if(ca(b)||Md.test(b))return e.$setValidity("url",!0),b;e.$setValidity("url",!1);return s};e.$formatters.push(b);e.$parsers.push(b)},email:function(b,c,d,e,g,h){jb(b,c,d,e,g,h);b=function(b){if(ca(b)||Nd.test(b))return e.$setValidity("email",!0),
b;e.$setValidity("email",!1);return s};e.$formatters.push(b);e.$parsers.push(b)},radio:function(b,c,d,e){M(d.name)&&c.attr("name",Ta());c.on("click",function(){c[0].checked&&b.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(b,c,d,e){var g=d.ngTrueValue,h=d.ngFalseValue;H(g)||(g=!0);H(h)||(h=!1);c.on("click",function(){b.$apply(function(){e.$setViewValue(c[0].checked)})});e.$render=function(){c[0].checked=
e.$viewValue};e.$formatters.push(function(b){return b===g});e.$parsers.push(function(b){return b?g:h})},hidden:A,button:A,submit:A,reset:A},yc=["$browser","$sniffer",function(b,c){return{restrict:"E",require:"?ngModel",link:function(d,e,g,h){h&&(xc[J(g.type)]||xc.text)(d,e,g,h,c,b)}}}],gb="ng-valid",fb="ng-invalid",Da="ng-pristine",ib="ng-dirty",Pd=["$scope","$exceptionHandler","$attrs","$element","$parse",function(b,c,d,e,g){function h(b,c){c=c?"-"+pb(c,"-"):"";e.removeClass((b?fb:gb)+c).addClass((b?
gb:fb)+c)}this.$modelValue=this.$viewValue=Number.NaN;this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$name=d.name;var f=g(d.ngModel),k=f.assign;if(!k)throw P("ngModel")("nonassign",d.ngModel,ia(e));this.$render=A;var l=e.inheritedData("$formController")||hb,m=0,p=this.$error={};e.addClass(Da);h(!0);this.$setValidity=function(b,c){p[b]!==!c&&(c?(p[b]&&m--,m||(h(!0),this.$valid=!0,this.$invalid=!1)):(h(!1),this.$invalid=
!0,this.$valid=!1,m++),p[b]=!c,h(c,b),l.$setValidity(b,c,this))};this.$setPristine=function(){this.$dirty=!1;this.$pristine=!0;e.removeClass(ib).addClass(Da)};this.$setViewValue=function(d){this.$viewValue=d;this.$pristine&&(this.$dirty=!0,this.$pristine=!1,e.removeClass(Da).addClass(ib),l.$setDirty());q(this.$parsers,function(b){d=b(d)});this.$modelValue!==d&&(this.$modelValue=d,k(b,d),q(this.$viewChangeListeners,function(b){try{b()}catch(d){c(d)}}))};var n=this;b.$watch(function(){var c=f(b);if(n.$modelValue!==
c){var d=n.$formatters,e=d.length;for(n.$modelValue=c;e--;)c=d[e](c);n.$viewValue!==c&&(n.$viewValue=c,n.$render())}})}],Qd=function(){return{require:["ngModel","^?form"],controller:Pd,link:function(b,c,d,e){var g=e[0],h=e[1]||hb;h.$addControl(g);c.on("$destroy",function(){h.$removeControl(g)})}}},Rd=$({require:"ngModel",link:function(b,c,d,e){e.$viewChangeListeners.push(function(){b.$eval(d.ngChange)})}}),zc=function(){return{require:"?ngModel",link:function(b,c,d,e){if(e){d.required=!0;var g=function(b){if(d.required&&
(ca(b)||!1===b))e.$setValidity("required",!1);else return e.$setValidity("required",!0),b};e.$formatters.push(g);e.$parsers.unshift(g);d.$observe("required",function(){g(e.$viewValue)})}}}},Sd=function(){return{require:"ngModel",link:function(b,c,d,e){var g=(b=/\/(.*)\//.exec(d.ngList))&&RegExp(b[1])||d.ngList||",";e.$parsers.push(function(b){var c=[];b&&q(b.split(g),function(b){b&&c.push(aa(b))});return c});e.$formatters.push(function(b){return D(b)?b.join(", "):s})}}},Td=/^(true|false|\d+)$/,Ud=
function(){return{priority:100,compile:function(b,c){return Td.test(c.ngValue)?function(b,c,g){g.$set("value",b.$eval(g.ngValue))}:function(b,c,g){b.$watch(g.ngValue,function(b){g.$set("value",b)})}}}},Vd=sa(function(b,c,d){c.addClass("ng-binding").data("$binding",d.ngBind);b.$watch(d.ngBind,function(b){c.text(b==s?"":b)})}),Wd=["$interpolate",function(b){return function(c,d,e){c=b(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",c);e.$observe("ngBindTemplate",function(b){d.text(b)})}}],
Xd=["$sce",function(b){return function(c,d,e){d.addClass("ng-binding").data("$binding",e.ngBindHtml);c.$watch(e.ngBindHtml,function(c){d.html(b.getTrustedHtml(c)||"")})}}],Yd=Db("",!0),Zd=Db("Odd",0),$d=Db("Even",1),ae=sa({compile:function(b,c){c.$set("ngCloak",s);b.removeClass("ng-cloak")}}),be=[function(){return{scope:!0,controller:"@"}}],ce=["$sniffer",function(b){return{priority:1E3,compile:function(){b.csp=!0}}}],Ac={};q("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur".split(" "),
function(b){var c=la("ng-"+b);Ac[c]=["$parse",function(d){return function(e,g,h){var f=d(h[c]);g.on(J(b),function(b){e.$apply(function(){f(e,{$event:b})})})}}]});var de=["$animate",function(b){return{transclude:"element",priority:1E3,terminal:!0,restrict:"A",compile:function(c,d,e){return function(c,d,f){var k,l;c.$watch(f.ngIf,function(f){k&&(b.leave(k),k=s);l&&(l.$destroy(),l=s);Ga(f)&&(l=c.$new(),e(l,function(c){k=c;b.enter(c,d.parent(),d)}))})}}}}],ee=["$http","$templateCache","$anchorScroll",
"$compile","$animate","$sce",function(b,c,d,e,g,h){return{restrict:"ECA",terminal:!0,transclude:"element",compile:function(f,k,l){var m=k.ngInclude||k.src,p=k.onload||"",n=k.autoscroll;return function(f,k){var q=0,s,w,A=function(){s&&(s.$destroy(),s=null);w&&(g.leave(w),w=null)};f.$watch(h.parseAsResourceUrl(m),function(h){var m=++q;h?(b.get(h,{cache:c}).success(function(b){if(m===q){var c=f.$new();l(c,function(h){A();s=c;w=h;w.html(b);g.enter(w,null,k);e(w.contents())(s);!z(n)||n&&!f.$eval(n)||d();
s.$emit("$includeContentLoaded");f.$eval(p)})}}).error(function(){m===q&&A()}),f.$emit("$includeContentRequested")):A()})}}}}],fe=sa({compile:function(){return{pre:function(b,c,d){b.$eval(d.ngInit)}}}}),ge=sa({terminal:!0,priority:1E3}),he=["$locale","$interpolate",function(b,c){var d=/{}/g;return{restrict:"EA",link:function(e,g,h){var f=h.count,k=h.$attr.when&&g.attr(h.$attr.when),l=h.offset||0,m=e.$eval(k)||{},p={},n=c.startSymbol(),t=c.endSymbol(),r=/^when(Minus)?(.+)$/;q(h,function(b,c){r.test(c)&&
(m[J(c.replace("when","").replace("Minus","-"))]=g.attr(h.$attr[c]))});q(m,function(b,e){p[e]=c(b.replace(d,n+f+"-"+l+t))});e.$watch(function(){var c=parseFloat(e.$eval(f));if(isNaN(c))return"";c in m||(c=b.pluralCat(c-l));return p[c](e,g,!0)},function(b){g.text(b)})}}}],ie=["$parse","$animate",function(b,c){var d=P("ngRepeat");return{transclude:"element",priority:1E3,terminal:!0,compile:function(e,g,h){return function(e,g,l){var m=l.ngRepeat,p=m.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
n,t,r,s,x,z,A,u={$id:za};if(!p)throw d("iexp",m);l=p[1];x=p[2];(p=p[4])?(n=b(p),t=function(b,c,d){A&&(u[A]=b);u[z]=c;u.$index=d;return n(e,u)}):(r=function(b,c){return za(c)},s=function(b){return b});p=l.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!p)throw d("iidexp",l);z=p[3]||p[1];A=p[2];var v={};e.$watchCollection(x,function(b){var l,n,p=g[0],u,x={},H,G,D,E,L,C,K=[];if(kb(b))L=b,t=t||r;else{t=t||s;L=[];for(D in b)b.hasOwnProperty(D)&&"$"!=D.charAt(0)&&L.push(D);L.sort()}H=L.length;
n=K.length=L.length;for(l=0;l<n;l++)if(D=b===L?l:L[l],E=b[D],u=t(D,E,l),v.hasOwnProperty(u))C=v[u],delete v[u],x[u]=C,K[l]=C;else{if(x.hasOwnProperty(u))throw q(K,function(b){b&&b.startNode&&(v[b.id]=b)}),d("dupes",m,u);K[l]={id:u};x[u]=!1}for(D in v)v.hasOwnProperty(D)&&(C=v[D],c.leave(C.elements),q(C.elements,function(b){b.$$NG_REMOVED=!0}),C.scope.$destroy());l=0;for(n=L.length;l<n;l++){D=b===L?l:L[l];E=b[D];C=K[l];if(C.startNode){G=C.scope;u=p;do u=u.nextSibling;while(u&&u.$$NG_REMOVED);C.startNode!=
u&&c.move(C.elements,null,w(p));p=C.endNode}else G=e.$new();G[z]=E;A&&(G[A]=D);G.$index=l;G.$first=0===l;G.$last=l===H-1;G.$middle=!(G.$first||G.$last);G.$odd=!(G.$even=0==l%2);C.startNode||h(G,function(b){c.enter(b,null,w(p));p=b;C.scope=G;C.startNode=b[0];C.elements=b;C.endNode=b[b.length-1];x[C.id]=C})}v=x})}}}}],je=["$animate",function(b){return function(c,d,e){c.$watch(e.ngShow,function(c){b[Ga(c)?"removeClass":"addClass"](d,"ng-hide")})}}],ke=["$animate",function(b){return function(c,d,e){c.$watch(e.ngHide,
function(c){b[Ga(c)?"addClass":"removeClass"](d,"ng-hide")})}}],le=sa(function(b,c,d){b.$watch(d.ngStyle,function(b,d){d&&b!==d&&q(d,function(b,d){c.css(d,"")});b&&c.css(b)},!0)}),me=["$animate",function(b){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,g){var h,f,k=[];c.$watch(e.ngSwitch||e.on,function(d){for(var m=0,p=k.length;m<p;m++)k[m].$destroy(),b.leave(f[m]);f=[];k=[];if(h=g.cases["!"+d]||g.cases["?"])c.$eval(e.change),q(h,function(d){var e=
c.$new();k.push(e);d.transclude(e,function(c){var e=d.element;f.push(c);b.enter(c,e.parent(),e)})})})}}}],ne=sa({transclude:"element",priority:500,require:"^ngSwitch",compile:function(b,c,d){return function(b,g,h,f){f.cases["!"+c.ngSwitchWhen]=f.cases["!"+c.ngSwitchWhen]||[];f.cases["!"+c.ngSwitchWhen].push({transclude:d,element:g})}}}),oe=sa({transclude:"element",priority:500,require:"^ngSwitch",compile:function(b,c,d){return function(b,c,h,f){f.cases["?"]=f.cases["?"]||[];f.cases["?"].push({transclude:d,
element:c})}}}),pe=sa({controller:["$transclude",function(b){this.$transclude=b}],link:function(b,c,d,e){e.$transclude(function(b){c.html("");c.append(b)})}}),qe=["$templateCache",function(b){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&b.put(d.id,c[0].text)}}}],re=$({terminal:!0}),se=["$compile","$parse",function(b,c){var d=/^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
e={$setViewValue:A};return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope","$attrs",function(b,c,d){var k=this,l={},m=e,p;k.databound=d.ngModel;k.init=function(b,c,d){m=b;p=d};k.addOption=function(c){l[c]=!0;m.$viewValue==c&&(b.val(c),p.parent()&&p.remove())};k.removeOption=function(b){this.hasOption(b)&&(delete l[b],m.$viewValue==b&&this.renderUnknownOption(b))};k.renderUnknownOption=function(c){c="? "+za(c)+" ?";p.val(c);b.prepend(p);b.val(c);p.prop("selected",!0)};k.hasOption=
function(b){return l.hasOwnProperty(b)};c.$on("$destroy",function(){k.renderUnknownOption=A})}],link:function(e,h,f,k){function l(b,c,d,e){d.$render=function(){var b=d.$viewValue;e.hasOption(b)?(v.parent()&&v.remove(),c.val(b),""===b&&A.prop("selected",!0)):M(b)&&A?c.val(""):e.renderUnknownOption(b)};c.on("change",function(){b.$apply(function(){v.parent()&&v.remove();d.$setViewValue(c.val())})})}function m(b,c,d){var e;d.$render=function(){var b=new Ma(d.$viewValue);q(c.find("option"),function(c){c.selected=
z(b.get(c.value))})};b.$watch(function(){xa(e,d.$viewValue)||(e=da(d.$viewValue),d.$render())});c.on("change",function(){b.$apply(function(){var b=[];q(c.find("option"),function(c){c.selected&&b.push(c.value)});d.$setViewValue(b)})})}function p(e,f,g){function h(){var b={"":[]},c=[""],d,k,w,z,y;w=g.$modelValue;z=t(e)||[];var E=n?Fb(z):z,I,B,F;B={};y=!1;var G,J;if(r)if(v&&D(w))for(y=new Ma([]),k=0;k<w.length;k++)B[m]=w[k],y.put(v(e,B),w[k]);else y=new Ma(w);for(F=0;I=E.length,F<I;F++)B[m]=z[n?B[n]=
E[F]:F],d=p(e,B)||"",(k=b[d])||(k=b[d]=[],c.push(d)),r?d=y.remove(v?v(e,B):q(e,B))!=s:(v?(d={},d[m]=w,d=v(e,d)===v(e,B)):d=w===q(e,B),y=y||d),G=l(e,B),G=G===s?"":G,k.push({id:v?v(e,B):n?E[F]:F,label:G,selected:d});r||(x||null===w?b[""].unshift({id:"",label:"",selected:!y}):y||b[""].unshift({id:"?",label:"",selected:!0}));B=0;for(E=c.length;B<E;B++){d=c[B];k=b[d];A.length<=B?(w={element:u.clone().attr("label",d),label:k.label},z=[w],A.push(z),f.append(w.element)):(z=A[B],w=z[0],w.label!=d&&w.element.attr("label",
w.label=d));G=null;F=0;for(I=k.length;F<I;F++)d=k[F],(y=z[F+1])?(G=y.element,y.label!==d.label&&G.text(y.label=d.label),y.id!==d.id&&G.val(y.id=d.id),G[0].selected!==d.selected&&G.prop("selected",y.selected=d.selected)):(""===d.id&&x?J=x:(J=H.clone()).val(d.id).attr("selected",d.selected).text(d.label),z.push({element:J,label:d.label,id:d.id,selected:d.selected}),G?G.after(J):w.element.append(J),G=J);for(F++;z.length>F;)z.pop().element.remove()}for(;A.length>B;)A.pop()[0].element.remove()}var k;if(!(k=
y.match(d)))throw P("ngOptions")("iexp",y,ia(f));var l=c(k[2]||k[1]),m=k[4]||k[6],n=k[5],p=c(k[3]||""),q=c(k[2]?k[1]:m),t=c(k[7]),v=k[8]?c(k[8]):null,A=[[{element:f,label:""}]];x&&(b(x)(e),x.removeClass("ng-scope"),x.remove());f.html("");f.on("change",function(){e.$apply(function(){var b,c=t(e)||[],d={},h,k,l,p,u,x;if(r)for(k=[],p=0,x=A.length;p<x;p++)for(b=A[p],l=1,u=b.length;l<u;l++){if((h=b[l].element)[0].selected){h=h.val();n&&(d[n]=h);if(v)for(var w=0;w<c.length&&(d[m]=c[w],v(e,d)!=h);w++);else d[m]=
c[h];k.push(q(e,d))}}else if(h=f.val(),"?"==h)k=s;else if(""==h)k=null;else if(v)for(w=0;w<c.length;w++){if(d[m]=c[w],v(e,d)==h){k=q(e,d);break}}else d[m]=c[h],n&&(d[n]=h),k=q(e,d);g.$setViewValue(k)})});g.$render=h;e.$watch(h)}if(k[1]){var n=k[0],t=k[1],r=f.multiple,y=f.ngOptions,x=!1,A,H=w(T.createElement("option")),u=w(T.createElement("optgroup")),v=H.clone();k=0;for(var E=h.children(),I=E.length;k<I;k++)if(""==E[k].value){A=x=E.eq(k);break}n.init(t,x,v);if(r&&(f.required||f.ngRequired)){var B=
function(b){t.$setValidity("required",!f.required||b&&b.length);return b};t.$parsers.push(B);t.$formatters.unshift(B);f.$observe("required",function(){B(t.$viewValue)})}y?p(e,h,t):r?m(e,h,t):l(e,h,t,n)}}}}],te=["$interpolate",function(b){var c={addOption:A,removeOption:A};return{restrict:"E",priority:100,compile:function(d,e){if(M(e.value)){var g=b(d.text(),!0);g||e.$set("value",d.text())}return function(b,d,e){var l=d.parent(),m=l.data("$selectController")||l.parent().data("$selectController");m&&
m.databound?d.prop("selected",!1):m=c;g?b.$watch(g,function(b,c){e.$set("value",b);b!==c&&m.removeOption(c);m.addOption(b)}):m.addOption(e.value);d.on("$destroy",function(){m.removeOption(e.value)})}}}}],ue=$({restrict:"E",terminal:!0});(ya=Y.jQuery)?(w=ya,E(ya.fn,{scope:Pa.scope,controller:Pa.controller,injector:Pa.injector,inheritedData:Pa.inheritedData}),sb("remove",!0,!0,!1),sb("empty",!1,!1,!1),sb("html",!1,!1,!0)):w=S;Ha.element=w;(function(b){E(b,{bootstrap:Mb,copy:da,extend:E,equals:xa,element:w,
forEach:q,injector:Nb,noop:A,bind:nb,toJson:oa,fromJson:Ib,identity:wa,isUndefined:M,isDefined:z,isString:H,isFunction:B,isObject:U,isNumber:lb,isElement:Dc,isArray:D,$$minErr:P,version:Gd,isDate:Ea,lowercase:J,uppercase:Ba,callbacks:{counter:0}});Oa=Jc(Y);try{Oa("ngLocale")}catch(c){Oa("ngLocale",[]).provider("$locale",gd)}Oa("ng",["ngLocale"],["$provide",function(b){b.provider("$compile",Xb).directive({a:Jd,input:yc,textarea:yc,form:Kd,script:qe,select:se,style:ue,option:te,ngBind:Vd,ngBindHtml:Xd,
ngBindTemplate:Wd,ngClass:Yd,ngClassEven:$d,ngClassOdd:Zd,ngCsp:ce,ngCloak:ae,ngController:be,ngForm:Ld,ngHide:ke,ngIf:de,ngInclude:ee,ngInit:fe,ngNonBindable:ge,ngPluralize:he,ngRepeat:ie,ngShow:je,ngStyle:le,ngSwitch:me,ngSwitchWhen:ne,ngSwitchDefault:oe,ngOptions:re,ngTransclude:pe,ngModel:Qd,ngList:Sd,ngChange:Rd,required:zc,ngRequired:zc,ngValue:Ud}).directive(Eb).directive(Ac);b.provider({$anchorScroll:Sc,$animate:Id,$browser:Vc,$cacheFactory:Wc,$controller:Zc,$document:$c,$exceptionHandler:ad,
$filter:nc,$interpolate:fd,$http:bd,$httpBackend:cd,$location:id,$log:jd,$parse:nd,$rootScope:qd,$q:od,$sce:sd,$sceDelegate:rd,$sniffer:td,$templateCache:Xc,$timeout:ud,$window:wd,$$urlUtils:vd})}])})(Ha);w(T).ready(function(){Hc(T,Mb)})})(window,document);angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}</style>');
/*
//@ sourceMappingURL=angular.min.js.map
*/
;

/* file-end: js/lib/angular/1.2.0-rc.2/angular.min.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/editor/basicToolbar.js 
*/


/* ---------------------------------------------------------------------------------
   file-start: js/core/angular/api.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/core/angular/messages.js 
*/

Site.page.template['angular/ljMessages.ng.tmpl'] = '<div class=\"b-msgsystem-wrapper b-msgsystem-wrapper-fixed\">\n    <div ng-repeat=\"message in active()\" class=\"b-msgsystem\" ng-class=\"\'b-msgsystem-type-\' + message.type\" ng-animate=\"\'b-msgsystem\'\">\n        <header class=\"b-msgsystem-head\" lj-html=\"message.title\" ng-if=\"message.title\"></header>\n        <div class=\"b-msgsystem-wrap\"><div class=\"b-msgsystem-body\" lj-html=\"message.body\"></div></div>\n        <span class=\"b-msgsystem-close\" ng-click=\"close(message)\">\n            <span class=\"b-msgsystem-close-text\" lj-ml=\"component.messages.close\"></span>\n            <span class=\"b-msgsystem-close-ctrl\" lj-ml=\"component.messages.close\" lj-ml-attr=\"title\">&times;</span>\n        </span>\n    </div>\n</div>\n';
/* ---------------------------------------------------------------------------------
   file-start: js/core/angular/common.js 
*/

/*
 * Include LJ.Templates as module dependency to have access to templates,
 * required using require_template. Don't forget to require this file.
 *
 * @example
 *   js:
 *     //= require_template angular/ljMessages.ng.tmpl
 *     angular.module('MyModule', ['LJ.Templates']);
 *
 *   html:
 *     <div ng-include src="'ljMessages.ng.tmpl'">
 *
 * If you need direct access as a string, use $templateCache.
 */
angular.module('LJ.Templates', []).run(['$templateCache', function($templateCache) {
  var template = LJ.get('template'), key;

  for (key in template) {
    if (template.hasOwnProperty(key)) {
      $templateCache.put(key.split('/').pop(), template[key]);
    }
  }
}]);

/*
 * Common directives
 */

angular.module('LJ.Directives', [])

/**
 * Insert html and do not watch for changes
 */
.directive('ljHtml', function () {
  return function link(scope, element, attrs) {
    element.html( scope.$eval(attrs.ljHtml) || '' );
  };
})

/**
 * Insert html and watch for changes
 */
.directive('ljHtmlLive', function () {
  return function link(scope, element, attrs) {
    scope.$watch(function () {
      return scope.$eval(attrs.ljHtmlLive);
    }, function (value) {
      element.html( value || '' );
    });
  };
})

/**
 * @example
 *     <!-- replace span text with ml variable value -->
 *     <span lj-ml="user.text.save"></span>
 *
 * @example
 *     <!-- replace `placeholder` attr with ml variable value -->
 *     <input type="text"  lj-ml="user.text.save" lj-ml-attr="placeholder" />
 *
 * @example
 *
 *     Html:
 *       <!-- wait for substitutions like [[username]] -->
 *       <span lj-ml="user.text.save" lj-ml-resolve="mlResolve" />
 *
 *     Controller:
 *       var mlDefer = $q.defer();
 *
 *       // Notice:
 *       //   Object with `promise` field is needed!
 *       //   If promise is assigned directly, it will be resolved to `undefined`
 *
 *       $scope.mlResolve = { promise: mlDefer.promise }
 *       mlDefer.resolve({ username: 'good' })
 */
.directive('ljMl', ['$parse', function($parse) {
  return {
    link: function(scope, element, attrs) {
      var mlVar = attrs.ljMl,
          resolve;

      // we don't need substitutions
      if ( !attrs.ljMlResolve ) {
        replaceMl(mlVar);
        return;
      }

      resolve = $parse(attrs.ljMlResolve)(scope);

      if (!resolve || !resolve.promise) {
        throw new TypeError('Object with property `promise` should be provided.');
      }

      resolve.promise.then(function (data) {
        replaceMl(mlVar, data);
      });

      // replace variable with value
      function replaceMl(mlVar, dictionary) {
        var ml = LJ.ml(mlVar, dictionary);

        // attribute
        if (attrs.ljMlAttr) {
          element.attr( attrs.ljMlAttr, ml);
          return;
        }

        // html
        element.html(ml);
      }
    }
  };
}])
.directive('ljSwitchOff', ['$document', '$parse',
             function ( $document ,  $parse ) {
  /*
   * When area outside of element is clicked or ESC is pressed
   * 'showPopup' will be set to false and 'doSomething()' will be evaluated.
   *
   * <div ng-show="showPopup" lj-switch-off="showPopup" lj-switch-off-action="doSomething()"></div>
   *
   * Skip switching:
   * Notice: now skipping of switch is working for all `lj-switch-off` directives (is not grouped)
   * <span lj-switch-off-skip>This element prevents switching via `lj-switch-off` directive</span>
   *
   */

  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var state    = $parse(attrs.ljSwitchOff),
          _clicked = false;

      element.on('click', function () {
        _clicked = true;
      });

      $document
        .on('keydown', keyPressed)
        .on('click', '[lj-switch-off-skip]', preventSwitching)
        .on('click', documentClick);

      // cleanup
      scope.$on('$destroy', function () {
        $document
          .off('keydown', keyPressed)
          .off('click', '[lj-switch-off-skip]', preventSwitching)
          .off('click', documentClick);
      });

      function close() {
        if (attrs.ljSwitchOffAction) {
          scope.$eval(attrs.ljSwitchOffAction);
        }

        state.assign(scope, false);
      }

      function preventSwitching() {
        _clicked = true;
      }

      function documentClick(event) {

        // right click in Firefox is closing the bubble
        if (event.button === 2) {
          return;
        }

        if ( !_clicked && state(scope) ) {
          scope.$apply(close);
        }

        _clicked = false;
      }

      function keyPressed(event) {
        /** ESC */
        if ( event.which === 27 && state(scope) ) {
          scope.$apply(close);
        }
      }
    }
  };
}]).
directive('ljDisabled', [function() {
  /*
   * Toggles disabled state for LiveJournal button
   *
   * <div class="b-ljbutton b-ljbutton-submit">
   *   <button lj-disabled="!comment">Submit comment</button>
   * </div>
   */
  return function (scope, element, attrs) {
    scope.$watch(attrs.ljDisabled, function(value) {
      element.prop('disabled', value);
      element.parent().toggleClass('b-ljbutton-disabled', value);
    });
  };
}])
.directive('focusAndSelect', ['$timeout', function ($timeout) {
  /*
   * Focus and select an input or textarea when expression is true
   *
   * <input focus-and-select="show">
   */
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var attr = attrs.focusAndSelect;

      scope.$watch(attr, function (value, prev) {
        if (value) {
          $timeout(function () {
            element[0].focus();
            element[0].select();
          });
        } else if (prev) {
          // fix: blur for IE
          element[0].blur();
        }
      });
    }
  };
}]);
;

/* file-end: js/core/angular/common.js 
----------------------------------------------------------------------------------*/

// @ml component.messages.close

/*
 * LiveJournal page messages
 * https://conf.sup.com/pages/viewpage.action?pageId=6161047#id-1AddRemoveLinksandButtonsFRSCR-Warnings
 *
 * @requires
 *   stc/msgsystem.css
 *
 * @example
 *   js:
 *     //= require js/core/angular/messages.js
 *
 *     angular.module('MyModule', ['LJ.Messages'])
 *     .controller('MyCtrl', ['$scope', 'Messages', function($scope, Messages) {
 *       Messages.error({ body: 'Call the cops!', title: 'Title is optional' });
 *     }]);
 *
 * .error, .info, .success, .warning methods are available.
 *
 * @example
 *   Alternatively, you can use it from Perl controller:
 *
 *   LJ::need_var(messages => [{
 *     title => 'hello', body => 'world',
 *     type => 'success', active => 1
 *   }]);
 */

(function() {
'use strict';

angular.module('LJ.Messages', ['LJ.Templates'])
  .run(['$compile', '$rootScope', function($compile, $rootScope) {
      $compile(
        '<div lj-messages></div>'
      )($rootScope)
      .appendTo('body');
  }])
  .factory('Messages', [function() {
    var factory = {
          items: LJ.get('messages') || []
        },
        types = ['error', 'info', 'success', 'warning'];


    factory.add = function(data) {
      if ( types.indexOf( data.type ) === -1 ) {
        return;
      }

      data.active = true;
      factory.items.push(data);
    };

    types.forEach(function(method) {
      factory[method] = function(data) {
        data.type = method;
        factory.add(data);
      };
    });

    factory.clear = function() {
      factory.items.forEach(function(item) {
        item.active = false;
      });

      return factory;
    };

    return factory;
  }])
  .directive('ljMessages', ['$timeout', 'Messages',
                   function( $timeout,   Messages ) {
    return {
      templateUrl: 'ljMessages.ng.tmpl',
      link: function(scope) {
        scope.active = function() {
          return Messages.items.filter(function(item) {
            return item.active;
          });
        };

        scope.close = function(data) {
          data.active = false;
        };
      }
    };
  }]);

})();
;

/* file-end: js/core/angular/messages.js 
----------------------------------------------------------------------------------*/

/**
 * @description Angular wrapper of LJ.Api
 * @author Valeriy Vasin (valeriy.vasin@sup.com)
 *
 * @example
 *
 *     angular.module('MyModule', ['LJ.Api'])
 *       .factory('myFactory', ['Api', function (Api) {
 *          return {
 *            fetch: function () {
 *              return Api.call('rpc.method', {param: 'value'});
 *            },
 *
 *            fetchCached: function () {
 *              return Api.call('rpc.method', { param: 'value' }, { cache: true });
 *            },
 *
 *            fetchCallback: function (callback) {
 *              Api.call('rpc.method', { param: 'value' }, callback);
 *            }
 *          };
 *       }]);
 *
 */

angular.module('LJ.Api', ['LJ.Messages'])
  .factory('Api', ['$cacheFactory', '$timeout', '$q', '$window', 'Messages',
         function ( $cacheFactory,   $timeout,   $q,   $window,   Messages ) {

      var factory = {},
          cacheData = $cacheFactory('LJApiData'),
          cachePromises = $cacheFactory('LJApiPromises');

      /**
       * Call JSON Rpc API
       *
       * @param  {String}   method                   JSON Rpc method
       * @param  {Object}   [params]                 JSON Rpc method params
       * @param  {Function} [callback]               Callback to call after data recieved
       * @param  {Object}   [options]                Additional api options
       * @param  {Boolean}  [options.cache=false]    Cache options: turn on/off cache for request
       * @param {Boolean}   [options.silent=false]   Turn on/off messages (error/info etc)
       *
       * @return {Promise}           Promise that will be resolved when data received
       */
      factory.call = function (method, params, callback, options) {
        var defer = $q.defer(),
            promise = defer.promise,
            defaults = { cache: false, silent: false },
            cacheKey,
            previousPromise,
            dataFromCache;

        params = params || {};

        if ( typeof callback === 'object' ) {
          options = callback;
          callback = null;
        }

        options = angular.extend(defaults, options || {});

        cacheKey = method + JSON.stringify(params);

        if (options.cache) {
          previousPromise = cachePromises.get(cacheKey);
          if ( previousPromise ) {

            // Request has been sent before and is still waiting for response.
            if (typeof callback === 'function') {
              previousPromise.then(callback);
            }

            return previousPromise;
          }

          // check if cached data is available for request
          dataFromCache = cacheData.get(cacheKey);
          if (dataFromCache) {

            if (typeof callback === 'function') {
              promise.then(callback);
            }

            $timeout(function () {
              defer.resolve(dataFromCache);
            });

            return promise;
          }
        }

        // retrieve data from server
        if (typeof callback === 'function') {
          promise.then(callback);
        }

        // show errors/messages
        if ( !options.silent ) {
          promise
            .then(function (data) {
              var message = data.message;

              if ( typeof message === 'undefined' ) {
                return;
              }

              message.body = message.content;
              Messages.add(message);
            }, function (message) {
              Messages.error({ body: message });
            });
        }

        $window.LJ.Api.call(method, params, function (data) {
          $timeout(function () {
            if (data.error) {
              defer.reject(data.error.message);
              return;
            }

            if (options.cache) {
              cachePromises.remove(cacheKey);
              cacheData.put(cacheKey, data);
            }

            defer.resolve(data);
          });
        });

        if (options.cache) {
          cachePromises.put(cacheKey, promise);
        }

        return promise;
      };

      return factory;
    }
  ]);
;

/* file-end: js/core/angular/api.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/core/angular/bubble.js 
*/


Site.page.template['Widgets/ljBubble.tmpl'] = '<div\n    class=\"b-popup bubble-node b-updateform-bubble b-popupus b-popupus-blue b-popup-withclosecontrol\"\n    ng-show=\"show\"\n    lj-switch-off=\"show\"\n    lj-switch-off-action=\"bubble.close()\"\n    ng-style=\"{ left: position.x, top: position.y }\"\n    ng-class=\"\'b-updateform-bubble-\' + bubble.name\"\n    >\n    <div class=\"b-popup-outer\">\n        <div class=\"b-popup-inner\">\n            <i class=\"i-popup-arr\" ng-class=\"getPosition()\">\n                <i class=\"i-popup-arr-brdr-outer\">\n                    <i class=\"i-popup-arr-brdr-inner\">\n                        <i class=\"i-popup-arr-bg\"></i>\n                    </i>\n                </i>\n            </i>\n            <div ng-include src=\"template\"></div>\n            <i class=\"i-popup-close\" ng-click=\"bubble.close()\"></i>\n        </div>\n    </div>\n</div>\n';
/*
 * LJ bubble directive
 *
 * @requires
 *   stc/popup/popupus.css,
 *   stc/popup/popupus-blue.css
 *
 * @example
 *   html:
 *     <!--
 *       Following will add click handler to button
 *       and include myBubble.tmpl inside bubble.
 *     -->
 *     <button lj-bubble="{ name: 'myBubble' }">Show bubble!</button>
 *
 *   js:
 *     //= require js/core/angular/bubble.js
 *
 *     angular.module('MyModule', ['LJ.Bubble'])
 *     .controller('MyCtrl', ['$scope', 'Bubble', function($scope, Bubble) {
 *
 *       // Use Bubble.open to control bubble from JS.
 *       // You can pass jQuery node to reposition the bubble from the original placement.
 *       Bubble.open('myBubble', { 'some-stuff': 'optional' }, jQuery('.b-some-other-block'));
 *     }]);
 *
 * @todo
 *   Refactor detection of current bubble open
 *   Refactor disableClick option of directive
 *
 * @authors
 *   Artem Tyurin (artem.tyurin@sup.com)
 *   Valeriy Vasin (valeriy.vasin@sup.com)
 */

(function($) {
  'use strict';

  angular.module('LJ.Bubble', ['LJ.Templates', 'LJ.Directives'])
  .factory('Bubble', function() {
    var factory  = {},

        // bubbles options
        _options = {},

        // targets for bubbles
        _targets = {};

    // currently opened bubble name
    factory.current = null;

    // we can change bubble node while opening bubble
    factory.node = null;

    /**
     * Register bubble
     * @param {String} name Bubble name
     */
    factory._register = function (name) {
      if ( _options.hasOwnProperty(name) ) {
        console.warn('Warning: bubble with name `%s` has been registered before!', name);
      }

      _options[name] = {};
    };

    /**
     * Register target for bubble nodes
     *
     * @param {String} name Target name
     * @param {jQuery} node Target node
     */
    factory._registerTarget = function (name, node) {
      if ( _targets.hasOwnProperty(name) ) {
        throw new Error('Bubble with name `'+ name +'` has been registered before. Check it.');
      }

      _targets[name] = node;
    };

    function getTarget(name) {
      if ( !_targets.hasOwnProperty(name) ) {
        console.warn('Bubble target `'+ name +'` has not been registered yet.');
        return;
      }

      return _targets[name];
    }

    /**
     * Open bubble with provided name
     * @param {String}        name       Bubble name
     * @param {Object}        [options]  Options that will be available for bubble
     * @param {jQuery|String} [node]     jQuery: Node relative to which bubble will be positioned
     *                                   String: Registered bubble target name
     */
    factory.open = function (name, options, node) {
      if ( !_options.hasOwnProperty(name) ) {
        throw new Error('Bubble `'+ name +'` can\'t be opened, it has not been registered yet.');
      }

      if ( options instanceof jQuery ) {
        node = options;
        options = {};
      }

      if ( typeof options === 'string' ) {
        node = getTarget(options);
        options = {};
      }

      if (typeof options === 'object') {
        factory.options(name, options);
      }

      if (node instanceof jQuery) {
        factory.node = node;
      }

      factory.current = name;
    };

    /**
     * Close all opened bubbles
     * @param {String} [name] Close bubble
     */
    factory.close = function () {
      var name = factory.current,
          options = _options[name],
          option;

      // clear current bubble options
      for (option in options) {
        if ( options.hasOwnProperty(option) ) {
          delete options[option];
        }
      }

      factory.current = null;
      factory.node = null;
    };

    /**
     * Set context for opened bubble
     * @param  {String} name    Bubble name
     * @param  {Object} options Opening context (arguments)
     * @return {Object}         Bubble options
     */
    factory.options = function (name, options) {
      if (typeof options === 'undefined') {
        return _options[name];
      }

      angular.copy(options, _options[name]);
    };

    return factory;
  })
  .directive('ljBubble', ['Bubble', '$parse', '$compile', '$timeout', '$templateCache',
                 function( Bubble,   $parse,   $compile,   $timeout,   $templateCache ) {
    return {
      scope: true,
      link: function(scope, element, attrs) {
        var options = $parse(attrs.ljBubble)(scope),
            name = options.name,
            bubble  = $compile($templateCache.get('ljBubble.tmpl'))(scope),
            arrow = bubble.find('.i-popup-arr');

        scope.show = false;

        Bubble._register(name);

        scope.template = options.template || (name + '.html');
        scope.bubble = {
          name: name,
          close: Bubble.close,
          options: Bubble.options(name)
        };

        scope.arrow = {
          vertical:   't', /* top  (t) or bottom (b) */
          horizontal: 'l'  /* left (l) or right  (r) */
        };

        scope.position = {
          x: -9999,
          y: -9999
        };

        scope.getPosition = function() {
          return 'i-popup-arr' + scope.arrow.vertical + scope.arrow.horizontal;
        };

        scope.$watch(function() {
          return Bubble.current;
        }, function(value) {
          scope.hideFromViewport();

          $timeout(function() {
            scope.show = value === name;

            if (value) {
              $timeout(scope.setPosition);
            }
          });
        }, true);

        scope.setPosition = function() {
          var el      = Bubble.node || element,
              centerX = el.offset().left + Math.floor(el.outerWidth() / 2);

          scope.position.x = centerX - arrow.position().left - Math.floor(arrow.outerWidth() / 2) - 2;
          scope.position.y = el.offset().top + el.outerHeight() - arrow.position().top;
        };

        scope.hideFromViewport = function() {
          scope.position.x = -9999;
        };

        scope.rightFromViewport = function() {
          return scope.position.x + bubble.outerWidth() > $(window).width();
        };

        if (!options.disableClick) {
          element.click(function(event) {
            event.preventDefault();

            $timeout(function() {
              Bubble.open(options.name);
            });
          });
        }

        $(window).on('resize', function() {
          if (scope.show) {
            $timeout(scope.setPosition);
          }
        });

        $(document.body).append(bubble);
      }
    };
  }])

  // register a target for the bubble
  // <span lj-bubble-target="mytarget"></span>
  .directive('ljBubbleTarget', ['Bubble', function (Bubble) {
    return function link(scope, element, attrs) {
      var name = attrs.ljBubbleTarget;
      Bubble._registerTarget(name, element);
    };
  }]);
})(jQuery);
;

/* file-end: js/core/angular/bubble.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/editor/editor.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/lib/textinputs_jquery.js 
*/

/**
 * @license Rangy Inputs, a jQuery plug-in for selection and caret manipulation within textareas and text inputs.
 *
 * https://github.com/timdown/rangyinputs
 *
 * For range and selection features for contenteditable, see Rangy.

 * http://code.google.com/p/rangy/
 *
 * Depends on jQuery 1.0 or later.
 *
 * Copyright 2013, Tim Down
 * Licensed under the MIT license.
 * Version: 1.1
 * Build date: 31 March 2013
 */
(function(a){function l(a,b){var c=typeof a[b];return"function"===c||!("object"!=c||!a[b])||"unknown"==c}function m(a,c){return typeof a[c]!=b}function n(a,b){return!("object"!=typeof a[b]||!a[b])}function o(a){window.console&&window.console.log&&window.console.log("RangyInputs not supported in your browser. Reason: "+a)}function p(a,c,d){return 0>c&&(c+=a.value.length),typeof d==b&&(d=c),0>d&&(d+=a.value.length),{start:c,end:d}}function q(a,b,c){return{start:b,end:c,length:c-b,text:a.value.slice(b,c)}}function r(){return n(document,"body")?document.body:document.getElementsByTagName("body")[0]}var c,d,e,f,g,h,i,j,k,b="undefined";a(document).ready(function(){function v(a,b){return function(){var c=this.jquery?this[0]:this,d=c.nodeName.toLowerCase();if(1==c.nodeType&&("textarea"==d||"input"==d&&"text"==c.type)){var e=[c].concat(Array.prototype.slice.call(arguments)),f=a.apply(this,e);if(!b)return f}return b?this:void 0}}var s=document.createElement("textarea");if(r().appendChild(s),m(s,"selectionStart")&&m(s,"selectionEnd"))c=function(a){var b=a.selectionStart,c=a.selectionEnd;return q(a,b,c)},d=function(a,b,c){var d=p(a,b,c);a.selectionStart=d.start,a.selectionEnd=d.end},k=function(a,b){b?a.selectionEnd=a.selectionStart:a.selectionStart=a.selectionEnd};else{if(!(l(s,"createTextRange")&&n(document,"selection")&&l(document.selection,"createRange")))return r().removeChild(s),o("No means of finding text input caret position"),void 0;c=function(a){var d,e,f,g,b=0,c=0,h=document.selection.createRange();return h&&h.parentElement()==a&&(f=a.value.length,d=a.value.replace(/\r\n/g,"\n"),e=a.createTextRange(),e.moveToBookmark(h.getBookmark()),g=a.createTextRange(),g.collapse(!1),e.compareEndPoints("StartToEnd",g)>-1?b=c=f:(b=-e.moveStart("character",-f),b+=d.slice(0,b).split("\n").length-1,e.compareEndPoints("EndToEnd",g)>-1?c=f:(c=-e.moveEnd("character",-f),c+=d.slice(0,c).split("\n").length-1))),q(a,b,c)};var t=function(a,b){return b-(a.value.slice(0,b).split("\r\n").length-1)};d=function(a,b,c){var d=p(a,b,c),e=a.createTextRange(),f=t(a,d.start);e.collapse(!0),d.start==d.end?e.move("character",f):(e.moveEnd("character",t(a,d.end)),e.moveStart("character",f)),e.select()},k=function(a,b){var c=document.selection.createRange();c.collapse(b),c.select()}}r().removeChild(s),f=function(a,b,c,e){var f;b!=c&&(f=a.value,a.value=f.slice(0,b)+f.slice(c)),e&&d(a,b,b)},e=function(a){var b=c(a);f(a,b.start,b.end,!0)},j=function(a){var e,b=c(a);return b.start!=b.end&&(e=a.value,a.value=e.slice(0,b.start)+e.slice(b.end)),d(a,b.start,b.start),b.text};var u=function(a,b,c,e){var f=b+c.length;switch(e="string"==typeof e?e.toLowerCase():""){case"collapsetostart":d(a,b,b);break;case"collapsetoend":d(a,f,f);break;case"select":d(a,b,f)}};g=function(a,b,c,d){var e=a.value;a.value=e.slice(0,c)+b+e.slice(c),"boolean"==typeof d&&(d=d?"collapseToEnd":""),u(a,c,b,d)},h=function(a,b,d){var e=c(a),f=a.value;a.value=f.slice(0,e.start)+b+f.slice(e.end),u(a,e.start,b,d||"collapseToEnd")},i=function(a,d,e,f){typeof e==b&&(e=d);var g=c(a),h=a.value;a.value=h.slice(0,g.start)+d+g.text+e+h.slice(g.end);var i=g.start+d.length;u(a,i,g.text,f||"select")},a.fn.extend({getSelection:v(c,!1),setSelection:v(d,!0),collapseSelection:v(k,!0),deleteSelectedText:v(e,!0),deleteText:v(f,!0),extractSelectedText:v(j,!1),insertText:v(g,!0),replaceSelectedText:v(h,!0),surroundSelectedText:v(i,!0)})})})(jQuery);;

/* file-end: js/lib/textinputs_jquery.js 
----------------------------------------------------------------------------------*/

(function($) {

'use strict';

angular.module('Editor', [])
.factory('Editor', function() {
  var factory = {};

  factory.getSelectedText = function() {
    var textarea = $('#body');

    return textarea.getSelection().text;
  };

  factory.htmlMode = function() {
    return $('#body').is(':visible');
  };

  factory.insertContent = function(type, content, data, additional) {
    var textarea  = $('#body'),
        /* selector is used on update.bml and also s2 commenting form */

        parts     = content.split('{caret}'),
        selection;

    if (factory.htmlMode()) {
      textarea.surroundSelectedText(
        parts[0],
        parts.length > 1 ? (parts[parts.length - 1] || '') : ''
      ).trigger('input');

      selection = textarea.getSelection();

      // use text between {caret} if selection is empty,
      // move caret to the end
      if (parts.length === 3 && selection.length === 0) {
        textarea
          .replaceSelectedText(parts[1], 'collapseToEnd')
          .setSelection(selection.start + parts[1].length + parts[parts.length - 1].length);
      }
    } else {
      if (type === 'color') {
        return LJ.Event.trigger('selectedColor', data);
      }

      LJ.Event.trigger(type + '_response', data || content, additional);
    }
  };

  return factory;
})
.controller('EditorCtrl', ['$scope', 'Editor', 'Bubble', '$timeout',
                  function( $scope ,  Editor ,  Bubble ,  $timeout ) {

    var basicFormatting = {
      bold: '<b>{caret}</b>',
      italic: '<i>{caret}</i>',
      underline: '<u>{caret}</u>',
      strikethrough: '<s>{caret}</s>'
    };

    var photoUploaderNode = $(document);

    $scope.formattingAction = function(event, type) {
      event.preventDefault();

      if (basicFormatting[type]) {
        Editor.insertContent(type, basicFormatting[type]);
      }
    };

    $scope.userClick = function(event, type) {
      var selected = Editor.getSelectedText(),
          rxUsername = /^[A-Za-z0-9_\-]+$/;

      event.preventDefault();

      if (rxUsername.test(selected)) {
        Editor.insertContent(type, '<lj user="{caret}" />');
      } else {
        $timeout(function() {
          Bubble.open('user');
        });
      }
    };

    photoUploaderNode.photouploader(Site.page.fotki.uploader);

    $scope.photoUploaderClick = function(event) {
      event.preventDefault();

      if (LJ.get('disabled_input')) {
        return;
      }

      photoUploaderNode
        .photouploader('option', 'type', 'upload')
        .photouploader('show')
        .on('htmlready', function (data) {
          Editor.insertContent('photo', data.htmlStrings.join('\n'));
        });
    };

    $scope.toggleSpellcheck = function(event) {
      event.preventDefault();
      $scope.spellcheck = !$scope.spellcheck;
    };

    var widget = $('<div />').basicWidget().data('basicWidget');
    $scope.$watch('spellcheck', function(value, prevValue) {
      if (value !== prevValue) {
        widget._fire('toggle', ['spell', value], true);
      }
    });
}]);

})(jQuery);
;

/* file-end: js/editor/editor.js 
----------------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------------
   file-start: js/editor/media.js 
*/

LJ.define('LJ.Media');

/**
 * Parse link or embed html.
 * @param  {String} input  Input can contain link or html.
 * @return {Object} Object representing the media.
 */

LJ.Media.parse = (function() {
  'use strict';

  function parseMediaLink(input) {
    var link = {
      'youtube': 'http://youtube.com/watch?v={id}',
      'vimeo': 'http://vimeo.com/{id}',
      'vine': 'http://vine.co/v/{id}',
      'instagram': 'http://instagram.com/p/{id}/',
      'gist' : 'https://gist.github.com/{id}'
    };

    var embed = {
      'youtube': '<iframe src="http://www.youtube.com/embed/{id}" width="560" height="315" frameborder="0" allowfullscreen data-link="{link}"></iframe>'.supplant({link: link.youtube}),
      'vimeo'  : '<iframe src="http://player.vimeo.com/video/{id}" width="560" height="315" frameborder="0" allowfullscreen data-link="{link}"></iframe>'.supplant({link: link.vimeo}),
      'vine'   : '<iframe src="http://vine.co/v/{id}/card" width="380" height="380" frameborder="0" data-link="{link}"></iframe>'.supplant({link: link.vine}),
      'instagram' : '<iframe src="//instagram.com/p/{id}/embed/" width="612" height="710" frameborder="0" scrolling="no" allowtransparency="true"  data-link="{link}"></iframe>'.supplant({link: link.instagram}),
      'gist' : '<a data-expand="false" href="https://gist.github.com/{id}">gist.github.com/{id}</a>'.supplant({link: link.gist})
    };

    var provider = {
      'vine': {
        parse: function(input) {
          // http://vine.co/v/bdbF0i72uwA
          var matcher = /vine.co\/v\/([^\/]*)/,
              match = input.match(matcher);

          return (match && match[1]) || null;
        }
      },

      'vimeo': {
        parse: function(input) {
          var matcher = /^(http:\/\/)?(www\.)?(player\.)?vimeo.com\/(video\/)?(\d+)*/,
              match = input.match(matcher);

          return (match && match[5]) || null;
        }
      },

      'youtube': {
        parse: function(input) {
          // http://stackoverflow.com/a/8260383
          var matcher = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\??v?=?))([^#\&\?]*).*/,
              match = input.match(matcher);

          if (match && match[0].indexOf('youtu') === -1) {
            return null;
          }

          // we really should move from regexp to querystring parsing
          var qs = LiveJournal.parseGetArgs(input);
          if (qs.v) {
            return qs.v;
          }

          return (match && match[7]) || null;
        }
      },

      'instagram': {
        parse: function(input) {
          var matcher = /.*(?:instagram\.\w*|instagr\.am)\/p\/([^\/]+).*/,
              match = input.match(matcher);

          return (match && match[1]) || null;
        }
      },

      'gist': {
        parse: function(input) {
          var matcher = /.*(?:gist\.github\.com\/)([^\/]+\/{1}[^\/]+)\/{0,1}$/,
              match = input.match(matcher);

          return (match && match[1]) || null;
        }
      }
    };

    var id, key, result;
    for (key in provider) {
      if (provider.hasOwnProperty(key)) {
        id = provider[key].parse(input.trim());
        if (id) {
          result = {
            site: key,
            id: id
          };

          if (embed[key]) {
            result.embed = embed[key].supplant(result);
          }

          if (link[key]) {
            result.link = link[key].supplant(result);
          }

          return result;
        }
      }
    }

    return null;
  }

  return function(input) {

    // jQuery can fail on input
    try {
      var node = jQuery(input).first(), src;

      if (node && node.prop('tagName').toLowerCase() === 'iframe') {
        src = node && node.attr('src');

        if (src) {
          return parseMediaLink(src);
        }
      }
    } catch (e) {
      return parseMediaLink(input);
    }
  };
})();;

/* file-end: js/editor/media.js 
----------------------------------------------------------------------------------*/

/*
 * Module is responsible for buttons:
 * - Link
 * - User
 * - Embed
 *
 * This buttons are used on both update.bml and S1 comments.
 *
 * @author
 *   Artem Tyurin (artem.tyurin@sup.com)
 */

;(function() {

'use strict';

angular.module('BasicToolbar', [
  'LJ.Bubble',
  'LJ.Api',
  'Editor'
])
.controller('MediaCtrl', ['$scope', 'Editor',
                 function( $scope ,  Editor ) {

    $scope.media = '';

    $scope.setHint = function($event) {
      var target = $event.target,
          href   = target.getAttribute('href');

      if (href) {
          $scope.media = href;
      }

      $event.preventDefault();
    };

    $scope.getMedia = function(input) {
      var media = LJ.Media.parse(input),
          output,

          /*
           * RuTube is an exception and its links can be used
           * like <lj-embed>http://rutube.ru/video/90e2fbcd220cd26148fcb558126da73c/</lj-embed>
           */
          useLJEmbed = /rutube\.ru\/video\//.test(input);

      if (media && media.embed) {
          output = media.embed;
      } else if (/^<(embed|iframe|object).*>$/.test(input) || useLJEmbed) {
          output = ['<lj-embed>', input, '</lj-embed>'].join('\n');
      } else {
          output = '<a href="{link}">{caret}{link}{caret}</a>'.supplant({ link: input });
      }

      return output;
    };

    $scope.insert = function() {
      Editor.insertContent('video', $scope.getMedia($scope.media), $scope.media);

      $scope.media = '';
      $scope.bubble.close();
    };
}])
.controller('LinkCtrl', ['$scope', 'Editor', 'Bubble',
                function( $scope ,  Editor ,  Bubble ) {

  $scope.unlink = function() {
    LJ.Event.trigger('unlink'); // visual editor handles the event
    $scope.bubble.close();
  };

  $scope.$watch(function() {
    return Bubble.current === 'link';
  }, function(value) {

    if (value) {
      $scope.link = $scope.bubble.options.defaultText || '';
      $scope.showUnlink = !!($scope.bubble.options.rangeNotCollapsed || $scope.bubble.options.editMode);
      $scope.newWindow = (typeof $scope.bubble.options.hasTarget !== 'undefined') ? $scope.bubble.options.hasTarget : true;
    }

  });

  $scope.insertOrSave = function() {

    /*
     * If there is selected text, surround it with <a></a>,
     * otherwise use href as link text and move caret after </a>.
     */

    Editor.insertContent(
      'link',
      '<a href="{text}"{target}>{caret}{text}{caret}</a>'.supplant({
        text: LJ.String.linkify($scope.link),
        target: $scope.newWindow ? ' target="_blank"' : ''
      }),
      {
        url: $scope.link,
        target: $scope.newWindow ? '_blank' : ''
      }
    );

    $scope.link = '';
    $scope.bubble.close();
  };
}])
.controller('UserCtrl', ['$scope', 'Editor', 'Bubble', 'Api',
                function( $scope ,  Editor ,  Bubble ,  Api ) {

  $scope.$watch(function() {
    return Bubble.current === 'user';
  }, function(value) {
    if (value) {
      $scope.user  = $scope.bubble.options.user || '';

      // title could be one of: undefined, 'undefined', or actual title string
      $scope.title = $scope.bubble.options.title === 'undefined' ? '' : ( $scope.bubble.options.title || '');
      $scope.error = false;
    }
  });

  $scope.$watch('user', function() {
    $scope.error = false;
  });

  $scope.insertOrSave = function() {
    Api.call('ljuser.get', { user: $scope.user, raw: true }, function (data) {
      if (data.error) {
        $scope.error = true;
      } else {
        Editor.insertContent(
          'user',
          '<lj user="{caret}{text}{caret}" />'.supplant({
            text: $scope.user
          }),

          data,
          $scope.title
        );

        $scope.user  = '';
        $scope.title = '';

        $scope.bubble.close();
      }
    });
  };
}]);

})();
;

/* file-end: js/editor/basicToolbar.js 
----------------------------------------------------------------------------------*/

(function($) {

'use strict';

// fix forms
$(function() {
  $('[type="submit"]').on('click', function() {
    var form = $(this).closest('form');

    if (!form.attr('action') || form.attr('onclick')) {
      $(this).closest('form').submit();
    }
  });
});

angular.module('Entry', ['BasicToolbar'])
	/*
	 * Comment page uses lj-bubble directive (comment form),
	 * which uses ng-include inside bubble template.
	 *
	 * ng-include needs $AnchorScrollProvider, which lists $LocationProvider
	 * as a dependency, which triggers $locationChangeStart. This sends $digest
	 * into infinite loop when pushState is used from
	 * non-Angular code (s1 comments).
	 *
	 * This way we supress $LocationProvider init.
	 */
	.value('$anchorScroll', null);

})(jQuery);
;

/* file-end: js/entry/main.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/ljshare-init.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.lj.share.js 
*/

/* ---------------------------------------------------------------------------------
   file-start: js/core/object.js 
*/

;(function() {
    'use strict';

    LJ.define('LJ.Object');
    
    /**
     * Return a copy of the object only containing the whitelisted properties.
     * @param {Object} obj Object source
     * @param {String} keys* Keys which should be picked from source object
     * @return {Object} Copy of source object that contains only whitelisted keys
     */
    LJ.Object.pick = function(obj) {
        var copy = {},
            keys = Array.prototype.concat.apply(
                [], Array.prototype.slice.call(arguments, 1)
            );

        keys.forEach(function (key) {
            if (key in obj) {
                copy[key] = obj[key];
            }
        });

        return copy;
    };

})();;

/* file-end: js/core/object.js 
----------------------------------------------------------------------------------*/

LJ.UI.registerTemplate('templates-Widgets-share', "<div class=\"b-sharethis\"> <div class=\"b-sharethis-head\">${title}</div> <div class=\"b-sharethis-services\"> {{each(i, item) items}} <span class=\"b-sharethis-${item.service}\"> <a href=\"${item.url}\" target=\"_blank\" data-service=\"${item.service}\" class=\"b-sharethis-item\">${item.title}</a> </span> {{/each}} </div> </div>", 'JQuery.stat');
/**
 * @author Valeriy Vasin (valeriy.vasin@sup.com)
 * @fileOverview Plugin is responsible for sharing functionality
 * @requires jquery.lj.bubble.js
 */
;(function ($) {
    'use strict';

    /**
     * @todo Remove service defaults from JavaScript. It should come from server
     */

    // services defaults that will be used if server doesn't provide `services` option
    var SERVICES = {
        livejournal: {
            title: 'LiveJournal',
            bindLink: 'http://livejournal.com/update.bml?repost_type=c&repost={url}',
            openInTab: true
        },
        facebook: {
            title: 'Facebook',
            bindLink: 'http://www.facebook.com/sharer.php?u={url}'
        },
        twitter: {
            title: 'Twitter',
            bindLink: 'http://twitter.com/share?url={url}&text={title}&hashtags={hashtags}'
        },
        vkontakte: {
            title: 'Vkontakte',
            bindLink: 'http://vkontakte.ru/share.php?url={url}'
        },
        moimir: {
            title: 'Moi Mir',
            bindLink: 'http://connect.mail.ru/share?url={url}'
        },
        stumbleupon: {
            title: 'Stumbleupon',
            bindLink: 'http://www.stumbleupon.com/submit?url={url}',
            openInTab: true
        },
        digg: {
            title: 'Digg',
            bindLink: 'http://digg.com/submit?url={url}',
            openInTab: true
        },
        email: {
            title: 'E-mail',
            bindLink: 'http://api.addthis.com/oexchange/0.8/forward/email/offer?username=internal&url={url}&title={title}',
            height: 600
        },
        tumblr: {
            title: 'Tumblr',
            bindLink: 'http://www.tumblr.com/share?v=3&u={url}&description={text}'
        },
        odnoklassniki: {
            title: 'Odnoklassniki',
            bindLink: 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1&st._surl={url}'
        }
    };

    $.widget('lj.share', $.lj.basicWidget, {
        options: {
            selectors: {
                // button that activate bubble
                button: '.js-lj-share',
                item: '.b-sharethis-item',
                entry: '.js-lj-share-entry'
            },
            templates: {
                share: 'templates-Widgets-share'
            },
            ml: {
                title: 'sharing.popup.title'
            },
            // should come from server or initialize with defaults above
            services: null,
            // services to show
            links: null
        },

        _create: function () {
            $.lj.basicWidget.prototype._create.call(this);

            // bubble container
            this._container = $('<div />').appendTo( this.element );
            // currently active share button (needed to allow toggle bubble state)
            this._button = null;

            // services option hasn't been initialized explicitly
            if ( !this.options.services ) {

                // initialize from server params
                if (LJ.get('LJShareParams.services')) {
                    this.options.services = LJ.get('LJShareParams.services');
                } else {

                    // use defaults
                    this.options.services = SERVICES;
                }
            }

            // links opition hasn't been initialized explicitly
            if ( !this.options.links ) {

                // initialize from server options
                if (LJ.get('LJShareParams.links')) {
                    this.options.links = LJ.get('LJShareParams.links');
                } else {

                    // use defaults
                    this.options.links = this.options.services ? Object.keys(this.options.services) : [];
                }
            }

            this._bindControls();
        },

        _bindControls: function () {
            var that = this;

            $.lj.basicWidget.prototype._bindControls.call(this);

            // init bubble
            this._container.bubble();

            // click on sharing item inside sharing bubble
            this._container.on('click', this._s('item'), function (e) {
                that._share(e, this);
            });

            // click on sharing button
            this.element.on('click', this._s('button'), function (e) {
                that.shareButtonClick(e, this);
            });

            // click on share entry button
            this.element.on('click', this._s('entry'), function (e) {
                var service,
                    params,
                    link;

                e.preventDefault();

                service = $(this).data('service');
                params = that.getParams(this);
                link = that.createSharingLink(service, params);

                that.shareLink(link, service);
            });

            // handler for all layouts where we could not change html-code
            // and provide needed data-attributes and classname
            this.element.on('click', 'a', function (e) {
                var $this = $(this);

                // only sharing button click handler should work
                if ( $this.is( that._s('button') ) ) {
                    return;
                }

                // only entry click hangler should work
                if ( $this.is( that._s('entry') ) ) {
                    return;
                }

                // only item click handler should work
                if ( $this.is( that._s('item') ) ) {
                    return;
                }

                that.shareButtonClick(e, this, true);
            });
        },

        /**
         * Parse params from target node
         * @param  {HTMLElement}    target Share button node
         * @return {Object}         Params needed for sharing (double encoded)
         */
        getParams: function (target) {
            var data = $(target).data(),
                params = LJ.Object.pick(data, 'url', 'title', 'hashtags', 'text'),

                href,
                args,
                matches;

            // try to parse from link href and query string
            if ( !params.url ) {
                href = target.href;
                args = LiveJournal.parseGetArgs( href );

                if (typeof args.title !== 'undefined') {
                    params.title = args.title;
                }

                if (typeof args.hashtags !== 'undefined') {
                    params.hashtags = args.hashtags;
                }

                if (typeof args.text !== 'undefined') {
                    params.text = args.text;
                }

                matches = href.match(/(.*\.html)/);
                if (matches && matches[1]) {
                    // encode url because other params are escaped and server needs double escaping
                    params.url = encodeURIComponent(matches[1]);
                }

                // we should have title or hashtags inside the query string
                if ( typeof params.title === 'undefined' && typeof params.hashtags === 'undefined' ) {
                    return null;
                }
            }

            // double escape needed params, because server unescapes them during redirect
            // also set default value for params that not provided
            params.url = encodeURIComponent(params.url);
            params.title = encodeURIComponent(params.title || '');
            params.text = encodeURIComponent(params.text || '');

            params.hashtags = params.hashtags || '';

            return params;
        },

        /**
         * Handler for Share button click
         * @param {jQuery.Event} e          jQuery event object
         * @param {HTMLElement}  target     Share button node
         */
        shareButtonClick: function (e, target) {
            var $target = $(target),
                isCurrentButtonPressed = this._button === target,
                params = this.getParams(target);

            // prevent default action only for links sharing could be applied for
            if ( !params ) {
                return;
            }
            e.preventDefault();

            // just hide bubble if it's showed and we click on same share button again
            if (this._container.bubble('visible') && isCurrentButtonPressed) {
                this._container.bubble('hide');
                return;
            }

            // update bubble target and content
            if (this._button !== target) {
                this._setContentFor(params);
                this._container.bubble('option', 'target', $target);
                this._button = target;
            }

            // show bubble
            this._container
                .bubble('block', true) // prevent hiding bubble when click event bubbles to the document
                .bubble('show');

            return this;
        },

        /**
         * Share link handler
         * @param {jQuery.Event} e      jQuery event object
         * @param {HTMLElement} target  Share item link node
         */
        _share: function (e, target) {
            var $target = $(target),
                service = $target.data('service'),
                serviceObj = this.options.services[service];


            if ( !serviceObj ) {
                console.error('Service is not defined.');
                return;
            }

            // if we are trying to open in tab and browser supports it (IE > 8)
            // we should not prevent default action
            if ( !serviceObj.openInTab || ($.browser.msie && $.browser.version < 9) ) {
                e.preventDefault();
            }

            this._container.bubble('hide');
            this.shareLink(target.href, service);
        },

        /**
         * Share link for service
         */
        shareLink: function (url, service) {
            var serviceObj = this.options.services[service],
                width,
                height;


            if ( !serviceObj ) {
                console.error('Service is not defined.');
                return;
            }

            if (serviceObj.openInTab) {
                /**
                 * Notice: Internet Explorer version less than 9 doesn't support
                 *         opening links with target='_blank' in new tab and open
                 *         link in new window by default (depends on settings)
                 *         That's why we simulate this behavior through new window with
                 *         correct width and height params
                 */
                if ($.browser.msie && $.browser.version < 9) {
                    width = $(window).width();
                    height = $(window).height();
                    window.open(url, null, 'toolbar=yes,menubar=yes,status=1,location=yes,scrollbars=yes,resizable=yes,width=' + width + ',height=' + height);
                }
                /**
                 * all other browsers support target='_blank'
                 * and we should do nothing for opening in new tab
                 */
            } else {
                width = serviceObj.width || 640;
                height = serviceObj.height || 480;
                window.open(url, 'sharer', 'toolbar=0,status=0,width=' + width + ',height=' + height + ',scrollbars=yes,resizable=yes');
            }
        },

        /**
         * Create sharing link for exact service
         * @param  {String} service Service for which url should be generated
         * @param  {String} params  Params for url creation (title, url, etc)
         * @return {String}         Sharing link for provided service
         */
        createSharingLink: function (service, params) {
            var serviceObj = this.options.services[service];

            if ( !serviceObj || !serviceObj.bindLink ) {
                console.error('Service parameters error. URL cant be generated.');
                return;
            }

            return serviceObj.bindLink.supplant( params );
        },

        /**
         * Update sharing bubble content
         * @param {Object} params               Object for sharing links construction
         * @param {String} params.url           Url to share
         * @param {String} [params.title]       Title for sharing url (for some services: FB, Twitter, email)
         * @param {String} [params.hashtags]    Hashtags for twitter
         * @param {String} [params.text]        Entry text
         */
        _setContentFor: function (params) {
            var content,
                that = this;

            // update content should always be applied when bubble is hidden
            if ( this._container.bubble('visible') ) {
                this._container.bubble('hide');
            }

            // update bubble content
            content = this._tmpl('share', {
                title: this._ml('title'),
                items: this.options.links.map(function (serviceName) {
                    var service = that.options.services[serviceName],
                        shareURL = service.bindLink.supplant(params);

                    return {
                        service: serviceName,
                        url: shareURL,
                        title: service.title
                    };
                })
            });

            this._container.html(content);
        },

        /**
         * Sharing items inside the bubble
         */
        items: function () {
            return this
                ._container
                .find( this._s('item') );
        },

        /**
         * Hide sharing bubble
         */
        hide: function () {
            this._container.bubble('hide');
        },

        _setOption: function (option, value) {
            if (typeof value === 'undefined') {
                return;
            }

            switch (option) {
                case 'services':
                    this.options.services = $.extend(true, {}, this.options.services || {}, value);
                    break;
                case 'links':
                    this.options.links = value;
                    break;

                // no defaults
            }
        }
    });
}(jQuery));
;

/* file-end: js/jquery/jquery.lj.share.js 
----------------------------------------------------------------------------------*/

/**
 * @author Valeriy Vasin (valeriy.vasin@sup.com)
 * @description Initialization of share widget (js/jquery/lj.share.js)
 */
;(function ($) {
    'use strict';

    $(function () {
        $(document.body).share();
    });
}(jQuery));
;

/* file-end: js/ljshare-init.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/jquery/jquery.lj.journalPromoStrip.js 
*/

/**
 * @name $.lj.journalPromoStrip
 * @requires $.ui.core, $.ui.widget, $.lj.basicWidget, $.lj.bubble
 * @class Implements functionality of Promo in Journals page via JSON-RPC API
 * @extends $.lj.basicWidget
 * @author artem.tyurin@sup.com (Artem Tyurin)
 */

(function ($, window) {
	'use strict';

	$.widget('lj.journalPromoStrip', $.lj.basicWidget, {

		options: {
			selectors: {
				'popupInfo': '.journalpromo-popup-content-info',
				'popupDelete': '.journalpromo-popup-content-delete',

				'button': '#journalpromo-popup-btn',
				'iconClose': '.b-journalpromo-actions-close',

				'options': '.b-journalpromo-header-options',
				'promoItem': '.b-journalpromo-item',
				'iconDelete': '.b-journalpromo-actions-delete',

				'info': '.journalpromo-popup-info-action',
				'spinner': '.journalpromo-popup-spinner',
				'error': '.journalpromo-popup-info-error',
				'errorContent': '.journalpromo-popup-info-error-content',

				'ban': '#journalpromo-user-ban'
			},

			classNames: {
				'iconInfo': '.journalpromo-info-icon',
				'iconDelete': '.b-journalpromo-actions-delete',
				'noPromo': 'b-journalpromo-item-nopromotion'
			},

			template: "<dt><a href='{rules_link}'>{subject}</a> {ljuser}</dt><dd>{body}</dd>"
		},

		_create: function () {
			var that = this;
			$.lj.basicWidget.prototype._create.apply(this);

			this._el('spinner');
			this._el('info');
			this._el('button');
			this._el('iconClose');
			this._el('error');
			that._el('promoItem');
			this._el('iconDelete');
			this._el('popupDelete');
			this._el('errorContent');

			if (this._el('iconDelete')[0]) {
				this._deleteBubble = this._popupDelete.bubble({
					target: this._cl('iconDelete'),
					showOn: 'click'
				});
			}

			this._el('popupInfo').bubble({
				target: this._cl('iconInfo'),
				showOn: 'hover',
				closeControl: false,
				showDelay: 500
			});

			this._bindControls();
		},

		_toggleSpinner: function(isLoading) {
			this._spinner.toggle(isLoading);

			this._info.toggle(!isLoading);
		},

		_toggleError: function(isError, message) {
			this._error.toggle(isError);

			this._info.toggle(!isError);

			if (message) {
				this._errorContent.text(message);
			}
		},

		_updateBlock: function(entry) {
			if (!entry.object[0].object_url) {
				this._promoItem.html(
					'<span class="b-journalpromo-item-message">' +
					entry.object[0].body +
					'</span>'
				).addClass(this._cl('noPromo'));
			} else {
				this._promoItem.html(
					this.options.template.supplant({
						'rules_link': entry.object[0].object_url,
						'subject': entry.object[0].subject,
						'body': entry.object[0].body,
						'ljuser': entry.object[0].ljuser_display
					})
				);
			}
		},

		_closeClick: function() {
			var that = this;

			if (location.hash === '#__debug') {
				return this._debug();
			}

			that._toggleSpinner(true);

			LJ.Api.call('journalpromo.admin_cancel', {
				object_url: that.options.url,
				user: Site.currentJournal,
				get_slot: 1,
				ban_user: document.getElementById('journalpromo-user-ban').checked
			}, function(result) {
				that._toggleSpinner(false);

				console.dir(result);

				// promo could have been withdrawn after the page load
				if (result.error && result.error.data && result.error.data.entry) {
					that._updated = result.error.data.entry[0];
					that._toggleError(true, result.error.message);

					console.error(result.error.message);
					return;
				}

				if (!result.error && result.entry) {
					var entry = result.entry[0];

					if (!entry || !entry.object || !entry.object[0]) {
						console.error('Wrong data', result);
						return;
					}

					// re-render item and hide controls
					that._updateBlock(entry);
					that._iconDelete.hide();
				}

				that._deleteBubble.bubble('hide');
			});
		},

		_disableClick: function() {
			var that = this;
			LJ.Api.call('journalpromo.disable_promo_announce', {journal: LJ.get('currentJournal')}, function(result) {
				if (!result.error) {
					that.element.slideUp('fast');
				}
			});
		},

		_bindControls: function() {
			var that = this;
			$.lj.basicWidget.prototype._bindControls.apply(this);

			this._button.on('click', this._closeClick.bind(this));
			this._iconClose.on('click', this._disableClick.bind(this));

			if (this._deleteBubble) {
				this._deleteBubble.bind('bubblehide', function(ev) {
					that._toggleError(false);

					if (that._updated) {
						that._updateBlock(that._updated);
						that._iconDelete.hide();
					}
				});
			}
		},

		_debug: function() {
			var that = this;

			that._toggleSpinner(true);
			setTimeout(function() {
				that._toggleSpinner(false);
				that._toggleError(true, 'Sample error');
			}, 1000);
		}
	});
}(jQuery, window));
;

/* file-end: js/jquery/jquery.lj.journalPromoStrip.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/horizon-adaptive.js 
*/

(function($) {
	"use strict";

	var options = {
			item: '.s-navmenu-item',
			submenu: '.s-navmenu-submenu',
			activeItem: 's-navmenu-item-active'
		},
		currentActive = null,
		menuClicked = false;

	function changeLang() {
		var lang = this.value;

		if (lang) {
			LJ.Api.call('lang.set', {lang: lang}, function () {
				location.reload();
			});
		}
	}

	function docClick(ev) {
		if (currentActive && !menuClicked) {
			currentActive.removeClass(options.activeItem);
			currentActive = null;
		}

		menuClicked = false;
	}

	function menuClick(ev) {
		var newActive = jQuery(this).closest(options.item);

		//for touch devices we should just expand menu on first tap
		if (newActive.hasClass(options.activeItem) || newActive.find(options.submenu).length === 0) {
			return; //we should pass the handler here
		}

		if (currentActive) {
			currentActive.removeClass(options.activeItem);
		}

		currentActive = jQuery(this).closest(options.item);
		currentActive.addClass(options.activeItem);
		menuClicked = true;

		ev.preventDefault();
	}

	function initScheme() {
		$('#footer_lang_list').on('change', changeLang);

		if (LJ.Support.touch && window.vertigo) {
			$('.s-navmenu').on('click', '.s-navmenu-rootlink', menuClick);
			$(document).on('touchstart', docClick);
		}
	}

	LiveJournal.register_hook('page_load', initScheme);

	// toggle between menu / search field
	$(function () {
		var navbar = $('.s-navbar');

		navbar
			.find('.s-nav-local')
			.on('click', 'a', function () {
				navbar.toggleClass('s-show-local-search s-show-local-menu');
			});
	});
}(jQuery));
;

/* file-end: js/horizon-adaptive.js 
----------------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------------
   file-start: js/lj.api.js 
*/

(function ($) {
	'use strict';
	/**
	 * TODO:
	 *
	 * If this api will go outside of livejournal.com it should get rid of all dependencies
	 * from jquery.js and basic.js and should require only a few libs from LJ namespace through LJ.require
	 * to handle everything.
	 */

	/**
	 * @namespace LJ.Api
	 * @requires basic.js, jquery.js, livejournal.js, jquery/jquery.xdomainrequest.js, lj.postmessage.js
	 * @description Api provides an unified method to handle communications with the server.
	 * @author dmitry.petrov@sup.com (Dmitry Petrov), anazarov@sup.com (Alexander Nazarov)
	 */
	LJ.define('LJ.Api');

	var origin = location.protocol + '//' + location.host,
		siteroot = window.Site? Site.siteroot : origin,
		url = '/__api/',
		cdn = {
			endpoint: (window.Site && location.protocol === 'http:')? (Site.jsonrpcprefix || Site.statprefix) : null,
			time: (window.Site? Site.server_time * 1000 : +new Date()),
			methods: {}
		},
		context = {
			options: {},
			endpoint: siteroot,
			sameDomain: siteroot === origin,
			batchTimeout: 125
		},
		batchQueue = [],
		batchTimeout,
		corsParameters = $.extend({
			url: context.endpoint + url,
			type: 'POST',
			dataType: 'json',
			contentType: 'text/plain'
		}, context.sameDomain? {} : {
			xhrFields: {
				withCredentials: true
			}
		}),
		inactivityInterval;

	cdn.time -= cdn.time % 9E+5;

	function createRequestBody(name, params) {
		return {
			jsonrpc: '2.0',
			method: name,
			params: $.extend({}, params, { auth_token: context.options.auth_token }),
			id: Unique.id()
		};
	}

	function handleAnswer (name, params, callback, answer) {
		if (answer.result) {
			if (!answer.result.auth_token) {
				LJ.console.warn('Server did not return the new auth_token, further request may fail');
			} else {
				context.options.auth_token = answer.result.auth_token;
				delete answer.result.auth_token;
			}

			if (callback) {
				callback(answer.result);
			}
		} else if (answer.error) {
			if (callback) {
				callback({ error: answer.error });
			}
		} else {
			LJ.warn('Server did not return error or result in response for method ' + name);

			if (callback) {
				callback({
					error: {
						message: 'Invalid response',
						code: 2
					}
				});
			}
		}
	}

	function handleError (name, params, callback) {
		LJ.warn('An internal error has occured while calling the method ', name);

		if (callback) {
			callback({
				error: {
					message: 'Internal error',
					code: 1
				}
			});
		}
	}

	function defer (request, params, callback) {
		var promise = new $.Deferred();

		batchQueue.push({
			data: request,
			params: params,
			callback: callback,
			promise: promise
		});

		if (!batchTimeout) {
			batchTimeout = setTimeout(function () {
				var query = batchQueue.splice(0, batchQueue.length);

				$.ajax($.extend(corsParameters, {
					data: JSON.stringify(query.map(function (request) { return request.data; }))
				})).success(function (data) {
					var i, j, l, k, response, request;

					for (i = 0, l = data.length; i < l; i++) {
						response = data[i];

						for (j = 0, k = query.length; j < k; j++) {
							request = query[j];

							if (request.data.id === response.id) {
								if (request.promise.state() === 'pending') {
									/* Return result */
									handleAnswer(request.data.method, request.params, request.callback, response);
									request.promise.resolve();
								}
							}
						}
					}

					/* Some requests left unresolved */
					for (j = 0, k = query.length; j < k; j++) {
						request = query[j];

						if (request.promise.state() === 'pending') {
							handleError(request.data.method, request.params, request.callback);
							request.promise.resolve();
						}
					}
				}).error(function () {
					var i, l, request;

					for (i = 0, l = query.length; i < l; i++) {
						request = query[i];

						if (request.promise.state() === 'pending') {
							/* Return error */
							handleError(request.data.method, request.params, request.callback);
							request.promise.resolve();
						}
					}
				});

				batchTimeout = null;
			}, context.batchTimeout);
		}

		return promise;
	}

	/**
	 * Init LJ functionality.
	 *
	 * @param {Object} options Options for init object. auth_token field is required for further actions.
	 */
	LJ.Api.init = function(options) {
		options = options || {};

		if (context._initFired) {
			LJ.console.warn('LJ.Api.init was already called before');
		}

		context._initFired = true;
		context.options = $.extend({}, options);

		if (!context.options.auth_token) {
			LJ.console.warn('Auth token has not been specified, request may fail');
		}

		if (cdn.endpoint) {
			if (Site.rpc && Array.isArray(Site.rpc.public)) {
				Site.rpc.public.forEach(function (method) {
					cdn.methods[method] = true;
				});
			}
		}

		LJ.UI.bootstrap('lj-api');
	};

	/**
	 * Call api method on the server.
	 *
	 * @param {string} name Method name.
	 * @param {Object=} params A hash with parameters to send to the server.
	 * @param {Function=} callback Callback will be fired with results from the server.
	 */
	LJ.Api.call = function (name, params, callback) {
		var request = createRequestBody(name, params),
			publicMethod = !!cdn.methods.hasOwnProperty(name),
			endpoint = publicMethod? cdn.endpoint : context.endpoint,
			ajax, reqstr;

		// see LJ.Api.setInactivityInterval
		if (LJ.Activity.isInactiveMoreThan(inactivityInterval)) {
			LJ.Track.event('Site', 'Inactivity', 'API call aborted');
			console.log('Request is aborted due to inactivity');
			return;
		}

		if (!publicMethod && (LJ.Support.cors || context.sameDomain)) {
			/* CORS support detected or is not needed */
			return defer(request, params, callback);
		}

		/* Fall back to JSONP */
		if (publicMethod) {
			delete request.params.auth_token;
			request.id = cdn.time;
		}

		reqstr = JSON.stringify(request);

		ajax = $.ajax($.extend({
			url: endpoint + url,
			dataType: 'jsonp',
			data: { request: reqstr }
		}, publicMethod? {
			cache: true,
			
			/*
			 * Name is added to handle the case with several requests,
			 * which complete not in order. Otherwise request will
			 * fail because jQuery deletes callback after the response
			 */
			jsonpCallback: 'jQuery' + cdn.time + name.split('.').join('__')
		} : {}));

		ajax
			.success(handleAnswer.bind(null, name, params, callback))
			.error(handleError.bind(null, name, params, callback));

		return ajax.promise();
	};

	/*
	 * Disable API calls when page is not active.
	 * Tracking code is in core/track.js.
	 *
	 * @param {Number} interval Interval in ms
	 */
	LJ.Api.setInactivityInterval = function(interval) {
		if (!LJ.Activity.hasInterval(interval)) {
			throw new Error('Wrong interval parameter');
		}

		inactivityInterval = interval;
	};
}(jQuery));
;

/* file-end: js/lj.api.js 
----------------------------------------------------------------------------------*/
