/**
 * 创建弹出层
 */
var jhui = {version: '1.0'};

/**
 * 根据传入的弹出层类型，从windowHelper中取出此弹出层的初始化数据，创建弹出层
 * @param {} id 弹出层类型
 * @param {} json
 */
jhui.Window = function(id, json){
	var win = windowHelper.windows[id];
	this[win.winType](id, win.width, win.height, json, win.title, win.count);
}
 
jhui.Window.prototype = {
	//一级单选
	win: function(id, width, height){
		var winId = windowTool.createWin(id, width, height);
		windowTool.highlight('.win-item td', $(winId)).click(function(){
			windowTool.setValue(id, this);
		});
	},
	
	//二级单选
	subWin: function(id, width, height, json){
		var winId = windowTool.createWin(id, width, height);
		windowTool.highlight('.win-item td[class!="item-title"]', $(winId)).click(function(event){
			if(!windowTool.createSubWin(event, json, $(this).attr('code'))){
				return;
			}
			windowTool.highlight('.sub-win-body td').click(function(){
				windowTool.setValue(id, this);
			});
			windowTool.removeSubWin(this);
		});
	},
	
	//一级多选
	win2: function(id, width, height, json, title, count){
		var winId = windowTool.createWin2(id, false, width, height, title);
		$('.win-item td[class!="item-title"][class!="check-title"][class!="fixCell"]', $(winId)).live('mouseover', function(){
			$(this).css({'background-color': 'orange'});
		}).live('mouseout', function(){
			var bgColor = $(this).parent().css('background-color');
			if(bgColor){
				$(this).css({'background-color': bgColor});
			} else{
				$(this).css({'background-color': 'transparent'});
			}
		});
		$('.item-check', $(winId)).live('click', function(){
			var text = $(this).parent().html();
			var code = $(this).parent().attr('code');
			if(this.checked){
				windowTool.addItem(id, this, code, text, count);
			} else{
				windowTool.removeItem(id, code, count);
			}
		});
		windowTool.close(id);
	},
	
	//二级多选
	subWin2: function(id, width, height, json, title, count){
		var winId = windowTool.createWin2(id, true, width, height, title);
		windowTool.highlight('.win-item td[class!="item-title"][class!="check-title"]', $(winId)).click(function(event){
			if($(this).attr('class') == 'use-item' || !windowTool.createSubWin(event, json, $(this).attr('code'))){
				return;
			}
			
			windowTool.addCheckbox(winId);
			windowTool.highlight('.sub-win-body td', $('.sub-win'));
			$('.item-check', $('.sub-win')).live('click', function(){
				var text = $(this).parent().html();
				var code = $(this).parent().attr('code');
				if(this.checked){
					windowTool.addItem(id, this, code, text, count);
				} else{
					windowTool.removeItem(id, code, count);
				}
			});
			
			/*
			 * 点击已选区域的多选框时，删除该多选框对应的项
			 */
			$('.use-item .item-check', $(winId)).live('click', function(){
				var code = $(this).parent().attr('code');
				$('.use-item[code="' + code + '"]', $(winId)).remove();
				/*
				$('.win-item tr[class!="item-data"]', $(winId)).each(function(){
					var cells = this.rowIndex > 0 ? count - 1 : count;
					if($('td', this).length < cells){
						if($(this).next().attr('class').indexOf('item-data') == -1){
							$($('td', $(this).next()).get(0)).appendTo(this);
						}
					}
				});
				*/					
			});
			 windowTool.removeSubWin(this);
		});
	   	windowTool.close(id);
	},
	
	//地区单选
	cityWin: function(id, width, height, json){
		var winId = windowTool.init(id, width, height);
		
		//主要城市
		windowTool.highlight('.city-data td[colspan!="6"]', $(winId)).click(function(){
			windowTool.setValue(id, this);
		});
		
		//省份及城市
		windowTool.highlight('.province-data td', $(winId)).click(function(event){
			windowTool.createSubWin(event, json, $(this).attr('code'), 4);
			windowTool.highlight('.sub-win-body td', $('.sub-win')).click(function(){
				windowTool.setValue(id, this);
			});
			windowTool.removeSubWin(this);
		});
		
		//确定
		$('.win-title-ok', $(winId)).click(function(){
			$('body').unmask();
			$(winId).css({display: 'none'});
		});
	},
	
	//地区多选
	cityWin2: function(id, width, height, json, title, count){
		var winId = windowTool.init(id, width, height, title);
	 
		if(!$(winId).attr('init')){
			$(winId).attr({init: 'init'});
			$('.city-item', $(winId)).prepend('<tr><td class="city-title">' + title + '：</td></tr>');
			$('.item-data[first] td', $(winId)).css({'border-top': '1px dotted gray'});
			$('.city-data td[colspan!="6"]', $(winId)).prepend('<input type="checkbox" class="item-check" />');
		}
		
		//主要城市
		windowTool.highlight('.city-data td[colspan!="6"]', $(winId));
		$('.item-check', $(winId)).click(function(){
			var text = $(this).parent().html();
			var code = $(this).parent().attr('code');
			if(this.checked){
				windowTool.addItem(id, this, code, text, count);
			} else{
				windowTool.removeItem(id, code, count);
			}
		});
		
		//省份及城市
		windowTool.highlight('.province-data td', $(winId)).click(function(event){
			windowTool.createSubWin(event, json, $(this).attr('code'), 4);
			windowTool.addCheckbox(winId);
			windowTool.highlight('.sub-win-body td', $('.sub-win'));
			$('.item-check', $('.sub-win')).live('click', function(){
				var text = $(this).parent().html();
				var code = $(this).parent().attr('code');
				if(this.checked){
					windowTool.addItem(id, this, code, text, count);
				} else{
					windowTool.removeItem(id, code, count);
				}
			});
			windowTool.removeSubWin(this);
		});
		
		//在已选区域删除已选项
		$('.use-item .item-check', $(winId)).live('click', function(){
			var code = $(this).parent().attr('code');
			$('.use-item[code="' + code + '"]', $(winId)).remove();
			$('.city-data td[code="' + code + '"] .item-check').attr({checked: false});
			$('.win-item tr[class!="item-data"]', $(winId)).each(function(){
				var cells = this.rowIndex > 0 ? count - 1 : count;
				if($('td', this).length < cells){
					if($(this).next().attr('class') != 'item-data'){
						$($('td', $(this).next()).get(0)).appendTo(this);
					}
				}
			});
		});
		
		windowTool.close(id);
	}
};

