var hkh = hkh || {};
hkh.MyHomesKeeper = hkh.MyHomesKeeper || {};

hkh.MyHomesKeeper.instance = function (config)
{
	this.ui = new hkh.MyHomesKeeper.ui(config);
	
	this.core = this.ui.core;
}

hkh.MyHomesKeeper.core = function (config)
{
	this.config = {
		listeners: {}
	};
	
	var me = this;
	this.clip = new ClipControl(config.member_id);
	this.clipped = {
		items: {},
		props: { ids:[], infos:{}, clip_item_ids:{} }
	};
	
	this.is_init_fetch = true;
	
	this.init = function (config)
	{
		$.extend(true, this.config, config);
		
		this.is_init_fetch = true;
		
		this.clip.fetchClipItems($.proxy(this.onClipItemsFetched, this), 'property', 'rent,buy');
	}
	
	this.initClippedProps = function (is_init_clip_ids)
	{
		this.clipped.props.ids = [];
		this.clipped.props.infos = {};
		
		if (is_init_clip_ids)
			this.clipped.props.clip_item_ids = {};
	}
	
	this.addListener = function (listener_name, listener)
	{
		if (!this.config.listeners[listener_name])
		{
			this.config.listeners[listener_name] = [];
		}
			
		this.config.listeners[listener_name].push(listener);
	}
	this.fireListener = function (listener_name, args)
	{
		if (this.config.listeners[listener_name])
			$.each(this.config.listeners[listener_name], function () {
				this(args);
			});
	}
	
	this.checkItems = function (info)
	{
		this.clip.checkClipItems($.proxy(this.onItemsChecked, this), info.item_cat, info.item_ids, info.item_type);
	};
	this.onItemsChecked = function (resp, req_id)
	{
		if (resp == null)
			return false;
			
		var resp = eval('('+resp+')');
		
		this.fireListener('onItemsChecked', resp);
	};
	
	this.clipItem = function (info)
	{
		this.clip.addClipItem($.proxy(this.onItemClipped, this), info.item_cat, info.item_id, info.item_type);
	};
	
	this.onItemClipped = function (resp, req_id)
	{
		if (resp == null)
			return false;
			
		var resp = eval('('+resp+')');
		
		this.fireListener('onItemClipped', resp);
	};
	
	this.unclipItem = function (clip_item_id)
	{
		this.clip.removeClipItem($.proxy(this.onItemUnclipped, this), clip_item_id);
	}
	this.onItemUnclipped = function (resp, req_id)
	{
		if (resp == null)
			return false;
		
		var resp = eval('('+resp+')');
		
		this.fireListener('onItemUnclipped', resp);
	}
	
	
	this.onClipItemsFetched = function (resp, req_id)
	{
		if (resp == null)
			return false;
		
		var resp = eval('('+resp+')');
		var items = resp.items;
		for (var i=0; i < items.length; i++)
		{
			var item = items[i];
			
			this.clipped.items[item.clip_item_id] = item;
			
			if (item.namespace == 'hkh.item.property')
			{
				this.clipped.props.ids.push(item.item_id);
				this.clipped.props.clip_item_ids[item.item_id] = item.clip_item_id;
			}
		}
		
		this.fireListener('onClipItemsFetched', resp);
		
		this.fetchListingInfos();
	}
	
	this.fetchListingInfos = function ()
	{
		var store = this.clipped;
		
		var url = '/'+LANG+'/get_clipped_props.php';
		var data = {
			pro_ids: store.props.ids.join(','),
			usage: 'myhomes_keeper'
		}
		
		$.post(url, data, $.proxy(this.onListingInfosFetched, this), 'json');
	}
	this.onListingInfosFetched = function (resp)
	{
		this.initClippedProps();
		
		if (resp != null)
		{
			$.each(resp.items, function (i, v) {
				v.building_name = decodeURIComponent(v.building_name);
				v.district_name = decodeURIComponent(v.district_name);
				v.rental_price = decodeURIComponent(v.rental_price);
				
				me.clipped.props.ids.push(v.pro_id);
				me.clipped.props.infos[v.pro_id] = v;
			});	
		}
			
		this.fireListener('onListingInfosFetched', resp);
			
		this.is_init_fetch = false;
	}
	
	this.init(config);
}

