/**
 * Choose region popup
 */
$(function() {
	function cookiesAreEnabled() {
		$.cookie('test_cookie', 'cookie_value', { path: '/' });
		if ($.cookie('test_cookie') == 'cookie_value') {
			$.cookie('test_cookie', null);
			return true;
		}
		return false;
	}

	if(window.location.hostname == $('#site_main_uri').val() && (window.location.pathname == '' || window.location.pathname == '/')){
		if(!$.cookie(RegionChooser.HOME_REGION_COOKIE_NAME)){
			if(cookiesAreEnabled()){

				var cookies = document.cookie.split(";");
				for(var i=0; i < cookies.length; i++) {
					var equals = cookies[i].indexOf("="),
						name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
					$.cookie($.trim(name), null, {path: '/', domain: $('#site_cookie_path').val()});
				}

				RegionChooser.getInstance().toggle();
				var $buttons = $('.popupRegions .b-title span').children();
				$('.popupRegions .b-title span').text('Выберите Ваш регион');
				$('.popupRegions .b-title span').append($buttons);
				$('.popupRegions .ico-set.ico-closeGreen:first').click(function(){RegionChooser.getInstance().save()});
			}
		}
	}

	$('ul.choose-region').click(function(){
		RegionChooser.getInstance().toggle();
		return false;
	});
});

/**
 * Constructor
 * @param config
 */
var RegionChooser = function (config){
	this.mask = null;
	this.popup = null;
	this.first_uri = null;
	this.first_column = null;
	this.second_column = null;
	this.third_column = null;
	this.statusbar = null;
	this.searchbar = null;
	this.search_results = null;
	this.tree = null;
	this.nothing_found = null;

	this.min_length = 3;

	this.cache = {};
	this.choosen = null;

	this.init();
};

/**
 * Init object
 */
