public class SlidingMenu extends RelativeLayout {

	private static final String TAG = SlidingMenu.class.getSimpleName();

	public static final int SLIDING_WINDOW = 0;
	public static final int SLIDING_CONTENT = 1;
	private boolean mActionbarOverlay = false;

	/** Constant value for use with setTouchModeAbove(). Allows the SlidingMenu to be opened with a swipe
	 * gesture on the screen's margin
	 */
	public static final int TOUCHMODE_MARGIN = 0;

	/** Constant value for use with setTouchModeAbove(). Allows the SlidingMenu to be opened with a swipe
	 * gesture anywhere on the screen
	 */
	public static final int TOUCHMODE_FULLSCREEN = 1;

	/** Constant value for use with setTouchModeAbove(). Denies the SlidingMenu to be opened with a swipe
	 * gesture
	 */
	public static final int TOUCHMODE_NONE = 2;

	/** Constant value for use with setMode(). Puts the menu to the left of the content.
	 */
	public static final int LEFT = 0;

	/** Constant value for use with setMode(). Puts the menu to the right of the content.
	 */
	public static final int RIGHT = 1;

	/** Constant value for use with setMode(). Puts menus to the left and right of the content.
	 */
	public static final int LEFT_RIGHT = 2;

	private CustomViewAbove mViewAbove;

	private CustomViewBehind mViewBehind;

	private OnOpenListener mOpenListener;
	
	private OnOpenListener mSecondaryOpenListner;

	private OnCloseListener mCloseListener;

	/**
	 * The listener interface for receiving onOpen events.
	 * The class that is interested in processing a onOpen
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addOnOpenListener<code> method. When
	 * the onOpen event occurs, that object's appropriate
	 * method is invoked
	 */
	public interface OnOpenListener {

		/**
		 * On open.
		 */
		public void onOpen();
	}

	/**
	 * The listener interface for receiving onOpened events.
	 * The class that is interested in processing a onOpened
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addOnOpenedListener<code> method. When
	 * the onOpened event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see OnOpenedEvent
	 */
	public interface OnOpenedListener {

		/**
		 * On opened.
		 */
		public void onOpened();
	}

	/**
	 * The listener interface for receiving onClose events.
	 * The class that is interested in processing a onClose
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addOnCloseListener<code> method. When
	 * the onClose event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see OnCloseEvent
	 */
	public interface OnCloseListener {

		/**
		 * On close.
		 */
		public void onClose();
	}

	/**
	 * The listener interface for receiving onClosed events.
	 * The class that is interested in processing a onClosed
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addOnClosedListener<code> method. When
	 * the onClosed event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see OnClosedEvent
	 */
	public interface OnClosedListener {

		/**
		 * On closed.
		 */
		public void onClosed();
	}

	/**
	 * The Interface CanvasTransformer.
	 */
	public interface CanvasTransformer {

		/**
		 * Transform canvas.
		 *
		 * @param canvas the canvas
		 * @param percentOpen the percent open
		 */
		public void transformCanvas(Canvas canvas, float percentOpen);
	}

	/**
	 * Instantiates a new SlidingMenu.
	 *
	 * @param context the associated Context
	 */
	public SlidingMenu(Context context) {
		this(context, null);
	}

	/**
	 * Instantiates a new SlidingMenu and attach to Activity.
	 *
	 * @param activity the activity to attach slidingmenu
	 * @param slideStyle the slidingmenu style
	 */
	public SlidingMenu(Activity activity, int slideStyle) {
		this(activity, null);
		this.attachToActivity(activity, slideStyle);
	}

	/**
	 * Instantiates a new SlidingMenu.
	 *
	 * @param context the associated Context
	 * @param attrs the attrs
	 */
	public SlidingMenu(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	/**
	 * Instantiates a new SlidingMenu.
	 *
	 * @param context the associated Context
	 * @param attrs the attrs
	 * @param defStyle the def style
	 */
	public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
		LayoutParams behindParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		mViewBehind = new CustomViewBehind(context);
		addView(mViewBehind, behindParams);
		LayoutParams aboveParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		mViewAbove = new CustomViewAbove(context);
		addView(mViewAbove, aboveParams);
		// register the CustomViewBehind with the CustomViewAbove
		mViewAbove.setCustomViewBehind(mViewBehind);
		mViewBehind.setCustomViewAbove(mViewAbove);
		mViewAbove.setOnPageChangeListener(new OnPageChangeListener() {
			public static final int POSITION_OPEN = 0;
			public static final int POSITION_CLOSE = 1;
			public static final int POSITION_SECONDARY_OPEN = 2;

			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) { }

			public void onPageSelected(int position) {
				if (position == POSITION_OPEN && mOpenListener != null) {
					mOpenListener.onOpen();
				} else if (position == POSITION_CLOSE && mCloseListener != null) {
					mCloseListener.onClose();
				} else if (position == POSITION_SECONDARY_OPEN && mSecondaryOpenListner != null ) {
					mSecondaryOpenListner.onOpen();
				}
			}
		});

