/**
 *
 * @param {Object} local_conf
 */
jQuery.fn.follower = function (local_conf) {
	//
    var conf = {};

	conf.ajaxCheckUrl = null;
	conf.ajaxTokenUrl = null;

	conf.states = {yes: true, no: true};
	conf.defaultState = 'no';

	conf.seeMoreUrl = '';
	conf.recommendLink = '';

	conf.stateCheckBefore = function () {};
	conf.stateCheckAfter = function (data) {};

	conf.stateReloadBefore = function (state, data) {};
	conf.stateReloadAfter = function (state, data) {};

	conf.voteSubmitBefore = function () {};
	conf.voteSubmitAfter = function (data) {};

	//
	var standard = {};

	standard.states = {
		no: {
			checkResult: 'no',
			ajaxVoteUrl: null,
			linkVoteText: '',
			hoverLinkVoteText: '',
			boxCssClass: 'stateNo',
			hoverBoxCssClass: 'stateNoHover',
			successNextState: 'yes',
			failureNextState: 'no'},
		yes: {
			checkResult: 'yes',
			ajaxVoteUrl: null,
			linkVoteText: '',
			hoverLinkVoteText: '',
			boxCssClass: 'stateYes',
			hoverBoxCssClass: 'stateYesHover',
			successNextState: 'no',
			failureNextState: 'yes'}};

	//
	var boxJQ = jQuery(this);

	var linkVoteJQ = null;
	var summaryJQ = null;
	var followerListJQ = null;
	var seeMoreJQ = null;
	var recommendJQ = null;

	var followersCount = null;
	
	var currentState = conf.defaultState;
	
	/**
	 * 
	 * @param {Object} local_conf
	 */
    var init = function (local_conf) {
		conf = jQuery.extend(conf, local_conf);

		//
		for(var state in conf.states) {
			if(typeof(standard.states[state]) !== 'undefined') {
				if(typeof(conf.states[state]) === 'object' || conf.states[state] === true) {
					conf.states[state] = jQuery.extend(true, standard.states[state], conf.states[state]);
				}
				else {
					delete conf.states[state];
				}
			}
		}

		//
        boxJQ.find('.link').addClass('a');

		linkVoteJQ = boxJQ.find('.voteLink .a')
			.mouseover(function () {
				linkVoteJQ.contents()
					.text(conf.states[currentState].hoverLinkVoteText);
				
				boxJQ
					.removeClass(conf.states[currentState].boxCssClass)
					.addClass(conf.states[currentState].hoverBoxCssClass);
			})
			.mouseout(function () {
				linkVoteJQ.contents()
					.text(conf.states[currentState].linkVoteText);

				boxJQ
					.removeClass(conf.states[currentState].hoverBoxCssClass)
					.addClass(conf.states[currentState].boxCssClass);
			})
			.click(function () {
				voteSubmit();
			});

		//
        summaryJQ = jQuery('<div />')
            .addClass('summary')
            .appendTo(boxJQ.find('.boxBody'));

        followerListJQ = jQuery('<div />')
            .addClass('followerList')
            .appendTo(boxJQ.find('.boxBody'));

        seeMoreJQ = jQuery('<div />')
            .addClass('seeMore')
            .appendTo(boxJQ.find('.boxBody'));

        recommendJQ = jQuery('<div />')
            .addClass('recommend')
            .appendTo(boxJQ.find('.boxBody'));

		//
		stateCheck();
    };

	/**
	 * 
	 */
	var stateCheck = function () {
		//
		conf.stateCheckBefore();
		
		//
        jQuery.ajax({
            type: 'GET',
            url: conf.ajaxCheckUrl,
            dataType: 'json',
            success: function (data, textStatus) {
				for(var s in conf.states) {
					if(conf.states[s].checkResult === data.result) {
						stateReload(s, data)
						break;
					}
				}

				conf.stateCheckAfter(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
			}});
	}

	/**
	 * 
	 * @param {String} state
	 */
	var stateReload = function (state, data) {
		//
		conf.stateReloadBefore(state, data);
		
		//		
		linkVoteJQ.contents()
			.text(conf.states[state].linkVoteText);

		boxJQ
			.removeClass(conf.states[currentState].boxCssClass)
			.removeClass(conf.states[currentState].hoverBoxCssClass)
			.addClass(conf.states[state].boxCssClass);

		//
		var displayfollowerList = false;
		var displaySeeMore = false;
		var displayRecommend = false;
		
		switch(true) {
			case state === 'no' && data.userList.totalItemsCount == 0:
				summaryJQ.html('Jeszcze nikt tego nie polubił. <strong>Zrób to Ty!</strong>');

				break;

			case state === 'yes' && data.userList.totalItemsCount == 1:
				summaryJQ.html('<strong>Tylko Ty</strong> to lubisz.');

				displayRecommend = true;

				break;
			
			case state === 'yes' && data.userList.totalItemsCount > 1:
				summaryJQ.html('<strong>Ty</strong> i <a href="' + conf.seeMoreUrl + '" class="userListLink"><span class="count">' + (data.userList.totalItemsCount - 1) + '</span> ' + (data.userList.totalItemsCount == 2 ? 'użytkownik' : 'użytkowników') + '</a> to lubi.');

				displayfollowerList = true;
				displaySeeMore = true;

				break;

			case state === 'no' && data.userList.totalItemsCount > 0:
				summaryJQ.html('<a href="' + conf.seeMoreUrl + '" class="userListLink"><span class="count">' + data.userList.totalItemsCount + '</span> ' + (data.userList.totalItemsCount == 1 ? 'użytkownik' : 'użytkowników') + '</a> to lubi.');

				displayfollowerList = true;
				displaySeeMore = true;

				break;
		}

		followerListJQ.empty();
		if(displayfollowerList) {
			var ulJQ = jQuery('<ul />').appendTo(followerListJQ);
			
			for(var i in data.userList.items) {
				jQuery('<li />')
					.html('<a href="/wizytowka-' + data.userList.items[i].nick + '"><img src="' + data.userList.items[i].imageUrl + '" alt="' + data.userList.items[i].nick + '"></a>')
					.appendTo(ulJQ);
			}
		}
		
		seeMoreJQ.empty();
		if(displaySeeMore) {
			seeMoreJQ.html('<a href="' + conf.seeMoreUrl + '" class="userListLink"><span>Więcej</span></a>');
		}
		
		recommendJQ.empty();
		if(displayRecommend) {
			recommendJQ.html('<a href="' + conf.recommendLink + '" class="recommendLink">Powiadom znajomych</a> o ciekawym materiale!');
		}

		//
		currentState = state;
		
		conf.stateReloadAfter(state, data);
	}

	/**
	 * 
	 */
	var voteSubmit = function () {
		if(linkVoteJQ.queue().length > 0) {
			return;
		}
		
		//
		conf.voteSubmitBefore();
		
		//
		linkVoteJQ.queue(function () {
	        jQuery.ajax({
	            type: 'GET',
	            url: conf.ajaxTokenUrl,
	            dataType: 'json',
	            success: function (data, textStatus) {
					var token = data.result;
					
			        jQuery.ajax({
			            type: 'POST',
			            url: conf.states[currentState].ajaxVoteUrl,
			            data: {token: token},
			            dataType: 'json',
			            success: function (data, textStatus) {
							stateReload(data.result == 1 ? conf.states[currentState].successNextState : conf.states[currentState].failureNextState, data);
							linkVoteJQ.dequeue();

							conf.voteSubmitAfter(data);
			            },
			            error: function (XMLHttpRequest, textStatus, errorThrown) {
							stateReload(conf.states[currentState].failureNextState);
							linkVoteJQ.dequeue();
						}});
	            },
	            error: function (XMLHttpRequest, textStatus, errorThrown) {
					stateReload(conf.states[currentState].failureNextState);
					linkVoteJQ.dequeue();
				}});
		});
	}

	//
    jQuery(document).ready(
        function () {
            init(local_conf);
        });
};

