/**
 * @Author 冯涛涛
 * @Data 2011.7.11
 * @Note 第三方委托页面JS
 */
$(document).ready(function(){
	var _mainClass = "all";
	var _topClass = "topbox";
	var _middleClass = "contentbox";
	var _bottomClass = "footer";
	var _searchBoxClass = "searchbox";
	var _searchInputClass = "searchinput";
	var _inputAttachClass = "searchAttach";
	var _searchAttachTableClass = "st";
	var _matchResultItemClass = "ml";
	var _qsListClass = "qslist";
	var _buttonClass = "btn_jb";
	var _buttonInvalClass = "btn_null";
	var _buttonFrClass = "fr_ml8";
	var _tipClass = "tips-yybox";
	var _butConfirmClass = "confirm";
	var _butCancelClass = "cancel";
	var _itemClass = "item";
	var _itemDftClass = "bn_default";
	var _itemHasTipClass = "bn_default_r";
	var _itemDftCurClass = "current_rd";
	var _itemHasTipCurClass = "current_rd";
	var _hasTipClass = "fontb";
	var _topTitle = "选择开户券商:";
	var _searchBoxValue = "拼音缩写/关键字搜索，如：海通证券/htzq/ht";
	var _loadPackInfoUrl = "http://dsfwt.10jqka.com.cn/default/index/dealerpacket/?jsoncallback=?";
	var _loadTipInfoUrl = "http://dsfwt.10jqka.com.cn/default/index/dealerinfor/?jsoncallback=?";

	/**
	 * @Author jinjian2@myhexin.com
	 * @var	{JSON} 券商列表数据
	 */
	var _dataStore = null;
	var _loadDealerListUrl = "http://dsfwt.10jqka.com.cn/dealerlist/index.html";
	
	var _searchSelector;
	var _itemContainerSelector;
	var _hotInforSelector;
	var _hotInforTipSelector;
	var _ulSelector;
	var _confirmSelector;
	var _cancelSelector;
	var _inputAttachSelector;
	var _keyWords;
	var _searchResult;
	var _addedList;
	var _addList;
	var _ggyyTip = [];
	var _tipHeight;
	var _midDivHeight;
	var _sortData;
	
	var _inputLimitNum = 24;
	var _tdIndex = -1;
	var _debug = false;
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.11
	 * @Note 添加事件侦听器，包括搜索框和搜索确认按钮等
	 */
	function attachListener(){
		itemListener();
		hotInforListener();
		matchItemListener();
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 搜索框侦听器，监听focus和keyup事件
	 */
	function inputListener(){
		_searchSelector.focus(function(e){
			if(_searchSelector.attr("value") == _searchBoxValue){
				_searchSelector.addClass("inputFocus").attr("value", "");
			}
		});
		
		_searchSelector.blur(function(e){
			if(_searchSelector.attr("value") == ""){
				_searchSelector.removeClass("inputFocus").attr("value", _searchBoxValue);
			}
			
		})
		
		_searchSelector.keyup(function(e){
			if(_keyWords != _searchSelector.attr("value")){
				_keyWords = _searchSelector.attr("value");
				_keyWords = _keyWords.replace(/[^(\u4E00-\u9FA5a-zA-Z)]/g,'');
				updataMaxLength(_keyWords);
				_searchSelector.attr("value", _keyWords);
				if(_keyWords != _searchBoxValue && _keyWords != ''){
					doSearch(_keyWords);
					_tdIndex = -1;
				}else{
					sortRender(_sortData);
					_tdIndex = -1;
				}
				
				$(getSelector4Class(_butConfirmClass)).addClass(_buttonInvalClass).removeClass(_buttonClass);
			}
		});
	}
	
	function updataMaxLength(value){
		var valueArr = value.split('');
		var limitNum = _inputLimitNum;
		_searchSelector.attr("maxlength", _inputLimitNum);
		for(var i in valueArr){
			if(!(("a"<=valueArr[i] && valueArr[i]<="z") || ("A"<=valueArr[i] && valueArr[i]<="Z"))){
				_searchSelector.attr("maxlength", (--limitNum));
			}
		}
		
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 广告营运信息标志侦听器，控制tip框的显示与隐藏
	 */
	function hotInforListener(){
		var t;
		_hotInforSelector.delegate(".bn_default_r", "mouseover", function(e){
			var that = this;
			var flag = true;
			var id = $(that).attr("id");
			for(var i in _ggyyTip){
				if(id == _ggyyTip[i].id){
					flag = false;
					var htmlArr = [];
					var tipName = getTipName(id);
					htmlArr.push(
						'<p><strong>', tipName ,'</strong>', _ggyyTip[i].infor, '</p>'
					);
					_hotInforTipSelector.html(htmlArr.join(''));
				}
			};
			if(flag){
				loadGGYY(id)
			}
			var offset = $(this).offset();
			
			t = setTimeout(function(){
				_hotInforTipSelector.attr("style", "top:" + (_midDivHeight + 46) + "px");
				_hotInforTipSelector.show("slow");
				_tipHeight = $(getSelector4Class(_tipClass)).height();
				_midDivHeight = $(getSelector4Class(_middleClass)).height();
				if(offset.top < 160){
					_hotInforTipSelector.attr("style", "top:" + (_midDivHeight - _tipHeight + 46) + "px");
				}else{
					_hotInforTipSelector.attr("style", "top:50px");
				}
			}, 300);
			
			flag = true;
		});
		
		_hotInforSelector.delegate(".bn_default_r", "mouseout", function(e){
			if(t){
				clearTimeout(t);
			}
			_hotInforTipSelector.hide();
		});
		
		_hotInforTipSelector.mouseover(function(e){
			_hotInforTipSelector.show();
		});
		
		_hotInforTipSelector.mouseout(function(e){
			_hotInforTipSelector.hide();
		});
	}
	
	function itemListener(){
		_itemContainerSelector.delegate(getSelector4Class(_itemClass), "click", function(e){
			if(!$(this).children().hasClass(_hasTipClass)){
				$.each($(this).siblings(), function(i, obj){
					if($(obj).hasClass(_itemDftCurClass)){
						$(obj).removeClass(_itemDftCurClass);
					}else if($(obj).hasClass(_itemHasTipCurClass)){
						$(obj).removeClass(_itemHasTipCurClass);
					}
				});
				$.each($(this).parent().parent().siblings(), function(i, obj){
					$.each($(obj).children().children(), function(j, item){
						if($(item).hasClass(_itemDftCurClass)){
							$(item).removeClass(_itemDftCurClass);
						}else if($(item).hasClass(_itemHasTipCurClass)){
							$(item).removeClass(_itemHasTipCurClass);
						}
					})
				})
				
				$(this).hasClass(_itemHasTipClass) ? $(this).addClass(_itemHasTipCurClass) : $(this).addClass(_itemDftCurClass);
				$(getSelector4Class(_butConfirmClass)).addClass(_buttonClass).removeClass(_buttonInvalClass);
			}
		});
		
		_itemContainerSelector.delegate(getSelector4Class(_itemClass), "dblclick", function(e){
			e.preventDefault();
			if(!($(this).children().hasClass(_hasTipClass))){
				loadAddedList($(this).attr("id"));
			}
		});
		
		_confirmSelector.click(function(e){
			e.preventDefault();
			if($(".item").hasClass(_itemDftCurClass)){
				loadAddedList($("." + _itemDftCurClass).attr("id"));
			}else if($(".item").hasClass(_itemHasTipCurClass)){
				loadAddedList($("." + _itemHasTipCurClass).attr("id"));
			}
			
		})
		
	}
	
	function cancelButListener(){
		_cancelSelector.click(function(e){
			e.preventDefault();
			external.clickButton(2);
		})
	}
	
	function matchItemListener(){
		_inputAttachSelector.delegate("tr", "mouseover", function(e){
			$.each($(this).siblings(), function(i, obj){
				if($(obj).hasClass("mo")){
					$(obj).attr("class", "ml");
				}
			});
			$(this).attr("class", "mo");
			_tdIndex = $(getSelector4Class(_inputAttachClass) + " tr").index($(this));
		});
		
		_inputAttachSelector.delegate("tr", "mouseout", function(e){
			$(this).attr("class", "ml");
		});
		
		_inputAttachSelector.delegate("tr", "click", function(e){
			var dataArr = [];
			var that = this;
			$.each(_dataStore, function(i, obj){
				if(obj.qsid == $(that).attr("id")){
					dataArr.push(obj);
					_searchSelector.attr("value", obj.key1);
				}
			})
			render(dataArr);
			$(this).parent().hide();
		});
		
		$("body").click(function(e){
			_inputAttachSelector.hide();
		})
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 检索函数
	 * @param key 输入框的值
	 */
	function doSearch(key){
		if(_dataStore){
			var result = [];//记录正则表达式匹配结果
			var flag;//判断是否符合匹配
			parse_url = new RegExp(key,"i");
			_searchResult = [];
			
			$.each(_dataStore, function(i, obj){
				$.each(obj, function(j, value){
					if(!flag){
						result = (parse_url.exec(value));
						if(result){
							flag = true;
						}
					}
				})
				if(flag){
					_searchResult.push(_dataStore[i]);
					flag = false;
				}
			})
			render(_searchResult);
		}
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.11
	 * @params dataStore 需要渲染的数据
	 * @Note 页面渲染函数
	 */
	function render(dataStore){
		if(!dataStore) return;
		var htmlArr = [];
		var dataNum = dataStore.length;
		
		$.each(dataStore, function(i, obj){
			if(i == 0){
				htmlArr.push(
					'<dd class="list_dh">',
					'<h5>&nbsp</h5>',
					'<p>',
					'<a href="#" id="', obj.qsid ,'" class="', (obj.infor == "0" ? _itemDftClass : _itemHasTipClass),' ', _itemClass, '"><span class="',(isAdded(obj.qsid) ? _hasTipClass:""),'">', obj.key1, '</span></a>'
				);
			}else if(i == (dataNum - 1)){
				htmlArr.push(
					'<a href="#" id="', obj.qsid ,'" class="', (obj.infor == "0" ? _itemDftClass : _itemHasTipClass),' ', _itemClass, '"><span class="',(isAdded(obj.qsid) ? _hasTipClass:""),'">', obj.key1, '</span></a></p></dd>'
				);
			}else{
				htmlArr.push(
					'<a href="#" id="', obj.qsid ,'" class="', (obj.infor == "0" ? _itemDftClass : _itemHasTipClass),' ', _itemClass, '"><span class="',(isAdded(obj.qsid) ? _hasTipClass:""),'">', obj.key1, '</span></a>'
				);
			}
		});
		
		_ulSelector.html(htmlArr.join(''));
		_tdIndex = -1;
	}
	
	function dosort(dataStore){
		_sortData = {};
		var initLetter = null;
		$.each(dataStore, function(i, obj){
			firstLetter=obj.key3.split('')[0];
			if(firstLetter != initLetter){
				initLetter = firstLetter;
				_sortData[initLetter] = [];
				_sortData[initLetter].push(obj);
			}else{
				_sortData[initLetter].push(obj);
			}
		});
		sortRender(_sortData);
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 分类渲染函数，当搜索框的值为空时调用该函数
	 * @param dataStore 待渲染的数据
	 */
	function sortRender(sortData){
		var htmlArr = [];
		
		if(!sortData)
			return;
		
		$.each(sortData, function(i, obj){
			htmlArr.push(
				'<dd class="list_dh">',
				'<h5>', i.toUpperCase(), '</h5>',
				'<p>'
			);
			$.each(obj, function(j, item){
				htmlArr.push(
					'<a href="#" id="', item.qsid ,'" class="', (item.infor == "0" ? _itemDftClass : _itemHasTipClass), ' ', _itemClass, '"><span class="',(isAdded(item.qsid) ? _hasTipClass:""),'">', item.key1, '</span></a>'
				);
			});
			htmlArr.push(
				'</p>',
				'</dd>'
			);
		});
		
		_ulSelector = $(getSelector4Class(_qsListClass));
		_ulSelector.html(htmlArr.join(''));
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 搜索框字符数限制函数
	 */
	function inputLimit(num){
		_searchSelector.attr("maxlength", num);
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 加载安装包信息并调用静默安装接口
	 * @param id 欲安装券商的id
	 */
	function loadAddedList(id){
		if(id != undefined){
			//加载包信息
			$.getJSON(_loadPackInfoUrl, 
			{
				op: "infor",
				type: "json",
				gid: id
			},
			function(data){
				_addList = data[0];
				var addInfo = {
					ID:Number(_addList.qsid),
					INSTALLTYPE:_addList.type,
					NAME:_addList.name,
					DOWNLOADURL:_addList.url,
					INSTALLKEY:_addList.regedit,
					VERSION:_addList.version,
					EXENAME:_addList.setup,
					INSTALLCMD:'',
					WEITUOID:_addList.wtid,
					XDTYPE:_addList.xdtype
				}
				//进入安装
				if(!_debug){
					external.addUserBrokerage(addInfo);
					external.clickButton(1);
				}
			});
		}
	};
	
	//加载广告运营信息
	function loadGGYY(id){
		$.getJSON(_loadTipInfoUrl, 
		{
			op: "infor",
			gid: id
		},function(data){
			_ggyyTip.push({"id": id, "infor": data[0].infor});
			tipInfor = data[0].infor;
			
			var htmlArr = [];
			var tipName = getTipName(id);
			htmlArr.push(
				'<p><strong>', tipName ,'</strong>', tipInfor, '</p>'
			);
			_hotInforTipSelector.html(htmlArr.join(''));
		});
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note html框架的生成函数
	 */
	function generateBody(){
		var bodyHtmlArr = [];
		
		bodyHtmlArr.push(
			'<div class="', _mainClass, '">',
				'<div class="', _topClass, '">',
					'<h4>', _topTitle, '</h4>',
					'<div class="', _searchBoxClass,'">',
						'<input type="text" value="', _searchBoxValue, '" class="', _searchInputClass, '"/>',
						'<div class="', _inputAttachClass, '" style="display:none;"></div>',
					'</div>',
				'</div>',
				'<div class="', _middleClass, '">',
					'<dl class="', _qsListClass, '"></dl>',
				'</div>',
				'<div class="', _bottomClass, '">',
					'<p class="intro_text">同花顺老用户可选择添加“A老版下单程序”，恢复到原来的下单模式。</p>',
					'<a href="#" class="', _buttonClass, ' fr_ml8 cancel">取消</a>',
					'<a href="#" class="', _buttonInvalClass, ' fr_ml8 confirm">添加</a>',
				'</div>',
			'</div>',
			'<div class="', _tipClass, '"></div>'
		);
		
		$("body").html(bodyHtmlArr.join(''));
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 初始各选择器
	 */
	function initSelector(){
		_searchSelector = $(getSelector4Class(_searchInputClass));
		_itemContainerSelector = $(getSelector4Class(_qsListClass));
		_hotInforSelector = $(getSelector4Class(_middleClass));
		_hotInforTipSelector = $(getSelector4Class(_tipClass));
		_ulSelector = $(getSelector4Class(_qsListClass));
		_confirmSelector = $(getSelector4Class(_butConfirmClass));
		_cancelSelector = $(getSelector4Class(_butCancelClass));
		_inputAttachSelector = $(getSelector4Class(_inputAttachClass));
	}
	
	/**
	 * @Author 冯涛涛
	 * @Data 2011.7.26
	 * @Note 加载已安装列表
	 */
	function loadUserBrokerages(){
		var list = external.getUserBrokerages();
		list = list.split(",");
		
		return list;
	}
	
	function getTipName(id){
		var name;
		$.each(_dataStore, function(i, obj){
			if(obj.qsid == id){
				name = obj.key1;
			}
		})
		return name;
	}
	
	function isAdded(id){
		var flag = false;
		$.each(_addedList, function(i, obj){
			if(obj == id){
				flag = true;
			}
		})
		return flag;
	}
	
	function getSelector4Class(cls){
		return "." + cls;
	}
	
	generateBody();
	initSelector();
	
	if(_debug){
		_addedList = [1, 2, 3];//调试数据
	}else{
		_addedList = loadUserBrokerages();
	}
	
	//请求券商列表数据
	$.ajax({
			url: _loadDealerListUrl,
			dataType: "jsonp",
			cache: false,
			jsonp: false,
			jsonpCallback: "loadData",
			success: function(data){
				_dataStore = data;
				if(_dataStore){
					dosort(_dataStore);
					attachListener();
				}else{
				}
			}
		}
	);
	inputListener();
	cancelButListener();
	inputLimit(_inputLimitNum);
	_hotInforTipSelector.hide();
});