/**
 * 弹出层的工具类
 */
var windowTool = {
	//初始化弹出层
	init: function(id, width, height){
		var winId = 'div[win="' + id + '"]';
		
		$(winId).css({width: width + 'px'});
		$('.win-body', winId).css({height: height + 'px'});
		
		var left = ($('body').innerWidth() - $(winId).innerWidth()) / 2;
		
		
	    var topPX=document.documentElement.scrollTop;
		var top = ($('body').innerHeight() - $(winId).innerHeight()) / 2;
		
		$('body').mask();
		$(winId).css({
			position: 'absolute',
			display: 'block',
			left: left + 'px',
			top: 100 +topPX+ 'px',
			'z-index': 15000 //一级弹出层的zIndex
		}).draggable({
			handle: '.win-title-wrap'
		});
		
		return winId;
	},
	
	//高亮文字
	highlight: function(expr, context){
		var obj = $(expr);
		if(context){
			obj = $(expr, context);
		}
		return obj.mouseover(function(){
			$(this).css({'background-color': 'orange'});
		}).mouseout(function(){
			var bgColor = $(this).parent().css('background-color');
			if(bgColor){
				$(this).css({'background-color': bgColor});
			} else{
				$(this).css({'background-color': 'transparent'});
			}
		});
	},
	
	//创建单选弹出层
	createWin: function(id, width, height){
		var winId = this.init(id, width, height);
		$('.win-title-ok', $(winId)).click(function(){
			$('body').unmask();
			$(winId).css({display: 'none'});
		});
		return winId;
	},
	
	//单选弹出层取值
	setValue: function(id, target){
		var source = windowHelper.target;
		var winId = 'div[win="' + id + '"]';
		$('body').unmask();
		$(winId).css({display: 'none'});
		$(source).html(Ext.util.Format.ellipsis($(target).text(), 8));
		$(source).attr({title: $(target).text()});
		$(source).next().val($(target).attr('code'));
		$('.sub-win').remove();
	},
	
	//创建二级弹出层
	createSubWin: function(event, json, code, count){
		if(!json || !json[code + '']){
			return false;
		}
		var step = count || 2;
		var data = json[code + ''];
		var title = data.name;
		var items = data.items;
		var html = '<table class="sub-win-body" cellspacing="0" cellpadding="0">';
		html += '<tr><td colspan="' + count + '" style="font-weight: bold" code="' + code + '">' + title + '</td></tr>';
		var buffer = new Array();
		for(var i = 0, len = items.length;i < len;i++){
			var tpl = '';
			if(i % step == 0){
				tpl += '<tr>';
			}
			tpl += '<td code="' + items[i].code + '">' + items[i].name + '</td>';
			if((i - (step - 1)) % step == 0){
				tpl += '</tr>';
			}
			buffer.push(tpl)
		}
		html = html + buffer.join('') + '</table>';
		
		if($('.sub-win').length > 0){
			$('.sub-win').remove();
		}
		$('body').append('<div class="sub-win"></div>');
		var evt = event || window.event;
		$('.sub-win').css({
			left: evt.pageX + 'px',
			top:  evt.pageY + 'px',
			position: 'absolute',
			'z-index': 16000, //二级弹出层的zIndex
			border: '1px solid orange'
		}).append(html);
		
		if($('body').innerHeight() < evt.clientY + $('.sub-win').outerHeight()){
			$('.sub-win').css({
				top: $('body').innerHeight() - $('.sub-win').outerHeight() + 'px'
			});
		}
		return true;
	},
	
	//销毁二级弹出层
	removeSubWin: function(target){
		var win = {};
		win.left = $(target).offset().left;
		win.top = $(target).offset().top;
		win.width = $(target).outerWidth(true);
		win.height = $(target).outerHeight(true);
		
		var subWin = {};
		subWin.left = $('.sub-win').offset().left;
		subWin.top = $('.sub-win').offset().top;
		subWin.width = $('.sub-win').outerWidth(true);
		subWin.height = $('.sub-win').outerHeight(true);
		$('body').mousemove(function(event){
		    var evt = event || window.event;
			var x = evt.pageX;
			var y = evt.pageY;
			if(x < win.left || x > (win.left + win.width) || y < win.top || y > (win.top + win.height)){ //不在文字上
				if(x < subWin.left - 5 || x > (subWin.left + subWin.width) + 5 || y < subWin.top || y > (subWin.top + subWin.height)){ //不在窗口内
					$('.sub-win').remove();
					$('body').unbind('mousemove');
				}
			}
		});
	},
	
	//创建多选弹出层
	createWin2: function(id, subWin, width, height, title){
		var winId = this.createWin(id, width, height);
		if(!$(winId).attr('init')){
			$(winId).attr({init: 'init'});
			$('.win-item', $(winId)).prepend('<tr><td class="check-title">' + title + '：</td></tr>');
			if(!subWin){
				$('.item-data td[class!="item-title"][class!="fixCell"]', $(winId)).prepend('<input type="checkbox" class="item-check" />');
			}
			$('.item-data[first] td', $(winId)).css({'border-top': '1px dotted gray'});
		}
		return winId;
	},
	
	//添加多选框
	addCheckbox: function(winId){
		$('.item-check', $('.sub-win')).die();
		$('.sub-win-body td', $('.sub-win')).prepend('<input type="checkbox" class="item-check" />');
		$('.use-item', $(winId)).each(function(){
			var code = $(this).attr('code');
			$('.sub-win-body td[code="' + code + '"] .item-check', $('.sub-win')).attr({checked: true});
		});
		
		if($('body').innerHeight() < $('.sub-win').offset().top + $('.sub-win').outerHeight()){
			$('.sub-win').css({
				top: $('body').innerHeight() - $('.sub-win').outerHeight() + 'px'
			});
		}
	},
	
	//在已选区域添加内容
	addItem: function(id, target, code, text, count){
		var winId = 'div[win="' + id + '"]';
		var flag = true;
		if($('.use-item', $(winId)).length >= 5){
			target.checked = false;
			alert('最多只能选择5项');
			return;
		}
		var target = $('.win-item tr[class!="item-data"]', $(winId));
		if(target.length == 0){
			target = $('.city-item tr[class!="item-data"]', $(winId));
		}
		target.each(function(){
			var cells = this.rowIndex > 0 ? count - 1 : count;
			if($('td', this).length < cells){
				$(this).append('<td class="use-item" code="' + code + '">' + text + '</td>');
				flag = false;
				return false;
			}
		});
		if(flag){
			$('.item-data[first]', $(winId)).before('<tr><td class="use-item" code="' + code + '">' + text + '</td></tr>');
			$('td.check-title', $(winId)).attr({rowSpan: $('.item-data[first]', $(winId)).get(0).rowIndex});
		}
	},
	
	//在已选区域删除内容
	removeItem: function(id, code, count){
		var winId = 'div[win="' + id + '"]';
		var target = $('.use-item[code="' + code + '"]', $(winId));
		if(target.length > 0){
			$('.item-data td[code="' + code + '"] .item-check').attr({checked: false});
			target.remove();
			/*		
			$('.win-item tr[class!="item-data"]', $(winId)).each(function(){
				var cells = this.rowIndex > 0 ? count - 1 : count;
				if($('td', this).length < cells){
					if($(this).next().attr('class').indexOf('item-data') == -1){
						$($('td', $(this).next()).get(0)).appendTo(this);
					}
				}
			});
			*/
		}
	},
	
	//多选弹出层取值
	close: function(id){
		var source = windowHelper.target;
		var winId = 'div[win="' + id + '"]';
		$('.win-title-ok', $(winId)).click(function(){
			$('body').unmask();
			$(winId).css({display: 'none'});
			$('.item-check', $(winId)).die();
			var text = '';
			var value = '';
			$('.use-item', $(winId)).each(function(){
				text += $(this).text() + '+';
				value += $(this).attr('code') + ',';
			});
			if(text != ''){
				text = text.substring(0, text.length - 1);
				value = value.substring(0, value.length - 1);
			}
			if(text == ''){
				$(source).html('选择/修改');
			} else{
				$(source).html(Ext.util.Format.ellipsis(text, 8));
				$(source).attr({title: text});
			}
			$(source).next().val(value);
		});
	}
};

