/**
 * Plani javascript module
 *
 * jquery 1.11.4
 *
 * @package	Plani javascript Api Module
 * @author	kim seung beom
 * @copyright	Copyright (c) 2016, Plani, Inc.
 * @link	http://plani.co.kr
 * @since	 Version 2.0
 * @filesource
 */
$.info.style('/_res/plani_api/calendar.css');
$.info.append('/_res/jquery/plugin/jquery.mtz.monthpicker.js');

$.api['calendar'] = function( options, json ) {
	this.options = $.extend({
			selector : '#',
			year : null,
			month : null,
			netsort_x_margin : 5,
			netsort_y_margin : 8
		},
		options
	);

	this.form = $(this.options.selector).closest('form');
	this.layer = $(this.options.selector);

	this.json = null;
	this.tds = null;
	this.trs = null;
	this.items = {};

	this.__construct();
}

$.extend
(
	$.api['calendar'].prototype, {
		__construct : function() {
			var $this=this;

			new $.module['form']
			(
				$this.form, {
					before : function(module){
						$this.request();
					}
				}
			);

			$this._parse();		
			$.window
			.on
			(
				'resize', function(e){
					$('.item', $this.layer).css({'top' : 0, 'left' : 0, 'height' : 'auto' }).hide();

					if( typeof this.resizedFinished != 'undefined' ) {
						clearTimeout(this.resizedFinished);
					}

					if( $(this).width() > 780 ) {
						$this.layer.removeClass('list-mode');
						$this.tds.height($this.tds.width()*0.8 > 70 ? 70 : $this.tds.width()*0.8);
						this.resizedFinished = setTimeout
						(
							function(){	
								$this.netsort_x();
							},
							400
						);
					}else {
						$this.layer.addClass('list-mode');
						$this.tds.height('auto');
						this.resizedFinished = setTimeout
						(
							function(){	
								$this.netsort_y();
							},
							400
						);
					}
				}
			)
			.trigger('resize');

			$this.form.delegate
			(
				'.jump', 'click', function(){
					var val = $(this).attr('href');
					$this.options.year = val.substring(0, 4);
					$this.options.month = val.substring(4);

					$this.request();

					return false;
				}
			);

			$this.form.delegate
			(
				'.monthpicker', 'update', function(){
					var val = $(this).val();

					var opt = {
						selectedYear : val.substring(0, 4),
						selectedMonth : val.substring(4),
						pattern: 'yyyymm',
						monthNames: ['01','02','03','04','05','06','07','08','09','10','11','12']
					};
					
					$(this).monthpicker(opt);
					$(this).monthpicker('show');
				}
			)
			.delegate
			(
				'.monthpicker', 'change', function(){
					var val = $(this).val();
					$this.options.year = val.substring(0, 4);
					$this.options.month = val.substring(4);

					$this.request();

					return false;					
				}
			);
			
			$this.form.delegate
			(
				'.monthpicker-btn', 'click', function(){
					$('.monthpicker').trigger('update');
				}
			);	
		},
		netsort_x : function() {
			var $this=this;

			for( key in $this.items ) {
				var item = $this.items[key],
					td = item.obj.closest('td'),
					width = (item.end.offset().left-(item.start.offset().left)+item.start.width())-5

				item.obj.width(width).show();
				item.obj.css({'left' : 'auto', 'top' : 'auto', 'height' : 'auto'});

				var h = item.obj.height()+$this.options.netsort_x_margin;
				if( typeof item.depth != 'undefined' )
				{
					var target=$this.items[item.depth].obj,
						top=target.position().top+target.height()+$this.options.netsort_y_margin;

					item.obj.css('top', top);
					
					var depth_h = top+item.obj.height()+$this.options.netsort_y_margin;
					if( h < depth_h ){
						h = depth_h;
					}
				}

				//td.height(h);
				td[0].style.setProperty( 'height', (h+95)+'px', 'important' );
			}
		},
		netsort_y : function() {
			var $this=this,
				exists = {};

			for( key in $this.items ) {
				var item = $this.items[key],
					seq = item.obj.attr('url'),
					dump = null,
					dump_end = null;

				console.log(item.obj.text() + ' = ' + item.sort);

				if( seq != '' ){
					if( typeof exists[seq] != 'undefined' ){
						var dump = item,
							dump_end = exists[seq].end;

						item = exists[seq];
						item.end = dump.end;
					}else {
						exists[seq] = item;	
					}
				}

				var	td = item.obj.closest('td'),
					width = ((td.width()-70) / item.depth_count) - 10,
					left = (width * item.sort) + (10*item.sort),
					height = ((item.end.offset().top+item.end.height()) - item.start.offset().top) - 20;

				item.obj.css({'left' : left, 'width' : width}).show();

				if( item.obj.height() < height ) {
					item.obj.height(height);
				}

				var obj_bottom = item.obj.offset().top+item.obj.height(),
					end_bottom = item.end.offset().top+item.end.height();

				if( obj_bottom+10 > end_bottom ) {
					item.end.height(obj_bottom-item.end.offset().top+10);
				}

				if( dump_end != null ){
					item.end = dump_end;	
				}
			}
		},
		request : function(url) {
			var $this=this,
				param = $this.form.serialize(),
				param_tail = '&year=%s&month=%s'.sprintf($this.options.year, $this.options.month);

			if( !url ){
				url = $this.form.attr('action')
			}

			$.request
			(	
				{
					'url' : url,
					'param' : param+param_tail
				},
				function( html ){
					$this._parse(html);
					$.window.trigger('resize');
				}
			);
		},
		_parse : function( html ) {
			var $this=this,
				other_layer_selector = '.request',
				other_form = $this.layer.closest('form').next(),
				other_layer = other_form.find(other_layer_selector);
			if( html ){
				$this.layer.html($(html).find('.calendar_base').html());

				if(other_form.length>0 && other_layer.length>0){

					other_form.find('[update-id]').each(function(){
						var obj1 = $(this),
							obj2 = $('[update-id=' +obj1.attr('update-id')+ ']', other_form);
						if( obj2.length > 0 ){
							obj2.after(obj1).empty();
							obj2.after(obj1).html($(html).find('[update-id]')[0].innerHTML);
						}
					})
					other_layer.html($(html).find(other_layer_selector));

				}
			}

			$this.json = JSON.parse($('textarea.json_data', this.form).val());
			$this.tds = $('td', this.table);
			$this.trs = $('tbody tr', this.table);

			$this._items();
		},
		_items : function() {
			var $this=this,
				has = {},
				has_count = {},
				divs = {};

			$this.trs.each
			(
				function(n1){
					var $tds=$('td', this);

					$tds.each
					(
						function(n2){
							var td=$(this),
								td_key=td.data('key'),
								td_date=new Date(td.data('key'));

							for( key in $this.json ) {
								var item = $this.json[key],
									item_name = 'DAY%s_%s'.sprintf(n1, item.id),
									item_subject = item.subject,
									item_start = item.start_date,
									item_end = item.end_date;

								if( td_date >= new Date(item_start) && td_date <= new Date(item_end) ) {
									if( typeof has[td_key] == 'undefined' ) {
										has[td_key] = [];
										has_count[td_key] = 0;
									}

									if( typeof divs[item_name] == 'undefined' ) {
										divs[item_name] = {
											'key' : item_name,
											'obj' : $('<div />', {'class' : 'item', 'helper' : 'tooltip', 'title': item.subject, 'url' : item.url, 'style' : 'background-color:%s; color:%s !important'.sprintf(item.bg_color, item.font_color) }).html(item.subject),
											'start_date' : item_start,
											'end_date' : item_end,
											'start' : td,
											'end' : td,
											'sort' : has_count[td_key],
											'depth' : has[td_key].pop(),
											'depth_count' : 1
										}

										td.append(divs[item_name].obj);									
									}else {
										divs[item_name].end = td;
									}

									has[td_key].push(item_name);
									has_count[td_key]++;
								}
							}
						}
					);
				}
			);

			for( key in divs ) {
				var item = divs[key],
					start = new Date(item.start_date),
					end = new Date(item.end_date),
					limit = 0;

				while( start <= end ) {
					var date = '%s-%s-%s'.sprintf(start.getFullYear(), ('00'+(start.getMonth() + 1)).slice(-2), ('00'+start.getDate()).slice(-2));

					if( typeof has_count[date] != 'undefined' && item.depth_count < has_count[date] ) {
						item.depth_count = has_count[date];
					}

					start.setDate(start.getDate() + 1);
					if( ++limit > 100 ){
						break;
					}
				}
			}

			$this.items = divs;
			$('.item', $this.layer).helper_tooltip();
		}
	}
);