hkh.MyHomesKeeper.ui = function (config)
{
	var me = this;
	this.core = null;
	this.container = { main:null, item:null };
	this.config = {
		img_dir:'',
		active_color: '#FBB829',
		main_min_height: 400,
		ui_top_height: 46,
		ui_btm_height: 41
	};
	
	this.init = function (config)
	{
		$.extend(true, this.config, config);
		
		var core_config = $.extend(true, {}, this.config);
		// core_config.listeners = {
			// 'onListingInfosFetched': $.proxy(this.onListingInfosFetched, this),
			// 'onClipItemRemoved': $.proxy(this.onClipItemRemoved, this),
			// 'onItemClipped': $.proxy(this.onItemClipped, this)
		// };
		
		this.core = new hkh.MyHomesKeeper.core(core_config);
		this.core.addListener('onListingInfosFetched', $.proxy(this.onListingInfosFetched, this));
		this.core.addListener('onItemUnclipped', $.proxy(this.onItemUnclipped, this));
		this.core.addListener('onItemClipped', $.proxy(this.onItemClipped, this));
		
		this.container.main = $('#'+this.config.container);
		this.container.item = $('.keeper-content', this.container.main);
		this.container.added_bubble = $('#myhomes-keeper-added-bubble');
		
		this.container.main.find('.keeper-close-btn').click(function () {
			me.hide();
		});
		
		this.container.added_bubble.click(function () {
			me.container.added_bubble.hide();
			me.show();
		})
		
		this.determineHeight();
		this.initShowHide();
			
		this.initTpl();
		
		
	}
	
	this.reinitScrollPane = function ()
	{
		if (this.scroll_pane)
		{
			this.scroll_pane.reinitialise();
		}
	}
	
	this.initShowHide = function ()
	{
		var on_off = getCookie('mhk_oo');
		if (on_off == '1')
			this.show(false);
		else
			this.hide();
	}
	this.show = function (is_enable_effect)
	{
		if (is_enable_effect == false)
		{
			this.container.main.show();
		}
		else
		{
			// this.container.main.animate({ height: 'show' }, 1000, 'easeOutBounce');
			this.container.main.animate({ height: 'show', bottom:'42px' }, 800, 'easeInOutBack');
			// this.container.main.animate({ height: 'show' }, 800, 'easeInOutCirc');
			// this.container.main.animate({ height: 'show' }, 800, 'easeInOutQuint');
		}
		setCookie('mhk_oo', 1);
		
		this.reinitScrollPane();
	}
	this.hide = function ()
	{
		// this.container.main.animate({ height: 'hide' }, 1000, 'easeOutBounce');
		this.container.main.animate({ height: 'hide', bottom:'30px'}, 800, 'easeInOutBack');
		// this.container.main.animate({ height: 'hide' }, 800, 'easeInOutCirc');
		// this.container.main.animate({ height: 'hide' }, 800, 'easeInOutQuint');
		setCookie('mhk_oo', 0);
	}
	this.toggle = function ()
	{
		if (this.container.main.is(':visible'))
			this.hide();
		else
		{
			this.container.added_bubble.hide();
			this.show();
		}
	}
	this.isShowed = function ()
	{
		return this.container.main.is(':visible');
	}
	
	this.showAddedBubble = function ()
	{
		this.container.added_bubble.fadeIn(2000, function () {
			me.container.added_bubble.fadeOut(3000);
		});
	}
	
	
	this.onUiItemAdded = function ()
	{
		if (!this.isShowed())
		{
			this.showAddedBubble();
		}
	}
	
	this.toggleNoItemsMsg = function ()
	{
		if ($.trim(this.container.item.text()) == '')
			this.container.item.append('<div class="no-items-msg" style="font-weight:bold; text-align:center; padding:50px;">'+__["no-items-saved"]+'</div>').fadeIn('slow');
		else
			this.container.item.find('.no-items-msg').fadeOut(800, function () {
				$(this).remove();
			});
	};
	
	this.determineHeight = function ()
	{
		var top_spacer = 230;
		var viewport_h  = $(window).height();
		
		var main_h = viewport_h - top_spacer;
		if (main_h < this.config.main_min_height)
		{
			main_h = this.config.main_min_height;
		}
		var content_h = main_h - this.config.ui_top_height - this.config.ui_btm_height;
		
		this.container.main.height(main_h);
		this.container.item.height(content_h);
	}
	
	this.initTpl = function ()
	{
		var tpl = '';
		tpl += '<div class="item" id="${clip_id}">';
		tpl += '	<div class="top">';
		tpl += '		<div class="remove-item-btn"></div>';
		tpl += '	</div>';
		tpl += '	<div class="info">';
		tpl += '		<div class="photo">';
		tpl += '			<a href="${prop_link}"><img width="60" height="45" src="${photo_src}" /></a>';
		tpl += '		</div>';
		tpl += '		<div class="detail">';
		tpl += '			<div class="prop-name"><a href="${prop_link}">${prop_name}</a></div>';
		tpl += '			<div>${size}</div>';
		tpl += '			<div class="bed-bath">';
		tpl += '				{{if bed}}<div class="bed">${__bed}: ${bed}{{if ensuite}} <span>(${ensuite} ${__ensuite})</span>{{/if}}</div>{{/if}}';
		tpl += '				{{if bath}}<div class="bath">${__bath}: ${bath}</div>{{/if}}';
		tpl += '				<div class="clear-fix"></div>';
		tpl += '			</div>';
		tpl += '			{{html rental_price}}';
		tpl += '		</div>';
		tpl += '		<div class="clear-fix"></div>';
		tpl += '	</div>';
		tpl += '	<div class="bottom"></div>';
		tpl += '</div>';
		$.template('myhomes-keeper-item', tpl);
	}
	
	this.formItemContainerId = function (clip_item_id)
	{
		return this.config.container+'-item-'+clip_item_id;
	}
	this.getClipItemIdFromItemContainerId = function (id)
	{
		return id.replace(this.config.container+'-item-', '');
	}
	
	this.onItemClipped = function (resp)
	{
		this.addClippedProp(resp);
	};
	
	this.onListingInfosFetched = function ()
	{
		var tpl_data = [];
		$.each(this.core.clipped.props.ids, function (i, prop_id) {
			var v = me.core.clipped.props.infos[prop_id];
			if (v)
			{
				var clip_item_id = me.core.clipped.props.clip_item_ids[prop_id];
				var clip_id = me.formItemContainerId(clip_item_id);
				
				tpl_data.push({
					clip_id: clip_id,
					prop_name: v.building_name,
					photo_src: v.cover_photo,
					prop_link: v.link,
					size: v.size,
					rental_price: v.rental_price,
					bed: v.bed,
					ensuite: v.ensuite,
					bath: v.bath,
					
					__bed: __['bed'],
					__bath: __['bath'],
					__ensuite: __['ensuite-abbr']
				});
			}
		});
		if (this.core.is_init_fetch)
		{
			$.tmpl('myhomes-keeper-item', tpl_data).prependTo(this.container.item);
			
			this.container.original_item = this.container.item;
			
			this.container.item.jScrollPane();
			this.container.item = this.container.main.find('.jspPane');
			
			this.scroll_pane = this.container.original_item.data('jsp');
			
			var clicked_item = getCookie('mhk_ci');
			if (typeof clicked_item != 'undefined' && clicked_item != '0' && clicked_item != '')
			{
				var ele = $('#'+clicked_item);
				this.scroll_pane.scrollToElement(ele, true);
				
				setCookie('mhk_ci', 0);
			}
			
			// remove clipped item
			this.container.item.find('.item .top .remove-item-btn').live('click', function () {
				me.unclipItem($(this).parents('.item'));
			});
		}
		else
		{
			$.tmpl('myhomes-keeper-item', tpl_data).prependTo(this.container.item).hide().fadeIn(3000);
			
			this.scroll_pane.reinitialise();
			this.scroll_pane.scrollToY(0);
		}
		this.toggleNoItemsMsg();
		
		// track clicked prop
		this.container.item.find('.item .detail a').click(function () {
			setCookie('mhk_ci', $(this).parents('.item').attr('id'));
		});
		
		// mouseover item div
		this.container.item.find('.item').hover(
				function ()
				{
					$('.top', this).addClass('top-mouseover');
					$('.info', this).addClass('info-mouseover');
					$('.bottom', this).addClass('bottom-mouseover');
				},
				function ()
				{
					$('.top', this).removeClass('top-mouseover');
					$('.info', this).removeClass('info-mouseover');
					$('.bottom', this).removeClass('bottom-mouseover');
				}
		);
	}
	
	this.unclipItem = function (ele)
	{
		// if (confirm(__["is-del-this-prop"]))
		// {
			var clip_item_id = this.getClipItemIdFromItemContainerId(ele.attr('id'));
			this.core.unclipItem(clip_item_id);
		// }
	}
	this.onItemUnclipped = function (resp)
	{
		if (resp == null)
			return;
		
		if (resp.result == 1)
		{
			this.removeClippedProp(resp);
		}
	}
	
	this.addClippedProp = function (resp)
	{
		if (resp.namespace != 'hkh.item.property')
			return false;
		
		this.core.initClippedProps(true);
		
		this.core.clipped.props.clip_item_ids[resp.item_id] = resp.clip_item_id;
		
		this.core.clipped.props.ids.push(resp.item_id);
		this.core.fetchListingInfos();
		
		this.onUiItemAdded();
	}
	
	this.removeClippedProps = function (resp)
	{
		if (resp.result == 1)
		{
			if (resp.items && resp.items.length)
			{
				$.each(resp.items, function () {
					me.removeClippedProp(this);
				});
			}
			else
			{
				me.removeClippedProp(resp);
			}
		}
	};
	
	this.removeClippedProp = function (resp)
	{
		var ele_id = me.formItemContainerId(resp.clip_item_id);
		var ele = this.container.item.find('#'+ele_id);
		if (ele.is(':visible'))
		{
			ele.fadeOut(800, function () {
				me.reinitScrollPane();
				ele.remove();
				me.toggleNoItemsMsg();
			});
		}
		else
		{
			ele.remove();
			this.toggleNoItemsMsg();
		}
	}
	
	this.init(config);
};