/**
 * 弹出层的初始化数据
 */
var windowHelper = {
	windows: {
		'industryWin': {
			winType: 'win',
			width: 480,
			height: 375
		},
		'functionsWin': {
			winType: 'subWin',
			width: 480,
			height: 375
		},
		'majorWin': {
			winType: 'subWin',
			width: 480,
			height: 185
		},
		'industryWin2': {
			winType: 'win2',
			width: 480,
			height: 440,
			title: '已选行业',
			count: 3
		},
		'functionsWin2': {
			winType: 'subWin2',
			width: 480,
			height: 375,
			title: '已选职能',
			count: 3
		},
		'industryWin3': {
			winType: 'win2',
			width: 750,
			height: 560,
			title: '已选行业',
			count: 4
		},
		'functionsWin3': {
			winType: 'subWin2',
			width: 650,
			height: 490,
			title: '已选职能',
			count: 4
		},
		'cityWin': {
			winType: 'cityWin',
			width: 480,
			height: 225
		},
		'cityWin2': {
			winType: 'cityWin2',
			width: 480,
			height: 270,
			title: '已选地区',
			count: 6
		}
	},
	template: {
		'win1': function(win, title, json){
			var tpl = new Array();
			tpl.push('<div class="win" win="' + win + '">');
			tpl.push('<div class="win-title-wrap"><span class="win-title">' + title + '</span><span class="win-title-ok">[确定]</span></div>');
			tpl.push('<div class="win-body"><table class="win-item" cellpadding="0" cellspacing="0">');
			for(var i = 0;i < json.length;i++){
				if(i == 0){
					tpl.push('<tr class="item-data" first="first">');
				}
				if(i > 0 &&  i % 3 == 0){
					tpl.push('<tr class="item-data">');
				}
				tpl.push('<td code="' + json[i].id + '">' + json[i].codeName + '</td>');
				if((i - 2) % 3 == 0){
					tpl.push('</tr>');
				}
			}
			tpl.push('</table></div></div>');
			$('body').append(tpl.join(''));
		},
		'win2': function(win, title, general, keys, rowspan){
			var tpl = new Array();
			tpl.push('<div class="win" win="' + win + '">');
			tpl.push('<div class="win-title-wrap"><span class="win-title">' + title + '</span><span class="win-title-ok">[确定]</span></div>');
			tpl.push('<div class="win-body"><table class="win-item" cellpadding="0" cellspacing="0">');
			for(var x = 0, len = keys.length;x < len;x++){
				var key = keys[x];
				var code = general[key];
				if(x == 0){
					tpl.push('<tr class="item-data bigGray" first="first">');
				}
				for(var y = 0, length = code.length;y < length;y++){
					var rows = rowspan[key];
					if((x == 0 && y > 0 && y % 3 == 0) || (x > 0 && y % 3 == 0)){
						if(x % 2 == 0){
							tpl.push('<tr class="item-data bigGray">');
						} else{
							tpl.push('<tr class="item-data">');
						}
					}
					if(y == 0){
						tpl.push('<td class="item-title" rowspan="' + rows + '">' + key + '：</td>');
					}
					tpl.push('<td code="' + code[y].id + '">' + code[y].codeName + '</td>');
					if(y == length - 1 && y + 1 < rows * 3){
						var fix = rows * 3 - y - 2;
						for(var z = 0;z <= fix;z++){
							tpl.push('<td class="fixCell">&nbsp;</td>');
						}
					}
					if((y - 2) % 3 == 0){
						tpl.push('</tr>');
					}
				}
			}
			tpl.push('</table></div></div>');
			$('body').append(tpl.join(''));
		},
		'win3': function(win, title, majorCities, province){
			var tpl = new Array();
			tpl.push('<div class="win" win="' + win + '">');
			tpl.push('<div class="win-title-wrap"><span class="win-title">' + title + '</span><span class="win-title-ok">[确定]</span></div>');
			tpl.push('<div class="win-body"><table class="city-item" cellpadding="0" cellspacing="0">');
			tpl.push('<tr class="city-data" first="first"><td class="city-title bigGray" colspan="6">主要城市：</td></tr>');
			for(var i = 0, len = majorCities.length;i < len;i++){
				if(i == 0){
					tpl.push('<tr class="city-data" first="first">');
				}
				if(i > 0 && i % 6 == 0){
					tpl.push('<tr class="city-data">');
				}
				tpl.push('<td code="' + majorCities[i].id + '">' + majorCities[i].codeName + '</td>');
				if((i - 5) % 6 == 0){
					tpl.push('</tr>');
				}
			}
			tpl.push('<tr class="item-data"><td class="city-title bigGray" colspan="6">主要省份：</td></tr>');
			for(var i = 0, len = province.length;i < len;i++){
				if(i == 0){
					tpl.push('<tr class="province-data" first="first">');
				}
				if(i > 0 && i % 6 == 0){
					tpl.push('<tr class="province-data">');
				}
				tpl.push('<td code="' + province[i].id + '">' + province[i].codeName + '</td>');
				if((i - 5) % 6 == 0){
					tpl.push('</tr>');
				}
			}
			tpl.push('</table></div></div>');
			$('body').append(tpl.join(''));
		}
	}
}