RegionChooser.prototype.init = function() {
	this.mask = $('#popupCurtain');
	this.popup = $('div.popupRegions:first');
	this.first_column = this.popup.find('#column-first');
	this.second_column = this.popup.find('#column-second');
	this.third_column = this.popup.find('#column-third');
	this.statusbar = this.popup.find('#statusbar');
	this.searchbar = this.popup.find('input:first');
	this.search_results = this.popup.find('div.b-searchRegion:first').hide();
	this.tree = this.popup.find('table.tree:first').show();
	this.nothing_found = this.popup.find('div.dontSearch:first').hide();

	this.search_results.ul = this.search_results.find('ul:first');

	/*this.popup.draggable({
		handle: this.popup.find('div.b-title:first').disableSelection()
	 });*/

	this.loadData(function(data){this.renderFirst(this.first_column, data)}, {op: 'get', parent: ''});

	this.addButtonHandlers();


	this.searchbar.autocomplete({
		source: $.proxy(function (request, response) {
			this.loadData(function (data){
				if (!data.items.length) {
					this.hideAllMainBlocks();
					this.nothing_found.show();
				}else{
					this.hideAllMainBlocks();
					this.search_results.show();
				}
				response( data.items );
			}, {op: 'search', term: request.term, parent:''});
		}, this),
		search: $.proxy(function(){
			if (this.searchbar.val().length == 0) {
				this.hideAllMainBlocks();
				this.tree.show();
			}
			if (this.searchbar.val().length < this.min_length){
				return false;
			}
			this.reg = new RegExp('(' + this.searchbar.val() + ')', 'i');
		}, this),
		minLength: 0, //set here zero, but limit chars in search event (we cant show 'region tree' screen without this when user erases search input)
		appendTo: this.popup,
		open: $.proxy(function(){
			this.popup.find('ul.ui-autocomplete').hide();
		}, this)
	}).data('autocomplete')._renderItem = $.proxy(function(ul, item) {
		var title = item.title.replace(this.reg, '<span class="selectTxt">$1</span>');
		var reg = new RegExp(/\/powerSellers\//);
		if (reg.test(window.location.href)) {
			var regParams = new RegExp(/\/sort\/(.+)\/|\/page(.+)\//);
			var params_arr = regParams.exec(window.location.href);
			var params = '';
			if (params_arr != null) {
				params = params_arr[0].replace(/^\//g, '');
			}
			var regUrl =  new RegExp(/^(.*?)\/powerSellers(list\/(.*?)|(.*?))\//);
			var url = regUrl.exec(window.location.href);
			if (url != null) {
				item.href = url[0] + item.href.replace(/^\//g, '') + params;
			}
		}
		var li = jQuery('<li></li>')
					.data('item.autocomplete', item)
					.append('<a href="' + item.href + window.location.search + '">' + (item.ru_type ? item.ru_type + '. ' : '<strong>') + title + (item.ru_type ? '' : '</strong>') + (item.ru_path ? ', '+item.ru_path : '') + '</a>')
					.appendTo(this.search_results.ul);
		li.find('a')
					.bind('click',$.proxy(function(event){
										this.choosen = {href: $(event.target).attr('href')};
										this.save();
										return false;
									}, this));
		return li;
	}, this);
};

/**
 * Hide all main blocks of popup (to show other later)
 */
RegionChooser.prototype.hideAllMainBlocks = function () {
	this.nothing_found.hide();
	this.search_results.hide().ul.empty();
	this.tree.hide();
};

/**
 * Show popup
 */
RegionChooser.prototype.toggle = function () {
	this.mask.toggle();
	this.popup.toggle();
};


/**
 * Main method to load data from server
 * @param callback
 * @param params
 */
RegionChooser.prototype.loadData = function (callback, params) {
	if (this.cache[params.op+params.parent+params.term]) {
		callback.call(this, this.cache[params.op+params.parent+params.term]);
	} else {
		$.ajax({
			url: '/ajax/choose_region.php',
			context: [this, params],
			dataType: 'json',
			data: params,
			success: function (data){
				this[0].cache[this[1].op + this[1].parent+this[1].term] = data;
				callback.call(this[0], data);
			}
		});
	}
};

/**
 * Save chosen region and close pop-up
 */
RegionChooser.prototype.save = function () {
	this.popup.toggle();
	$.cookie(RegionChooser.HOME_REGION_COOKIE_NAME, this.choosen.href, {expires: 90, path: '/', domain: $('#site_cookie_path').val()});
	var reg = new RegExp(/\/powerSellers\//);
	if (reg.test(window.location.href)) {
		var regParams = new RegExp(/\/sort\/(.+)\/|\/page(.+)\//);
		var params_arr = regParams.exec(window.location.href);
		var params = '';
		if (params_arr != null) {
			params = params_arr[0].replace(/^\//g, '');
		}
		var regUrl = new RegExp(/^(.*?)\/(powerSellers(list\/(.*?)|(.*?)))\//);
		var regMoscow = new RegExp(/^http:\/\//);
		var url = regUrl.exec(window.location.href);
		if (! regMoscow.test(this.choosen.href)) {
			window.location.href = url[0] + this.choosen.href.replace(/^\//g, '') + params;
		} else {
			window.location.href = this.choosen.href + url[2] + '/' + params;
		}
	} else {
		window.location.href = this.choosen.href + window.location.search;
	}


};

/**
 * Handle click on region link
 * @param link
 */
RegionChooser.prototype.regionClick = function (link) {
	link.parent().parent().parent().find('li').removeClass('act');

	link.parent().addClass('act');
	if (link.data('city')) {
		this.choosen = link.data();
		this.statusbar.show().find('span:first').text(this.choosen.title);
		this.loadData(
			function(data){
				this.renderThird(this.third_column, data)
			},
			{op: 'get_city', parent: link.data('uri')}
		);
	} else if (link.data('href')){
		this.choosen = link.data();
		this.statusbar.show().find('span:first').text(this.choosen.title);
	}else{
		this.loadData(
			function(data){
				this.renderSecond(this.second_column, data)
			},
			{op: 'get', parent: link.data('uri')}
		);
	}
};

/**
 * Render first column of popup
 * @param parent
 * @param data
 */
RegionChooser.prototype.renderFirst = function (parent, data) {
	var ul = parent.empty().append('<ul></ul>').find(':first');
	var _this = this;

	$.each(data.items, function(i, data){
		var last = $('<a href="#">' + data.title + '</a>').appendTo(
			$('<li></li>').appendTo(ul)
	     ).data(data);

		if (data.selected){
			_this.regionClick(last);
		}
	});

	ul.find('a').click(function(){
		_this.third_column.hide();
		_this.first_uri = $(this).data('uri');
		_this.regionClick($(this));
		return false;
	});
};

/**
 * Render second column of popup
 * @param parent
 * @param data
 */
RegionChooser.prototype.renderSecond = function (parent, data) {
	parent.scrollTop(0);
	var ul = parent.empty().append('<ul></ul>').find(':first');
	var _this = this;
	var last_letter = null;

	$.each(data.items, function(i, data){
		var active = '';

		if (!data.special && data.title.substr(0, 1) != last_letter) {
			last_letter = data.title.substr(0, 1);
			$('<li class="letter"></li>').text(last_letter).appendTo(ul);
		}

		var last = $('<a href="#">' + data.title + '</a>').appendTo(
			$('<li' + active + '></li>').appendTo(ul)
	    ).data(data);

		if (data.selected){
			_this.regionClick(last);
		}
	});
	ul.find('a').click(function(){
		var link = $(this);
		if (link.data('last_level')) {
			_this.third_column.hide();
		} else {
			link.data('city', _this.first_uri == 'russia/');
		}
		_this.regionClick(link);
		return false;
	});
};

/**
 * Render third column of popup
 * @param parent
 * @param data
 */
RegionChooser.prototype.renderThird = function (parent, data) {
	if (!data) {
		return;
	}
	parent.scrollTop(0);
	var ul = parent.empty().append('<ul></ul>').find(':first');
	var _this = this;
	$.each(data.items, function(i, data) {
		var active = '';

		var last = $('<a href="#">' + data.title + '</a>').appendTo(
			$('<li' + active + '></li>').appendTo(ul)
		).data(data);

		if (data.selected) {
			_this.regionClick(last);
		}
	});
	parent.show();
	ul.find('a').click(function(){_this.regionClick($(this));return false;});
};

/**
 *  Add handlers to all buttons of popup
 */
RegionChooser.prototype.addButtonHandlers = function () {
	this.popup.find('.ico-set.ico-closeGreen:first').click($.proxy(function () {
		this.toggle();
		return false;
	}, this));

	this.popup.find('div.b-bottom .btn-a a').click($.proxy(function () {
		this.save();
		return false;
	}, this));
};

RegionChooser.HOME_REGION_COOKIE_NAME = 'region_home'; //also used in irr/index.tpl

/**
 *  Like Singleton
 */
RegionChooser.getInstance = function () {
	if (!RegionChooser.instance){
		RegionChooser.instance = new RegionChooser();
	}
	return RegionChooser.instance;
};