		// now style everything!
		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingMenu);
		// set the above and behind views if defined in xml
		int mode = ta.getInt(R.styleable.SlidingMenu_mode, LEFT);
		setMode(mode);
		int viewAbove = ta.getResourceId(R.styleable.SlidingMenu_viewAbove, -1);
		if (viewAbove != -1) {
			setContent(viewAbove);
		} else {
			setContent(new FrameLayout(context));
		}
		int viewBehind = ta.getResourceId(R.styleable.SlidingMenu_viewBehind, -1);
		if (viewBehind != -1) {
			setMenu(viewBehind); 
		} else {
			setMenu(new FrameLayout(context));
		}
		int touchModeAbove = ta.getInt(R.styleable.SlidingMenu_touchModeAbove, TOUCHMODE_MARGIN);
		setTouchModeAbove(touchModeAbove);
		int touchModeBehind = ta.getInt(R.styleable.SlidingMenu_touchModeBehind, TOUCHMODE_MARGIN);
		setTouchModeBehind(touchModeBehind);

		int offsetBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindOffset, -1);
		int widthBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindWidth, -1);
		if (offsetBehind != -1 && widthBehind != -1)
			throw new IllegalStateException("Cannot set both behindOffset and behindWidth for a SlidingMenu");
		else if (offsetBehind != -1)
			setBehindOffset(offsetBehind);
		else if (widthBehind != -1)
			setBehindWidth(widthBehind);
		else
			setBehindOffset(0);
		float scrollOffsetBehind = ta.getFloat(R.styleable.SlidingMenu_behindScrollScale, 0.33f);
		setBehindScrollScale(scrollOffsetBehind);
		int shadowRes = ta.getResourceId(R.styleable.SlidingMenu_shadowDrawable, -1);
		if (shadowRes != -1) {
			setShadowDrawable(shadowRes);
		}
		int shadowWidth = (int) ta.getDimension(R.styleable.SlidingMenu_shadowWidth, 0);
		setShadowWidth(shadowWidth);
		boolean fadeEnabled = ta.getBoolean(R.styleable.SlidingMenu_fadeEnabled, true);
		setFadeEnabled(fadeEnabled);
		float fadeDeg = ta.getFloat(R.styleable.SlidingMenu_fadeDegree, 0.33f);
		setFadeDegree(fadeDeg);
		boolean selectorEnabled = ta.getBoolean(R.styleable.SlidingMenu_selectorEnabled, false);
		setSelectorEnabled(selectorEnabled);
		int selectorRes = ta.getResourceId(R.styleable.SlidingMenu_selectorDrawable, -1);
		if (selectorRes != -1)
			setSelectorDrawable(selectorRes);
		ta.recycle();
	}

	/**
	 * Attaches the SlidingMenu to an entire Activity
	 * 
	 * @param activity the Activity
	 * @param slideStyle either SLIDING_CONTENT or SLIDING_WINDOW
	 */
	public void attachToActivity(Activity activity, int slideStyle) {
		attachToActivity(activity, slideStyle, false);
	}

	/**
	 * Attaches the SlidingMenu to an entire Activity
	 * 
	 * @param activity the Activity
	 * @param slideStyle either SLIDING_CONTENT or SLIDING_WINDOW
	 * @param actionbarOverlay whether or not the ActionBar is overlaid
	 */
	public void attachToActivity(Activity activity, int slideStyle, boolean actionbarOverlay) {
		if (slideStyle != SLIDING_WINDOW && slideStyle != SLIDING_CONTENT)
			throw new IllegalArgumentException("slideStyle must be either SLIDING_WINDOW or SLIDING_CONTENT");

		if (getParent() != null)
			throw new IllegalStateException("This SlidingMenu appears to already be attached");

		// get the window background
		TypedArray a = activity.getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowBackground});
		int background = a.getResourceId(0, 0);
		a.recycle();

		switch (slideStyle) {
		case SLIDING_WINDOW:
			mActionbarOverlay = false;
			ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
			ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
			// save ActionBar themes that have transparent assets
			decorChild.setBackgroundResource(background);
			decor.removeView(decorChild);
			decor.addView(this);
			setContent(decorChild);
			break;
		case SLIDING_CONTENT:
			mActionbarOverlay = actionbarOverlay;
			// take the above view out of
			ViewGroup contentParent = (ViewGroup)activity.findViewById(android.R.id.content);
			View content = contentParent.getChildAt(0);
			contentParent.removeView(content);
			contentParent.addView(this);
			setContent(content);
			// save people from having transparent backgrounds
			if (content.getBackground() == null)
				content.setBackgroundResource(background);
			break;
		}
	}

	/**
	 * Set the above view content from a layout resource. The resource will be inflated, adding all top-level views
	 * to the above view.
	 *
	 * @param res the new content
	 */
	public void setContent(int res) {
		setContent(LayoutInflater.from(getContext()).inflate(res, null));
	}

	/**
	 * Set the above view content to the given View.
	 *
	 * @param view The desired content to display.
	 */
	public void setContent(View view) {
		mViewAbove.setContent(view);
		showContent();
	}

	/**
	 * Retrieves the current content.
	 * @return the current content
	 */
	public View getContent() {
		return mViewAbove.getContent();
	}

	/**
	 * Set the behind view (menu) content from a layout resource. The resource will be inflated, adding all top-level views
	 * to the behind view.
	 *
	 * @param res the new content
	 */
	public void setMenu(int res) {
		setMenu(LayoutInflater.from(getContext()).inflate(res, null));
	}

	/**
	 * Set the behind view (menu) content to the given View.
	 *
	 * @param view The desired content to display.
	 */
	public void setMenu(View v) {
		mViewBehind.setContent(v);
	}

	/**
	 * Retrieves the main menu.
	 * @return the main menu
	 */
	public View getMenu() {
		return mViewBehind.getContent();
	}

	/**
	 * Set the secondary behind view (right menu) content from a layout resource. The resource will be inflated, adding all top-level views
	 * to the behind view.
	 *
	 * @param res the new content
	 */
	public void setSecondaryMenu(int res) {
		setSecondaryMenu(LayoutInflater.from(getContext()).inflate(res, null));
	}

	/**
	 * Set the secondary behind view (right menu) content to the given View.
	 *
	 * @param view The desired content to display.
	 */
	public void setSecondaryMenu(View v) {
		mViewBehind.setSecondaryContent(v);
		//		mViewBehind.invalidate();
	}

	/**
	 * Retrieves the current secondary menu (right).
	 * @return the current menu
	 */
	public View getSecondaryMenu() {
		return mViewBehind.getSecondaryContent();
	}


	/**
	 * Sets the sliding enabled.
	 *
	 * @param b true to enable sliding, false to disable it.
	 */
	public void setSlidingEnabled(boolean b) {
		mViewAbove.setSlidingEnabled(b);
	}

	/**
	 * Checks if is sliding enabled.
	 *
	 * @return true, if is sliding enabled
	 */
	public boolean isSlidingEnabled() {
		return mViewAbove.isSlidingEnabled();
	}

	/**
	 * Sets which side the SlidingMenu should appear on.
	 * @param mode must be either SlidingMenu.LEFT or SlidingMenu.RIGHT
	 */
	public void setMode(int mode) {
		if (mode != LEFT && mode != RIGHT && mode != LEFT_RIGHT) {
			throw new IllegalStateException("SlidingMenu mode must be LEFT, RIGHT, or LEFT_RIGHT");
		}
		mViewBehind.setMode(mode);
	}

	/**
	 * Returns the current side that the SlidingMenu is on.
	 * @return the current mode, either SlidingMenu.LEFT or SlidingMenu.RIGHT
	 */
	public int getMode() {
		return mViewBehind.getMode();
	}

	/**
	 * Sets whether or not the SlidingMenu is in static mode (i.e. nothing is moving and everything is showing)
	 *
	 * @param b true to set static mode, false to disable static mode.
	 */
	public void setStatic(boolean b) {
		if (b) {
			setSlidingEnabled(false);
			mViewAbove.setCustomViewBehind(null);
			mViewAbove.setCurrentItem(1);
			//			mViewBehind.setCurrentItem(0);	
		} else {
			mViewAbove.setCurrentItem(1);
			//			mViewBehind.setCurrentItem(1);
			mViewAbove.setCustomViewBehind(mViewBehind);
			setSlidingEnabled(true);
		}
	}

	/**
	 * Opens the menu and shows the menu view.
	 */
	public void showMenu() {
		showMenu(true);
	}

	/**
	 * Opens the menu and shows the menu view.
	 *
	 * @param animate true to animate the transition, false to ignore animation
	 */
	public void showMenu(boolean animate) {
		mViewAbove.setCurrentItem(0, animate);
	}

	/**
	 * Opens the menu and shows the secondary menu view. Will default to the regular menu
	 * if there is only one.
	 */
	public void showSecondaryMenu() {
		showSecondaryMenu(true);
	}

	/**
	 * Opens the menu and shows the secondary (right) menu view. Will default to the regular menu
	 * if there is only one.
	 *
	 * @param animate true to animate the transition, false to ignore animation
	 */
	public void showSecondaryMenu(boolean animate) {
		mViewAbove.setCurrentItem(2, animate);
	}

	/**
	 * Closes the menu and shows the above view.
	 */
	public void showContent() {
		showContent(true);
	}

	/**
	 * Closes the menu and shows the above view.
	 *
	 * @param animate true to animate the transition, false to ignore animation
	 */
	public void showContent(boolean animate) {
		mViewAbove.setCurrentItem(1, animate);
	}

	/**
	 * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa.
	 */
	public void toggle() {
		toggle(true);
	}

	/**
	 * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa.
	 *
	 * @param animate true to animate the transition, false to ignore animation
	 */
	public void toggle(boolean animate) {
		if (isMenuShowing()) {
			showContent(animate);
		} else {
			showMenu(animate);
		}
	}

	/**
	 * Checks if is the behind view showing.
	 *
	 * @return Whether or not the behind view is showing
	 */
	public boolean isMenuShowing() {
		return mViewAbove.getCurrentItem() == 0 || mViewAbove.getCurrentItem() == 2;
	}
	
	/**
	 * Checks if is the behind view showing.
	 *
	 * @return Whether or not the behind view is showing
	 */
	public boolean isSecondaryMenuShowing() {
		return mViewAbove.getCurrentItem() == 2;
	}

	/**
	 * Gets the behind offset.
	 *
	 * @return The margin on the right of the screen that the behind view scrolls to
	 */
	public int getBehindOffset() {
		return ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams()).rightMargin;
	}

	/**
	 * Sets the behind offset.
	 *
	 * @param i The margin, in pixels, on the right of the screen that the behind view scrolls to.
	 */
	public void setBehindOffset(int i) {
		//		RelativeLayout.LayoutParams params = ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams());
		//		int bottom = params.bottomMargin;
		//		int top = params.topMargin;
		//		int left = params.leftMargin;
		//		params.setMargins(left, top, i, bottom);
		mViewBehind.setWidthOffset(i);
	}

	/**
	 * Sets the behind offset.
	 *
	 * @param resID The dimension resource id to be set as the behind offset.
	 * The menu, when open, will leave this width margin on the right of the screen.
	 */
	public void setBehindOffsetRes(int resID) {
		int i = (int) getContext().getResources().getDimension(resID);
		setBehindOffset(i);
	}

	/**
	 * Sets the above offset.
	 *
	 * @param i the new above offset, in pixels
	 */
	public void setAboveOffset(int i) {
		mViewAbove.setAboveOffset(i);
	}

	/**
	 * Sets the above offset.
	 *
	 * @param resID The dimension resource id to be set as the above offset.
	 */
	public void setAboveOffsetRes(int resID) {
		int i = (int) getContext().getResources().getDimension(resID);
		setAboveOffset(i);
	}

	/**
	 * Sets the behind width.
	 *
	 * @param i The width the Sliding Menu will open to, in pixels
	 */
	@SuppressWarnings("deprecation")
	public void setBehindWidth(int i) {
		int width;
		Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		try {
			Class<?> cls = Display.class;
			Class<?>[] parameterTypes = {Point.class};
			Point parameter = new Point();
			Method method = cls.getMethod("getSize", parameterTypes);
			method.invoke(display, parameter);
			width = parameter.x;
		} catch (Exception e) {
			width = display.getWidth();
		}
		setBehindOffset(width-i);
	}

	/**
	 * Sets the behind width.
	 *
	 * @param res The dimension resource id to be set as the behind width offset.
	 * The menu, when open, will open this wide.
	 */
	public void setBehindWidthRes(int res) {
		int i = (int) getContext().getResources().getDimension(res);
		setBehindWidth(i);
	}

	/**
	 * Gets the behind scroll scale.
	 *
	 * @return The scale of the parallax scroll
	 */
	public float getBehindScrollScale() {
		return mViewBehind.getScrollScale();
	}
	
	/**
	 * Gets the touch mode margin threshold
	 * @return the touch mode margin threshold
	 */
	public int getTouchmodeMarginThreshold() {
		return mViewBehind.getMarginThreshold();
	}
	
	/**
	 * Set the touch mode margin threshold
	 * @param touchmodeMarginThreshold
	 */
	public void setTouchmodeMarginThreshold(int touchmodeMarginThreshold) {
		mViewBehind.setMarginThreshold(touchmodeMarginThreshold);
	}

	/**
	 * Sets the behind scroll scale.
	 *
	 * @param f The scale of the parallax scroll (i.e. 1.0f scrolls 1 pixel for every
	 * 1 pixel that the above view scrolls and 0.0f scrolls 0 pixels)
	 */
	public void setBehindScrollScale(float f) {
		if (f < 0 && f > 1)
			throw new IllegalStateException("ScrollScale must be between 0 and 1");
		mViewBehind.setScrollScale(f);
	}

	/**
	 * Sets the behind canvas transformer.
	 *
	 * @param t the new behind canvas transformer
	 */
	public void setBehindCanvasTransformer(CanvasTransformer t) {
		mViewBehind.setCanvasTransformer(t);
	}

	/**
	 * Gets the touch mode above.
	 *
	 * @return the touch mode above
	 */
	public int getTouchModeAbove() {
		return mViewAbove.getTouchMode();
	}

	/**
	 * Controls whether the SlidingMenu can be opened with a swipe gesture.
	 * Options are {@link #TOUCHMODE_MARGIN TOUCHMODE_MARGIN}, {@link #TOUCHMODE_FULLSCREEN TOUCHMODE_FULLSCREEN},
	 * or {@link #TOUCHMODE_NONE TOUCHMODE_NONE}
	 *
	 * @param i the new touch mode
	 */
	public void setTouchModeAbove(int i) {
		if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN
				&& i != TOUCHMODE_NONE) {
			throw new IllegalStateException("TouchMode must be set to either" +
					"TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE.");
		}
		mViewAbove.setTouchMode(i);
	}

	/**
	 * Controls whether the SlidingMenu can be opened with a swipe gesture.
	 * Options are {@link #TOUCHMODE_MARGIN TOUCHMODE_MARGIN}, {@link #TOUCHMODE_FULLSCREEN TOUCHMODE_FULLSCREEN},
	 * or {@link #TOUCHMODE_NONE TOUCHMODE_NONE}
	 *
	 * @param i the new touch mode
	 */
	public void setTouchModeBehind(int i) {
		if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN
				&& i != TOUCHMODE_NONE) {
			throw new IllegalStateException("TouchMode must be set to either" +
					"TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE.");
		}
		mViewBehind.setTouchMode(i);
	}

	/**
	 * Sets the shadow drawable.
	 *
	 * @param resId the resource ID of the new shadow drawable
	 */
	public void setShadowDrawable(int resId) {
		setShadowDrawable(getContext().getResources().getDrawable(resId));
	}

	/**
	 * Sets the shadow drawable.
	 *
	 * @param d the new shadow drawable
	 */
	public void setShadowDrawable(Drawable d) {
		mViewBehind.setShadowDrawable(d);
	}

	/**
	 * Sets the secondary (right) shadow drawable.
	 *
	 * @param resId the resource ID of the new shadow drawable
	 */
	public void setSecondaryShadowDrawable(int resId) {
		setSecondaryShadowDrawable(getContext().getResources().getDrawable(resId));
	}

	/**
	 * Sets the secondary (right) shadow drawable.
	 *
	 * @param d the new shadow drawable
	 */
	public void setSecondaryShadowDrawable(Drawable d) {
		mViewBehind.setSecondaryShadowDrawable(d);
	}

	/**
	 * Sets the shadow width.
	 *
	 * @param resId The dimension resource id to be set as the shadow width.
	 */
	public void setShadowWidthRes(int resId) {
		setShadowWidth((int)getResources().getDimension(resId));
	}

	/**
	 * Sets the shadow width.
	 *
	 * @param pixels the new shadow width, in pixels
	 */
	public void setShadowWidth(int pixels) {
		mViewBehind.setShadowWidth(pixels);
	}

	/**
	 * Enables or disables the SlidingMenu's fade in and out
	 *
	 * @param b true to enable fade, false to disable it
	 */
	public void setFadeEnabled(boolean b) {
		mViewBehind.setFadeEnabled(b);
	}

	/**
	 * Sets how much the SlidingMenu fades in and out. Fade must be enabled, see
	 * {@link #setFadeEnabled(boolean) setFadeEnabled(boolean)}
	 *
	 * @param f the new fade degree, between 0.0f and 1.0f
	 */
	public void setFadeDegree(float f) {
		mViewBehind.setFadeDegree(f);
	}

	/**
	 * Enables or disables whether the selector is drawn
	 *
	 * @param b true to draw the selector, false to not draw the selector
	 */
	public void setSelectorEnabled(boolean b) {
		mViewBehind.setSelectorEnabled(true);
	}

	/**
	 * Sets the selected view. The selector will be drawn here
	 *
	 * @param v the new selected view
	 */
	public void setSelectedView(View v) {
		mViewBehind.setSelectedView(v);
	}

	/**
	 * Sets the selector drawable.
	 *
	 * @param res a resource ID for the selector drawable
	 */
	public void setSelectorDrawable(int res) {
		mViewBehind.setSelectorBitmap(BitmapFactory.decodeResource(getResources(), res));
	}

	/**
	 * Sets the selector drawable.
	 *
	 * @param b the new selector bitmap
	 */
	public void setSelectorBitmap(Bitmap b) {
		mViewBehind.setSelectorBitmap(b);
	}

	/**
	 * Add a View ignored by the Touch Down event when mode is Fullscreen
	 *
	 * @param v a view to be ignored
	 */
	public void addIgnoredView(View v) {
		mViewAbove.addIgnoredView(v);
	}

	/**
	 * Remove a View ignored by the Touch Down event when mode is Fullscreen
	 *
	 * @param v a view not wanted to be ignored anymore
	 */
	public void removeIgnoredView(View v) {
		mViewAbove.removeIgnoredView(v);
	}

	/**
	 * Clear the list of Views ignored by the Touch Down event when mode is Fullscreen
	 */
	public void clearIgnoredViews() {
		mViewAbove.clearIgnoredViews();
	}

	/**
	 * Sets the OnOpenListener. {@link OnOpenListener#onOpen() OnOpenListener.onOpen()} will be called when the SlidingMenu is opened
	 *
	 * @param listener the new OnOpenListener
	 */
	public void setOnOpenListener(OnOpenListener listener) {
		//mViewAbove.setOnOpenListener(listener);
		mOpenListener = listener;
	}

	
	/**
	 * Sets the OnOpenListner for secondary menu  {@link OnOpenListener#onOpen() OnOpenListener.onOpen()} will be called when the secondary SlidingMenu is opened
	 * 
	 * @param listener the new OnOpenListener
	 */
	
	public void setSecondaryOnOpenListner(OnOpenListener listener) {
		mSecondaryOpenListner = listener;
	}
	
	/**
	 * Sets the OnCloseListener. {@link OnCloseListener#onClose() OnCloseListener.onClose()} will be called when any one of the SlidingMenu is closed
	 *
	 * @param listener the new setOnCloseListener
	 */
	public void setOnCloseListener(OnCloseListener listener) {
		//mViewAbove.setOnCloseListener(listener);
		mCloseListener = listener;
	}

	/**
	 * Sets the OnOpenedListener. {@link OnOpenedListener#onOpened() OnOpenedListener.onOpened()} will be called after the SlidingMenu is opened
	 *
	 * @param listener the new OnOpenedListener
	 */
	public void setOnOpenedListener(OnOpenedListener listener) {
		mViewAbove.setOnOpenedListener(listener);
	}

	/**
	 * Sets the OnClosedListener. {@link OnClosedListener#onClosed() OnClosedListener.onClosed()} will be called after the SlidingMenu is closed
	 *
	 * @param listener the new OnClosedListener
	 */
	public void setOnClosedListener(OnClosedListener listener) {
		mViewAbove.setOnClosedListener(listener);
	}

	public static class SavedState extends BaseSavedState {

		private final int mItem;

		public SavedState(Parcelable superState, int item) {
			super(superState);
			mItem = item;
		}

		private SavedState(Parcel in) {
			super(in);
			mItem = in.readInt();
		}

		public int getItem() {
			return mItem;
		}

		/* (non-Javadoc)
		 * @see android.view.AbsSavedState#writeToParcel(android.os.Parcel, int)
		 */
		public void writeToParcel(Parcel out, int flags) {
			super.writeToParcel(out, flags);
			out.writeInt(mItem);
		}

		public static final Parcelable.Creator<SavedState> CREATOR =
				new Parcelable.Creator<SavedState>() {
			public SavedState createFromParcel(Parcel in) {
				return new SavedState(in);
			}

			public SavedState[] newArray(int size) {
				return new SavedState[size];
			}
		};

	}

	/* (non-Javadoc)
	 * @see android.view.View#onSaveInstanceState()
	 */
	@Override
	protected Parcelable onSaveInstanceState() {
		Parcelable superState = super.onSaveInstanceState();
		SavedState ss = new SavedState(superState, mViewAbove.getCurrentItem());
		return ss;
	}

	/* (non-Javadoc)
	 * @see android.view.View#onRestoreInstanceState(android.os.Parcelable)
	 */
	@Override
	protected void onRestoreInstanceState(Parcelable state) {
		SavedState ss = (SavedState)state;
		super.onRestoreInstanceState(ss.getSuperState());
		mViewAbove.setCurrentItem(ss.getItem());
	}

	/* (non-Javadoc)
	 * @see android.view.ViewGroup#fitSystemWindows(android.graphics.Rect)
	 */
	@SuppressLint("NewApi")
	@Override
	protected boolean fitSystemWindows(Rect insets) {
		int leftPadding = insets.left;
		int rightPadding = insets.right;
		int topPadding = insets.top;
		int bottomPadding = insets.bottom;
		if (!mActionbarOverlay) {
			Log.v(TAG, "setting padding!");
			setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
		}
		return true;
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void manageLayers(float percentOpen) {
		if (Build.VERSION.SDK_INT < 11) return;

		boolean layer = percentOpen > 0.0f && percentOpen < 1.0f;
		final int layerType = layer ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE;

		if (layerType != getContent().getLayerType()) {
			getHandler().post(new Runnable() {
				public void run() {
					Log.v(TAG, "changing layerType. hardware? " + (layerType == View.LAYER_TYPE_HARDWARE));
					getContent().setLayerType(layerType, null);
					getMenu().setLayerType(layerType, null);
					if (getSecondaryMenu() != null) {
						getSecondaryMenu().setLayerType(layerType, null);
					}
				}
			});
		}
	}

} public class App extends Application {

    public static final String PCKG_NAME = "com.mv2studio.amarok.kontrol.";

	private static boolean sActivityVisible;
    private static boolean sNotificationVisible;
    private static App sContext;

    private Connector activeConnector;

    private Set<ConnectorUpdateCallback> connectorUpdateCallbackList = new HashSet<ConnectorUpdateCallback>();

	public App() {
		sContext = this;
	}

	@Override
	public void onCreate() {
        super.onCreate();
//		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());
//		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());

		// getPrefs
		PreferenceManager.setDefaultValues(App.this, R.xml.preferences, false);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(App.this);
		Prefs.setAll(prefs);
		Prefs.setScreenWidth(App.this);

        activeConnector = new AmarokConnector(this);
        activeConnector.setConnectorCallback(activeConnectorUpdateCallback);

        Intent intent = new Intent(this, ConnectionService.class);
        startService(intent);
	}

    public static App getInstance() {
        return sContext;
    }

	public static void activityResumed() {
		sActivityVisible = true;
		sContext.sendBroadcast(new Intent(ConnectionService.STOP_FOREGROUND));
        if (!CommonHelper.isServiceRunning(ConnectionService.class)) {
            Intent intent = new Intent(getInstance(), ConnectionService.class);
            getInstance().startService(intent);
        }
    }

	public static void activityPaused() {
		sActivityVisible = false;
		Handler h = new Handler();
		h.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (!sActivityVisible)
					sContext.sendBroadcast(new Intent(ConnectionService.START_FOREGROUND));
			}
		}, 100);
	}

	public static boolean isActivityVisible() {
		return sActivityVisible;
	}

    public static void setNotificationVisibility(boolean isVisible) {
        sNotificationVisible = isVisible;
    }

    public static boolean isNotificationVisible() {
        return sNotificationVisible;
    }

    private ConnectorUpdateCallback activeConnectorUpdateCallback = new ConnectorUpdateCallback() {
        @Override
        public void onDataUpdated(Song song, PlayingState state) {
            Bundle bundle = new Bundle();
            bundle.putParcelable(ConnectorUpdateCallback.BUNDLE_SONG, song);
            bundle.putInt(ConnectorUpdateCallback.BUNDLE_STATE, state.ordinal());

            for (ConnectorUpdateCallback clbk : connectorUpdateCallbackList) {
                clbk.send(RC_DATA_UPDATED, bundle);
            }
        }

        @Override
        public void onDataUnavailable(int errorCode, ConnectionMessage connectionMessage) {
            Bundle bundle = new Bundle();
            bundle.putInt(BUNDLE_ERROR_CODE, errorCode);
            bundle.putParcelable(BUNDLE_CONNECTION_MESSAGE, connectionMessage);

            for (ConnectorUpdateCallback clbk : connectorUpdateCallbackList) {
                clbk.send(RC_DATA_UNAVAILABLE, bundle);
            }
        }

        @Override
        public void onPlayingStateChanged(PlayingState state) {
            Bundle bundle = new Bundle();
            bundle.putInt(ConnectorUpdateCallback.BUNDLE_STATE, state.ordinal());

            for (ConnectorUpdateCallback clbk : connectorUpdateCallbackList) {
                clbk.send(RC_PLAYING_STATE_CHANGED, bundle);
            }
        }
    };

    public void updatePlaylist(PlaylistUpdateCallback callback) {
        activeConnector.updatePlaylist(callback);
    }

    public void registerConnectorCallback(ConnectorUpdateCallback callback) {
        connectorUpdateCallbackList.add(callback);
    }

    public void unregisterConnectorCallback(ConnectorUpdateCallback callback) {
        connectorUpdateCallbackList.remove(callback);
    }

    public void sendCommand(Command command) {
        activeConnector.sendCommand(command);
    }

    public Connector getActiveConnector() {
        return activeConnector;
    }
} public class PlaylistAdapter extends ArrayAdapter<Song> {

	protected static final int ALBUM = 0;
	protected static final int SONG = 1;

    protected ArrayList<Song> mData;
	protected BaseActivity mBaseActivity;
	protected LayoutInflater mInflater;

	protected BitmapConcurrencyHandler mBch;

    protected Song currentSong;


	public void replaceContext(BaseActivity context) {
		this.mBaseActivity = context;
	}

	public PlaylistAdapter(Context context, int textViewResourceId, final ArrayList<Song> songs) {
		super(context, textViewResourceId);
		this.mBaseActivity = (BaseActivity) context;
		this.mData = songs;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		try {
			songs.get(0).setNewAlbum(true);
			for(int songIndex = 1; songIndex < songs.size(); songIndex++) {
				if(!songs.get(songIndex).onSameAlbum(songs.get(songIndex-1))) {
					songs.get(songIndex).setNewAlbum(true);
				}
			}
		} catch (IndexOutOfBoundsException ex) {}

		mBch = new BitmapConcurrencyHandler(context);

        App.getInstance().registerConnectorCallback(mConnectorUpdateCallback);
	}

    public void unregisterConnectorCallback() {
        App.getInstance().unregisterConnectorCallback(mConnectorUpdateCallback);
    }

    public int getIndexOfCurrentSong() {
		for(int i = 0; i < mData.size(); i++) {
			if(mData.get(i).equals(currentSong)) return i;
		}
		return -1;
	}
	
	@Override
	public int getCount() {
		return mData.size();
	}
	
	public void removeAtPosition(int position) {
		mData.remove(position);
		this.notifyDataSetChanged();
	}
	
	@Override
	public Song getItem(int position) {
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public int getItemViewType(int position) {
		return mData.get(position).isNewAlbum() ? ALBUM : SONG;
	}
	
	public int getViewTypeCount() {
		return 2;		
	}
	
	@Override
	public void clear() {
		mData.clear();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void addAll(Collection<? extends Song> collection) {
		mData = (ArrayList<Song>) collection;
		try{ mData.get(0).setNewAlbum(true); } catch(IndexOutOfBoundsException ex) {  return; }
		for(int songIndex = 1; songIndex < collection.size(); songIndex++) {
			if(!mData.get(songIndex).onSameAlbum(mData.get(songIndex-1))) {
				mData.get(songIndex).setNewAlbum(true);
			}
		}
        notifyDataSetChanged();
	}
	
	@Override
	public View getView(final int position, View convertView, final ViewGroup parent) {
		ViewHolder holder;
		final Song song = getItem(position);

		if(convertView == null) {
			holder = new ViewHolder();
			int type = getItemViewType(position);
			
			switch(type) {
			case ALBUM:
				convertView = mInflater.inflate(R.layout.item_playlist_album, parent, false);
				holder.cover = (ImageView) convertView.findViewById(R.id.listSongCover);				
				holder.artist = (CustomTextView) convertView.findViewById(R.id.listSongArtist);
				holder.album = (CustomTextView) convertView.findViewById(R.id.listSongAlbum);
				holder.downloadText = (CustomTextView) convertView.findViewById(R.id.playlist_back_view_download_text);
				holder.removeText = (CustomTextView) convertView.findViewById(R.id.playlist_back_view_remove_text);

                holder.download = convertView.findViewById(R.id.playlist_back_view_download);
				holder.remove = convertView.findViewById(R.id.playlist_back_view_remove);
				break;
			case SONG:
				convertView = mInflater.inflate(R.layout.item_playlist_song, parent, false);
				holder.download = convertView.findViewById(R.id.playlist_back_view_download);
				holder.remove = convertView.findViewById(R.id.playlist_back_view_remove);
				break;
			}
			holder.backLayout = (LinearLayout) convertView.findViewById(R.id.back);
			holder.frontLayout = (RelativeLayout) convertView.findViewById(R.id.front);


            holder.playingIcon = (ImageView) convertView.findViewById(R.id.listSongPlayingIcon);
			convertView.setTag(holder);
			holder.title = (CustomTextView) convertView.findViewById(R.id.listSongTitle);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		 ((SwipeListView)parent).recycle(convertView, position);
		 ((SwipeListView)parent).closeOpenedItems();
		
		holder.frontLayout.setBackgroundColor(Color.parseColor((position % 2 == 0) ? "#77000000" : "#aa000000"));
		holder.frontLayout.setX(0f);

        holder.title.setTag(getItem(position).toString()); //TODO:null pointer

        if(getItemViewType(position) == ALBUM) {
            holder.song = song;
            holder.cover.setTag(position);

            mBch.loadBitmap(song.getArtist() + song.getAlbum() + "_mini", holder.cover);

            holder.artist.setText(song.getArtist());
            holder.album.setText(song.getAlbum());
        }

        holder.download.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((SwipeListView) parent).closeOpenedItems();
                try { MediaHelper.downloadSong(song.getId(), song, mBaseActivity); } catch(Exception e) {}
            }
        });

        holder.remove.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((SwipeListView) parent).closeOpenedItems();

                App.getInstance().sendCommand(
                        AmarokCommand.REMOVE_BY_INDEX.param(song.getId() + "").withCallback(
                                new CommandCallback() {
                                    @Override
                                    public void onResponse() {
                                        mBaseActivity.refreshPlaylist();
                                    }
                                }));
            }
        });

        holder.backLayout.setVisibility(View.INVISIBLE);
        holder.playingIcon.setVisibility((song.equals(currentSong)) ? View.VISIBLE : View.GONE);
        holder.title.setText(song.getTitle());

		return convertView;
	}
	
	public class ViewHolder {
		public ImageView cover, playingIcon, addedSongIcon, addedAlbumIcon;
		public CustomTextView artist, album, title, removeText, downloadText;
		public Song song;
		public int position;
		public Button albumHigh;
		public Button songHigh;
		public View remove, download;
		public RelativeLayout frontLayout;
		public LinearLayout backLayout;
	}

    private final ConnectorUpdateCallback mConnectorUpdateCallback = new ConnectorUpdateCallback() {
        @Override
        public void onDataUpdated(Song song, PlayingState state) {
            currentSong = song;
        }

        @Override
        public void onDataUnavailable(int errorCode, ConnectionMessage connectionMessage) {

        }

        @Override
        public void onPlayingStateChanged(PlayingState state) {

        }
    };

} public class Prefs {
	
	public static String ipPortKey = "pref_remote_server",
						 useVolButtonsKey = "pref_volume_change",
						 showNotifyKey = "pref_show_notify",
						 notifyShowPhotoKey = "pref_notify_photo",
						 closePlaylistKey = "pref_close_playlist",
						 notifyUpdateIntervalKey = "pref_notify_interval",
						 updateIntervalKey = "pref_interval",
						 volumeStepKey = "pref_vol_step",
						 clearCacheKey = "pref_clear_cache",
						 use3gKey = "pref_allow_3g",
						 blurKey = "pref_blur";
	
	private static final int defaultPort = 8484;

	private static String ipPort;
	public static boolean useVolButtons, showNotify, notifyShowPhoto, closePlaylist, use3g;
	public static int updateInterval, notifyUpdateInterval, volumeStep, blurIntensity;
	
	private static int screenWidth;

	public static int getScreenWidth() {
		return screenWidth;
	}
	
	public static void setScreenWidth(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display d = wm.getDefaultDisplay();
		Point p = new Point();
		d.getSize(p);
		screenWidth = Math.min(p.x, 720);
	}
	
	public static void setIp(SharedPreferences prefs) {
		ipPort = checkUrl(prefs.getString(ipPortKey, ""));
	}
	
	public static String checkUrl(String ip) {
		if(!ip.startsWith("http://")) ip = "http://"+ip;
		boolean useDefaultPort = (ip.split(":").length != 3);
		boolean lastColon = ip.charAt(ip.length()-1) == ':';

		if(useDefaultPort) {
			ip += ":"+defaultPort;
		} else if (lastColon) {
			ip += defaultPort;
		}
		return ip;	
	}
	
	public static String getIp() {
		return ipPort;
	}
	
	public static void setAll(SharedPreferences prefs) {		 
		Prefs.useVolButtons = prefs.getBoolean(useVolButtonsKey, true);
		Prefs.closePlaylist = prefs.getBoolean(closePlaylistKey, false);
		Prefs.updateInterval = Integer.parseInt(prefs.getString(updateIntervalKey, "3"));
		Prefs.volumeStep = Integer.parseInt(prefs.getString(volumeStepKey, "5"));
		Prefs.blurIntensity = Integer.parseInt(prefs.getString(blurKey, "20"));
		setNotificationPrefs(prefs);
	}
	
	public static void setNotificationPrefs(SharedPreferences prefs) {
		Prefs.setIp(prefs);
		Prefs.use3g = prefs.getBoolean(use3gKey, false);
		Prefs.showNotify = prefs.getBoolean(showNotifyKey, true);
		Prefs.notifyShowPhoto = prefs.getBoolean(notifyShowPhotoKey, true);
		Prefs.notifyUpdateInterval = Integer.parseInt(prefs.getString(notifyUpdateIntervalKey, "5"));

	}
	
} public class ConnectionMessage implements Parcelable {

    private String topLine;
    private String middleLine;
    private String bottomLine;

    public ConnectionMessage(String topLine, String middleLine, String bottomLine) {
        this.setTopLine(topLine);
        this.setMiddleLine(middleLine);
        this.setBottomLine(bottomLine);
    }


    public String getTopLine() {
        return topLine;
    }

    public void setTopLine(String topLine) {
        this.topLine = topLine;
    }

    public String getMiddleLine() {
        return middleLine;
    }

    public void setMiddleLine(String middleLine) {
        this.middleLine = middleLine;
    }

    public String getBottomLine() {
        return bottomLine;
    }

    public void setBottomLine(String bottomLine) {
        this.bottomLine = bottomLine;
    }

    protected ConnectionMessage(Parcel in) {
        topLine = in.readString();
        middleLine = in.readString();
        bottomLine = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(topLine);
        dest.writeString(middleLine);
        dest.writeString(bottomLine);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<ConnectionMessage> CREATOR = new Parcelable.Creator<ConnectionMessage>() {
        @Override
        public ConnectionMessage createFromParcel(Parcel in) {
            return new ConnectionMessage(in);
        }

        @Override
        public ConnectionMessage[] newArray(int size) {
            return new ConnectionMessage[size];
        }
    };
} public abstract class ConnectorUpdateCallback extends ResultReceiver {

    public static final int RC_DATA_UPDATED = 0;
    public static final int RC_DATA_UNAVAILABLE = 1;
    public static final int RC_PLAYING_STATE_CHANGED = 2;
    public static final int RC_PLAYLIST_UPDATED = 3;

    public static final String BUNDLE_SONG = "SONG";
    public static final String BUNDLE_STATE = "STATE";
    public static final String BUNDLE_ERROR_CODE = "ERROR_CODE";
    public static final String BUNDLE_CONNECTION_MESSAGE = "CONNECTION_MESSAGE";

    public ConnectorUpdateCallback() {
        super(new Handler());
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);
        switch (resultCode) {
            case RC_DATA_UPDATED:
                onDataUpdated((Song)resultData.getParcelable(BUNDLE_SONG),
                        PlayingState.values()[resultData.getInt(BUNDLE_STATE)]);
                break;
            case RC_DATA_UNAVAILABLE:
                onDataUnavailable(resultData.getInt(BUNDLE_ERROR_CODE),
                        (ConnectionMessage)resultData.getParcelable(BUNDLE_CONNECTION_MESSAGE));
                break;
            case RC_PLAYING_STATE_CHANGED:
                onPlayingStateChanged(PlayingState.values()[resultData.getInt(BUNDLE_STATE)]);
                break;

        }
    }

    /**
     *  Called in update loop on successfull data update.
     *  Also called in case of
     * @param song Currently playing song. Can be null
     * @param state Playback state
     */
    public abstract void onDataUpdated(Song song, PlayingState state);

    /**
     * Called in update loop in case of error
     * @param errorCode code describing error
     * @param connectionMessage
     */
    public abstract void onDataUnavailable(int errorCode, ConnectionMessage connectionMessage);

    /**
     * Called if playing state has changed
      * @param state new playing state
     */
    public abstract void onPlayingStateChanged(PlayingState state);

} public enum AmarokCommand implements Command {

    NEXT("/cmdNext/"), PREV("/cmdPrev/"), PLAY("/cmdPlay/"), PAUSE("/cmdPause/"),
    PLAY_PAUSE("/cmdPlayPause/"), STOP("/cmdStop/"), VOL_UP("/cmdVolumeUp/"),
    VOL_DOWN("/cmdVolumeDown/"), MUTE("/cmdMute/"), PLAY_BY_INDEX("/cmdPlayByIndex/"),
    REMOVE_BY_INDEX("/cmdRemoveByIndex/"), SET_POSITION("/cmdSetPosition/"),
    COLLECTION_ENQUEUE("/cmdCollectionEnqueue/"), PLAYLIST_CLEAR("/cmdPlaylistClear/");

    private String mCommand;
    private String mParameter = "";
    private CommandCallback mCallback;

    private AmarokCommand(String command) {
        this.mCommand = command;
    }

    @Override
    public String getCommand() {
        return mCommand;
    }

    public Command param(String param) {
        if (param != null) mParameter = param;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void execute() {
        execute("");
    }

    public void execute(String params) {
        String url = Prefs.getIp();
        if (TextUtils.isEmpty(url)) return;

        OkHttpClient client = new OkHttpClient();
        String com = url + mCommand + mParameter + params;
        Request request = new Request.Builder().url(com).build();
        Log.e("", "COMMAND: " + com);
        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Request request, IOException e) {
                runCallbackInMainThread();
                Log.e("", request.toString());
            }
            @Override public void onResponse(Response response) throws IOException {
                runCallbackInMainThread();
                Log.e("", response.toString());
            }
        });
    }

    private void runCallbackInMainThread() {
        if (mCallback != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    mCallback.onResponse();
                }
            });
        }
    }

    @Override
    public Command withCallback(CommandCallback callback) {
        mCallback = callback;
        return this;
    }
} public abstract class PlaylistUpdateCallback extends ResultReceiver {

    public static final int RC_PLAYLIST_UPDATED = 0;

    public static final String DATA_PLAYLIST = "PLAYLIST";

    public PlaylistUpdateCallback() {
        super(new Handler());
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);

        if (resultCode == RC_PLAYLIST_UPDATED) {
            onPlaylistReceived(resultData.<Song>getParcelableArrayList(DATA_PLAYLIST));
        }
    }

    public abstract void onPlaylistReceived(ArrayList<Song> list);
} public class Storage {

    public static boolean getBoolValue(String key) {
        SharedPreferences prefs = getDataPrefs();
        return prefs.getBoolean(key, false);
    }

    public static void storeBoolValue(String key, boolean value) {
        SharedPreferences prefs = getDataPrefs();
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    private static SharedPreferences getDataPrefs() {
        return App.getInstance().getSharedPreferences("PREFS", Context.MODE_PRIVATE);
    }

} public class CacheCoversTask extends AsyncTask<Song, Void, Void> {

    private Context context;
    private static boolean inProgressOrDone;

    private CacheCoversTask() {
        context = App.getInstance();
    }

    public static void runTask(Song... songs) {
        if(inProgressOrDone) return;
        inProgressOrDone = true;
        new CacheCoversTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, songs);
    }

    protected String getCover = "/getCover/";

    @Override
    protected Void doInBackground(Song... songsList) {
        String prevAlbum = "";
        for(Song song: songsList) {
            try {
                if(prevAlbum.equals(song.getAlbum()) || (MediaHelper.readFromCache(
                        song.getArtist() + song.getAlbum() + "_mini", context) != null))
                { continue; }

                prevAlbum = song.getAlbum();

                MediaHelper.downloadBitmap(Prefs.getIp() + getCover + song.getId() + "/"
                                + context.getResources().getInteger(R.integer.playlist_cover_dimen),
                        song.getArtist() + song.getAlbum() + "_mini", context);
            } catch (NullPointerException ex) { /* Don't worry, be happy. */ }
        }
        return null;
    }

    @Override
    protected void onCancelled() {
        inProgressOrDone = false;
    }
} public abstract class Constants {

    public static final String COMM_START = "start_app";
    public static final String COMM_FORCE_REFRESH = "force_refresh";
    public static final String COMM_CLEAR_NOTIFICATION = "clear_notification";

    public static final String COMM_PLAYER_DISCONNECTED = "player_disconnected";

    public static final String URL_GITHUB = "https://github.com/MatejVancik/amaroKontrol";
    
    
    public static final String CONST_UPDATE_SCRIPT = "update_script_message";

    public static final String COMM_PATH_SONG = "/song";
    public static final String COMM_PATH_STATE = "/state";
    public static final String COMM_PATH_UNAVAILABLE = "/unavailable";
    public static final String COMM_DATA_CONTENT = "content";
    public static final String COMM_DATA_COVER = "cover";
    public static final String COMM_DATA_COVER_BLURED = "blured_cover";
    public static final String COMM_DATA_STATE = "state";

    public static final String WEAR_COMMAND_PLAY = "play";
    public static final String WEAR_COMMAND_NEXT = "next";
    public static final String WEAR_COMMAND_PREV = "prev";
    public static final String WEAR_COMMAND_VOL_DOWN = "vol_down";
    public static final String WEAR_COMMAND_VOL_UP = "vol_up";

} public enum PlayingState {

    PLAYING, PAUSE, NOTPLAYING, DOWN;

    public static PlayingState state = DOWN;

} public class Song implements Parcelable {

    private String title;
    private String artist;
    private String album;
    private int id;
    private Bitmap cover;
    private Bitmap bluredCover;
    private boolean isNewAlbum = false;
    private String lyrics;
    private int length;
    private int position;

    public Song(String title, String artist, String album){
        this.title = title;
        this.artist = artist;
        this.album = album;
    }

    public Song(String title, String artist, String album, Bitmap cover){
        this(title, artist, album);
        this.cover = cover;
    }

    public Song(int id, String title, String artist, String album) {
        this(title, artist, album);
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        Song obj = (Song)o;
        if(obj == null) return false;
        return title.equals(obj.getTitle()) && artist.equals(obj.getArtist()) && album.equals(obj.getAlbum());
    }

    @Override
    public String toString() {
        return title+artist+album;
    }

    public void setNewAlbum(boolean newAlbum) {
        isNewAlbum = newAlbum;
    }

    public boolean isNewAlbum() {
        return isNewAlbum;
    }

    public boolean sameSong(Song song) {
        return title.equals(song.title) && artist.equals(song.artist);
    }

    public boolean sameSong(String title, String artist, String album) {
        return this.title.equals(title) && this.artist.equals(artist) && this.album.equals(album);
    }

    public boolean onSameAlbum(Song song){
        return song.album.equals(album) && song.artist.equals(artist);
    }

    public boolean onSameAlbum(String artist, String album) {
        return this.artist.equals(artist) && this.album.equals(album);
    }

    public String getTitle() {
        return title;
    }

    public String getArtist() {
        return artist;
    }

    public String getAlbum() {
        return album;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public void setAlbum(String album) {
        this.album = album;
    }

    public void setCover(Bitmap cover) {
        this.cover = cover;
    }

    public int getId() {
        return id;
    }

    public Bitmap getCover() {
        return cover;
    }

    public void setLyrics(String lyrics) {
        this.lyrics = lyrics;
    }

    public String getLyrics() {
        return lyrics;
    }

    public Bitmap getBlured() {
        return bluredCover;
    }

    public void setBluredCover(Bitmap blured) {
        bluredCover = blured;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    protected Song(Parcel in) {
        title = in.readString();
        artist = in.readString();
        album = in.readString();
        id = in.readInt();
        cover = (Bitmap) in.readValue(Bitmap.class.getClassLoader());
        bluredCover = (Bitmap) in.readValue(Bitmap.class.getClassLoader());
        isNewAlbum = in.readByte() != 0x00;
        lyrics = in.readString();
        length = in.readInt();
        position = in.readInt();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(artist);
        dest.writeString(album);
        dest.writeInt(id);
        dest.writeValue(cover);
        dest.writeValue(bluredCover);
        dest.writeByte((byte) (isNewAlbum ? 0x01 : 0x00));
        dest.writeString(lyrics);
        dest.writeInt(length);
        dest.writeInt(position);
    }

    public static final Parcelable.Creator<Song> CREATOR = new Parcelable.Creator<Song>() {
        @Override
        public Song createFromParcel(Parcel in) {
            return new Song(in);
        }

        @Override
        public Song[] newArray(int size) {
            return new Song[size];
        }
    };


} public class BaseFragment extends Fragment implements SingleContentFragmentActivity.OnBackPressedListener {

    private Bundle mBundle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setRetainInstance(true);
    }

    @Override
    public void onBack() {
        // do not force fragments to implement this
    }

    public void setBundle(Bundle bundle) {
        mBundle = bundle;
    }

    protected Bundle getBundle() {
        return mBundle;
    }

}
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.fortysevendeg.swipelistview.BaseSwipeListViewListener;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.mv2studio.amarok.kontrol.App;
import com.mv2studio.amarok.kontrol.PlaylistAdapter;
import com.mv2studio.amarok.kontrol.Prefs;
import com.mv2studio.amarok.kontrol.R;
import com.mv2studio.amarok.kontrol.communication.ConnectionMessage;
import com.mv2studio.amarok.kontrol.communication.ConnectorUpdateCallback;
import com.mv2studio.amarok.kontrol.communication.amarok.AmarokCommand;
import com.mv2studio.amarok.kontrol.communication.amarok.PlaylistUpdateCallback;
import com.mv2studio.amarok.kontrol.helpers.Storage;
import com.mv2studio.amarok.kontrol.photosbrowser.CacheCoversTask;
import com.mv2studio.amarok.kontrol.shared.Constants;
import com.mv2studio.amarok.kontrol.shared.PlayingState;
import com.mv2studio.amarok.kontrol.shared.model.Song;
import com.mv2studio.amarok.kontrol.ui.Fragment.BaseFragment;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.Stack;
			startActivity(Intent.createChooser(intent, "Send Email"));
		}
		return false;
	}

    public void recoverBackground() {
        imageViewAnimatedChange(sBackground);
    }

	@SuppressLint("NewApi")
	public void imageViewAnimatedChange(final Bitmap new_image) {
		final ImageView v1 = (ImageView)findViewById(R.id.main_background1);
		final ImageView v2 = (ImageView)findViewById(R.id.main_background2);

		Window window = getWindow();
		window.setBackgroundDrawable(new BitmapDrawable(getResources(), new_image));

	    final Animation anim_out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
	    final Animation anim_in  = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);

	    if(v1.getVisibility() == View.INVISIBLE) {
	    	v2.setVisibility(View.INVISIBLE);
	    	v2.startAnimation(anim_out);
	    	anim_out.setAnimationListener(new AnimationListener() {
	    		@Override public void onAnimationStart(Animation animation) {}
	            @Override public void onAnimationRepeat(Animation animation) {}
	            @Override public void onAnimationEnd(Animation animation) {v2.setImageBitmap(null);}
			});
	    	v1.setVisibility(View.VISIBLE);
	    	v1.setImageBitmap(new_image);
	    	v1.startAnimation(anim_in);
	    } else {
	    	v1.setVisibility(View.INVISIBLE);
	    	v1.startAnimation(anim_out);
	    	anim_out.setAnimationListener(new AnimationListener() {
	    		@Override public void onAnimationStart(Animation animation) {}
	            @Override public void onAnimationRepeat(Animation animation) {}
	            @Override public void onAnimationEnd(Animation animation) {v1.setImageBitmap(null);}
			});
	    	v2.setVisibility(View.VISIBLE);
	    	v2.setImageBitmap(new_image);
	    	v2.startAnimation(anim_in);
	    }
	    
	}
	

	public void showActionBarInfo(AsyncTask task) {
		sActionBarTask = task;
		Animation animation = new TranslateAnimation(0 , 0, -mActionBarStatusLayout.getHeight(), 0);
		animation.setDuration(500);
		mActionBarStatusLayout.startAnimation(animation);
		mActionBarStatusLayout.setVisibility(View.VISIBLE);
		mActionBarStatusButton.setVisibility(View.VISIBLE);
	}
	
	public void hideActionBarInfo(AsyncTask task) {
		if(sActionBarTask != task) return;
		if(mActionBarStatusLayout.getVisibility() == View.INVISIBLE) return;
		mActionBarStatusLayout.startAnimation(createHideAnimationForActionBarItem(mActionBarStatusLayout));
		sActionBarTask = null;
	}
	
	private Animation createHideAnimationForActionBarItem(final View view) {
		Animation animation = new TranslateAnimation(0 , 0, 0, -view.getHeight());
		animation.setDuration(500);
		animation.setAnimationListener(new AnimationListener() {
			@Override public void onAnimationStart(Animation animation) { }
			@Override public void onAnimationRepeat(Animation animation) { }
			@Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.GONE); }
		});
		return animation;
	}
	
	public void setActionBarButtonInvisible(AsyncTask task) {
		if(sActionBarTask != task) return;
		mActionBarStatusButton.setVisibility(View.INVISIBLE);
	}
	
	public void setActionBarInfoText(String text, AsyncTask task) {
		if(sActionBarTask != task) return;
		mActionBarStatusText.setText(text);
	}
	
	public void setActionBarInfoCancelTask(final AsyncTask task) {
		mActionBarStatusButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                task.cancel(true);
            }
        });
	}
	
    private void setSearchButtonVisibile(boolean visible) {
        if (visible) {
            Animation animation = new TranslateAnimation(0 , 0, -mActionBarSearch.getHeight(), 0);
            animation.setDuration(500);
            mActionBarSearch.startAnimation(animation);
            mActionBarSearch.setVisibility(View.VISIBLE);
        } else {
            mActionBarSearch.startAnimation(createHideAnimationForActionBarItem(mActionBarSearch));
        }
    }

	public void updatePlaylistItemsPlayIcon() {
		try {
			int currentSongIndex = mPlaylistAdapter.getIndexOfCurrentSong();
			if(currentSongIndex > -1) {
				int firstVisible = mPlayListView.getFirstVisiblePosition();
				int lastVisible = mPlayListView.getLastVisiblePosition();
				int count = lastVisible - firstVisible;
				for(int i = 0; i < count; i++) {
					ImageView playingIcon = (ImageView) mPlayListView.getChildAt(i).findViewById(R.id.listSongPlayingIcon);
					playingIcon.setVisibility((currentSongIndex - firstVisible == i) ? View.VISIBLE : View.GONE);
				}				
			}
		} catch (NullPointerException ex) {}
	}
	
	public void refreshPlaylist() {
        App.getInstance().updatePlaylist(new PlaylistUpdateCallback() {