$(document).ready(function(){
	$.post('sys/getWindow.html',{}, function(data){
		data = Ext.decode(data);
		
		windowHelper.template['win1']('majorWin', '请选择专业', data.major);
		windowHelper.template['win1']('industryWin', '请选择行业', data.industry);
		windowHelper.template['win1']('functionsWin', '请选择职能', data.industry);
		windowHelper.template['win1']('industryWin2', '请选择行业', data.industry);
		windowHelper.template['win1']('functionsWin2', '请选择职能', data.industry);
		windowHelper.template['win2']('industryWin3', '请选择行业', data.general, data.keys, data.rowspan);
		windowHelper.template['win2']('functionsWin3', '请选择职能', data.general, data.keys, data.rowspan);
		windowHelper.template['win3']('cityWin', '请选择地区', data.majorCities, data.province);
		windowHelper.template['win3']('cityWin2', '请选择地区', data.majorCities, data.province);
		
		$('button[win]').live('click', function(){
			windowHelper.target = this;
			var id = $(this).attr('win');
			if(id == 'cityWin' || id == 'cityWin2'){
				new jhui.Window(id, data.city);
			} else if(id == 'majorWin'){
				new jhui.Window(id, data.subMajor);
			} else{
				new jhui.Window(id, data.functions);
			}
			return false;
		});
	});
});
