var Utils = {};
var shine = new Array();
var oldshine = new Array();
var cltOpt = {
	MoveWindow : function(){
		var cltWindow = external.GetObject2("window");
		if(cltWindow) {
			cltWindow.size("move");
		}
	},
	CloseWindow : function(){
		var cltWindow = external.GetObject2("window");
		if(cltWindow) cltWindow.close();
	},
	GetValue : function (optkey){
		var OptClt = external.GetObject("@pplive.com/options;1");
		var optVal = OptClt.GetValue(optkey);
		return optVal;
	},
	SetValue : function (optkey,optval){
		var OptClt = external.GetObject("@pplive.com/options;1");
		var ret = eval("(" + OptClt.SetValue(optkey,optval) + ")");
		return ret;
	},
	ResetValue :function (optkey){
		var OptClt = external.GetObject("@pplive.com/options;1");
		var ret = eval("(" + OptClt.Reset(optkey) + ")");
		return ret;
	},
	IsSupportIntel : function(){
		var OptClt = external.GetObject("@pplive.com/options;1");
		return OptClt.IsSupportIntel;
	},
	IsSupportEVR : function(){
		var OptClt = external.GetObject("@pplive.com/options;1");
		return OptClt.IsSupportEVR;
	},
	AudioDeviceList : function(){
		var OptClt = external.GetObject("@pplive.com/options;1");
		return OptClt.AudioDeviceList;
	},
	SelectFolder : function(objname){
		function cltSelectFolder(){
			var filePicker = external.CreateObject("@pplive.com/filepicker;1");
			if (filePicker){
				filePicker.init(external.GetObject2("options.xml"), "请选择路径", 2);
				var openReturn = filePicker.show();
				if (openReturn != 1){
					return filePicker.file;
				}
			}
			return "";
		};
		function selectFolderCallback(folder){
			if(folder.length>0){
				$('[name="'+objname+'"]').val(folder);
				$('[name="'+objname+'"]').focus();
			}
		};
		clientCommon.call(cltSelectFolder,[],selectFolderCallback);
	}
};
var KEY = {
	1 : 'opt.singletion', //只启动一个pptv 1 0
	2 : 'opt.minisite',	//启动今日焦点 1 0
	3 : 'opt.pptvstartup', //打开计算机时，启动PPTV（及时提醒更新）1 0
	4 : 'opt.shortcut', //智能管理PPTV桌面图标 1 0
	5 : 'opt.recommandbubble', //允许弹出PPTV精彩推荐 1 0
	6 : 'opt.vas', //允许PPTV广告气泡弹出 1 0
	7 : 'opt.ppapresident', //允许PPAP驻留（可让下次启动更加快速） 1 0
	8 : 'opt.deletalocalonclose', //退出后清空本地播放记录 1 0
	9 : 'opt.closetotray', //最小化到托盘 1 关闭程序 0

	10 : 'opt.downloadpath', //默认保存路径 具体路径
	11 : 'opt.downloadmaxcount', //同时开始任务上限 1 - 5
	12 : 'opt.downloadcustom', //每次下载最清晰的版本 0 每次下载以下载清晰度的视频 1
	13 : 'opt.downloaddefinition', //蓝光 0 超清 1 高清 2 流畅 3

	14 : 'opt.screenshottype', //仅保存到剪切板 1 0
	15 : 'opt.screenshotpath', //截图保存路径 路劲
	16 : 'opt.screenshotpic', //保存文件类型 bmp 0 jpg 1 png 2

	17 : 'opt.transfermode', //网络保护 0 播放优先 1
	18 : 'opt.cachesize', //缓存大小设置（单位：MB） 512-10240 -> 512 ，1024，2048，5120，10240
	19 : 'opt.cachepath', //缓存文件路径 路径
	20 : 'opt.dlna', //多屏互动 1 0
	21 : 'opt.ppapstartup', //开机时启动PPAP（开启支持节目更新提醒）

	22 : 'opt.showminiplayer', //选片自动开启“边选边播”模式 1 0
	23 : 'opt.skipheadandtail', //智能跳过片头、片尾
	24 : 'opt.disablescreensave', //禁止屏幕保护和电源管理
	25 : 'opt.playdefinition', //自动匹配当前网络情况 4 手动选择默认清晰度播放 0 - 3 (蓝光 0 超清 1 高清 2 流畅 3)
	26 : 'opt.decoder', //CoreAVC1 CoreAVC 0 CoreAVC2
	27 : 'opt.usedxva', //启动硬件加速（加快播放时的计算机运行效率） 1 0
	28 : 'opt.inteldecoder', //启动Intel硬件加速 1 0 -> cltOpt. IsSupportIntel () 判断是否支持inter加速

	29 : 'opt.prefervr', //选择默认渲染方式 0 1 2 3 4
	30 : 'opt.audiodevice',
	31 : 'opt.bosskeyenable',
	32 : 'opt.rgb32',		//todo 界面上没有
	33 : 'opt.click',
	34 : 'opt.dlnatip',
	35 : 'opt.ugsspeaker', //小喇叭管理器静音
	36 : 'opt.clouddrag'  //云拖动
};

function IsVip()
{
	var obj = clientCommon.getUserInfo();
	if(null != obj)
	{
		return obj.isVip;
	}
	return null;
}

(function(utils){
	var tipsstat = new Array("saved","unsaved","conflict");
	utils.setBaseTab = function(){
		var keys = []; //KEY
		for(var k = 1; k <= 36; k++){
			keys.push(KEY[k]);
		}
		var keys = keys || [], i = 0, val, key, elm, type = 'checkbox';
		while(keys[i]){
			key = keys[i];
			elm = $('[name="'+ key +'"]');
			type = elm.attr('type');
			val = cltOpt.GetValue(key);

			switch(type){
				case 'text' :
				case 'number' :
					elm.val(val);
					break;
				case 'checkbox' :
					if(key == 'opt.inteldecoder' && cltOpt.IsSupportIntel()){ //logic 2
						elm.parent().show();
						if(cltOpt.GetValue("opt.usedxva") == "0")
						{
							elm.attr('disabled','disabled');
						}
					}
					var vip = IsVip();
					if(key == 'opt.vas')
					{
						if(vip == null)
						{
							elm.parent().hide();
						}
						else if(vip == false)
						{
							elm.parent().hide();
							cltOpt.SetValue("opt.vas", 1);
						}						
					}
					elm.attr('checked', !!Number(val));
					elm.prop('checked', !!Number(val));
					break;
				case 'radio' :
					if(key == 'opt.downloadcustom'){
						var isCustom = (val == 1);
						Utils.disableRadioButton('opt.downloaddefinition',!isCustom);
					}
					else if(key == 'opt.playdefinition'){
						var isPlaydefinition = (val != 5);
						Utils.disableRadioButton('playdefinition',!isPlaydefinition);
						if(isPlaydefinition){
							Utils.checkRadioButtonChecked('playdefinition', val);
							Utils.checkRadioButtonChecked(key, 6);
						}
						else{
							Utils.checkRadioButtonChecked('playdefinition', 3);
							Utils.checkRadioButtonChecked(key, val);
						}
						break;
					}
					Utils.checkRadioButtonChecked(key, val);
					break;
				case 'select' :
					Utils.checkSelectOption(elm[0], val);
					break;
				default:
			}

			i++;
		}
	},
	utils.disableRadioButton = function(key, disable){
		var inputs = $('input[name="'+ key +'"]');
		inputs.attr('disabled',disable);
		inputs.prop('disabled',disable);
	},
	//检查radio button
	utils.checkRadioButtonChecked = function(key, index){
		var inputs = $('input[name="'+ key +'"]');
		inputs.removeAttr('checked');

		for(var i = 0; i < inputs.length; i++){
			if(inputs.eq(i).val() == index){
				inputs.eq(i).attr('checked', true);
				inputs.eq(i).prop('checked', true);
				return;
			}
		}
	},
	utils.checkSelectOption = function(objSelect, objItemValue){
		if(objItemValue){
			objSelect.value = objItemValue;
			return;
		}
		return objSelect.selectedIndex;
	},
	utils.ShowTips = function(txt,timeout,index)
	{
		if(timeout<=0){
			if(utils.tiptimeid){
				clearTimeout(utils.tiptimeid);
				utils.tiptimeid=null;
			}
			$(".tips").hide();
			for(var i = 0; i < shine.length; i++)
			{
				shine[i].removeClass('malformed');
			}
		}
		else{
			if(utils.tiptimeid){
				clearTimeout(utils.tiptimeid);
				for(var i = 0; i < oldshine.length; i++)
				{
					oldshine[i].removeClass('malformed');
				}
			}		
			var spantips = $('[name="span.tips"]');
			spantips.html(txt);
			for(var i = 0; i < 3; i++)
			{
				spantips.removeClass(tipsstat[i]);
			}
			spantips.addClass(tipsstat[index]);
			$(".tips").show();
			for(var i = 0; i < shine.length; i++)
			{
				shine[i].addClass('malformed');
			}
			utils.tiptimeid=setTimeout("Utils.ShowTips('',0," + index + ");",timeout);
		}
	}
})(Utils);

//基本设置
(function(){

	Init(); //init...
	function Init(){
		getAudioOutList();
		getAudioDeviceList();
		if(cltOpt.IsSupportEVR()){
			var elm = $('[name="opt.prefervr"]');
			addItemToSelect(elm[0], 'EVR', 5);
		}
		Utils.setBaseTab();
	}

	function getAudioDeviceList(){
		var AudioDeviceList = JSON.parse(cltOpt.AudioDeviceList())['audio'];
		for(var i = 0, len = AudioDeviceList.length; i < len; i++){
			addItemToSelect($('[name="opt.audiodevice"]')[0], AudioDeviceList[i].name, AudioDeviceList[i].val);
		}
	}
	function getAudioOutList(){
		addItemToSelect($('[name="opt.audioOut"]')[0], "立体声", "0");
		addItemToSelect($('[name="opt.audioOut"]')[0],  "单声道", "1");
		addItemToSelect($('[name="opt.audioOut"]')[0], "5.1环绕立体声","2");
		var i = cltOpt.GetValue('opt.audioOut');
		$('[name="opt.audioOut"]')[0].options.selectedIndex = parseInt(i);	
	}
})();


//tabs && search
(function(){
	var content = $('#content');
	var tabs = content.find('.tab_tit a'), tabsub = content.find('.tab_titL .subnav'), tabscont = content.find('.tab_conR');
	var sc = 'A';
    var section = '';
	var Pages = { 0 : 'A', 1 : 'B', 2 : 'C'};
	var Articles = {
		A : [],
		B : [],
		C : []
	};

    function getPosition(id){
	    $('[id ^= '+ id +']').each(function(a, b) {
	        Articles[id].push([$(this).offset().top - 105, this.id]);
	    });
    }

    function selectNavigation(id, instant) {
        if (id === section) {
            return false;
        }

        section = id;
        var current = $('.tab_titL .subnav a.cur');
        current.each(function() {
            $(this).removeClass('cur');
        });

        var next = $('.tab_titL .subnav a[href="#' + id +'"][class!="cur"]');
        next.addClass('cur');
    }

    function highlightSection() {
        var offset = content.find('.tab_conR:visible').scrollTop();
        var id = Articles[sc][0][1];
        for(var i = 0, l = Articles[sc].length; i < l; i++) {
            if (Articles[sc][i][0] < offset + 10) {
                id = Articles[sc][i][1];
            }
        }
        selectNavigation(id, offset === 0);
    }

    var TabHasChanged = {};
	var bFirst = true;
	function ChangeTab(index){
		if(bFirst == false)
		{
			if(tabs.eq(index).hasClass('cur'))
			{
				return;
			}
		}
		bFirst = false;
		tabs.removeClass('cur').eq(index).addClass('cur');
		tabscont.hide().eq(index).show();
		tabsub.hide(200).eq(index).show(200);
		sc = Pages[index];

		if(TabHasChanged[index]){
			highlightSection(sc);
			return;
		}
		getPosition(sc);
	    var initSelection = setTimeout(highlightSection, 100);
	    tabscont.eq(index).scroll(function() {
	        clearTimeout(initSelection);
	        highlightSection(sc);
	    });

		TabHasChanged[index] = true;

	}

	content.find('.tab_tit').click(function(evt){
		var index = this.attributes.getNamedItem("index").nodeValue;
		evt.preventDefault();
		ChangeTab(index);
	});


	//search & hilights
	var linksTable = {}, linksArr = [];
	function getLinks(){
		var linksElm = $('.tab_con > .tab_titL'), type, subType, elm;
		for(var i = 0; i < tabs.length; i++){
			type = tabs.find('span').eq(i).text();
			elm = linksElm.eq(i).find('a');
			for(var j = 0, len = elm.length; j < len; j++){
				subType = elm.eq(j).text() + '-' + type;
				linksArr.push(subType);
				linksTable[subType] = elm.eq(j).attr('href');
			}
		}
		return linksTable;
	}

	$("#autocomplete").bind('focus', function(){
		this.value = '';
	}).autocomplete({
		source: linksArr,
		close : function(){
			var hash = linksTable[this.value] || '###', index = 0;
			sc = hash.match(/\D/g)[1];
			if(sc == 'B'){
				index = 1;
			}else if(sc == 'C'){
				index = 2;
			}
			ChangeTab(index, true);
			window.location.hash = hash;
		}
	});

	//Init...
	getLinks();
	ChangeTab(0);

	//文件关联
	$('a[name="opt.file"]').click(function(){
		$('.file_pop').show();
	});

	//恢复默认设置
	$('a[name="opt.reset"]').click(function(){
		$('.reset_setup').show();
	});

	$('.pop_up .close').click(function(evt){
		evt.preventDefault();
		$(this).parent().parent().hide();
	});

	function ResetDefault(){
		var OptClt = external.GetObject("@pplive.com/options;1");
		var ret = OptClt.Reset("");
		return ret;
	};
	function ResetDefaultCallback(result){
		Utils.ShowTips('设置已保存！',2000,0);
		Utils.setBaseTab();
		Utils.initFile();
		Utils.ResetHotKey();
		Utils.ResetBossKey();
	}
	//确定
	$(".reset_setup .sure_btn").click(function(evt){
		evt.preventDefault();
		$('.reset_setup').hide();
		clientCommon.call(ResetDefault,[],ResetDefaultCallback);
	});
	$(".reset_setup .cancel_btn").click(function(evt){
		evt.preventDefault();
		$('.reset_setup').hide();
	});
})();


//SetValue
$('input[type=checkbox]').bind('click', function(evt){
	var type = this.type;
	var key = this.name, value = this.checked, index = value ? 1 : 0;
	if(key.length==0) return;
	cltOpt.SetValue(key, index);
	if(key == "opt.usedxva")
	{
		if(index == 1)
		{
			$('#checkbox16').removeAttr('disabled');
		}
		else
		{
			$("#checkbox16").attr('disabled','disabled');
			$("#checkbox16").attr('checked', false);
			cltOpt.SetValue("opt.inteldecoder", 0);
		}
	}
});

$('input[type=radio]').bind('click', function(){
	var key = this.name, value = this.value;
	if(key == 'opt.downloadcustom'){
		var isCustom = (value == 1);
		Utils.disableRadioButton('opt.downloaddefinition',!isCustom);
		if(isCustom){
			var subval = $('[name="opt.downloaddefinition"]:checked').val();
			cltOpt.SetValue('opt.downloaddefinition', subval);
		}
	}
	else if(key == 'opt.playdefinition'){
		var isPlaydefinition = (value == 6);
		Utils.disableRadioButton('playdefinition',!isPlaydefinition);
		if(isPlaydefinition){
			var subval = $('[name="playdefinition"]:checked').val();
			cltOpt.SetValue('opt.playdefinition', subval);
			return;
		}
	}
	if(key == 'playdefinition'){
		key = 'opt.playdefinition'
	}

	cltOpt.SetValue(key, value);
});
$('input[type=number]').bind('keyup input', function(evt){ //change|keyup input
	var key = this.name, elm = $(this), value = this.value;
	value=value.replace(/[^0-9]/g,'');
	var val = parseInt(value);
	if(val<1) val=1;
	else if(val>5) val=5;
	value = val;
	$(this).prop('value',value);
	$(this).attr('value',value);
	cltOpt.SetValue(key, value);
	return false;
});

$('select[type=select]').bind('change', function(){
	var key = this.name, value = this.value;
	cltOpt.SetValue(key, value);
});

/* 3 个 路径选择 */
(function(){
	var ArrKey = []; //KEY
	ArrKey.push("opt.downloadpath");
	ArrKey.push("opt.screenshotpath");
	ArrKey.push("opt.cachepath");
	
	//todo ui需要修改
	ArrKey.forEach(function(e){
		$('[name="browser.' + e + '"]').bind('click',function(evt){
			evt.preventDefault();
			cltOpt.SelectFolder(e);
			$('[name="confirm.' + e + '"]').show();
		});
		$('[name="apply.' + e + '"]').bind('click',function(evt){
			evt.preventDefault();
			var folder = $('[name="' + e + '"]').val();
			var setok = false;
			if(folder.length>0){
				var ret = cltOpt.SetValue(e,folder);
				if(ret.err=="0") setok=true;
			}
			folder = cltOpt.GetValue(e);
			$('[name="' + e + '"]').val(folder);
			$('[name="confirm.' + e + '"]').hide();
			if(!setok){
				Utils.ShowTips('路径不可用',2000,1);
			}
		});
		$('[name="cancel.' + e + '"]').bind('click',function(evt){
			evt.preventDefault();
			folder = cltOpt.GetValue(e);
			$('[name="' + e + '"]').val(folder);
			$('[name="confirm.' + e + '"]').hide();
		});
		$('[name="'+ e +'"]').bind('input',function(){
			
			$('[name="confirm.' + e + '"]').show();
		});
	});
})();
/**/

/* 老板键处理 */
(function(utils){
	function InitBossKey(){
		var bosskeyval =cltOpt.GetValue('opt.bosskeyvalue');
		var keycode = (bosskeyval & 0x0000ffff);
		var modify = (bosskeyval>>16);
		var bosskeyctrl = $('[name="opt.bosskeyvalue"]');
		bosskeyctrl.hotkey({
			modifiers: modify,
			keyCode: keycode,
			changing : function(event, ui) {
				if(0 == ui.modifiers && 0==ui.keyCode) return true;
				var allhotkey = $('[name^="opt.hotkey."]');
				for(var i=0,len=allhotkey.length;i<len;++i){
					var option = $(allhotkey[i]).hotkey('option');
					if(option.modifiers == ui.modifiers && option.keyCode==ui.keyCode){
						for(var j = 0; j < shine.length; j++)
						{
							oldshine[j] = shine[j];
						}
						shine[0] = $(allhotkey[i]);
						shine[1] = $(this);
						Utils.ShowTips('快捷键与 ' + $(allhotkey[i]).attr('txt') + ' 冲突',2000,2);
						return false;
					}
				}
				var keyval = (ui.modifiers<<16) | (ui.keyCode & 0x0000ffff);
				var result = cltOpt.SetValue('opt.bosskeyvalue',keyval);
				return (result.err==0)?true:false;
			},
			changed : function(event,ui){
			}
		});
	};
	function ResetBossKey(){
		var bosskeyval =cltOpt.GetValue('opt.bosskeyvalue');
		var keycode = (bosskeyval & 0x0000ffff);
		var modify = (bosskeyval>>16);
		var bosskeyctrl = $('[name="opt.bosskeyvalue"]');
		bosskeyctrl.hotkey('SetHotKey',modify,keycode);
	};
	utils.ResetBossKey = ResetBossKey;
	InitBossKey();
})(Utils);
/* 快捷键处理 */
(function(utils){
	function InitHotKey(){
		var hotkey = JSON.parse(cltOpt.GetValue('opt.hotkey'))['hotkey'];
		for(var i=0,len=hotkey.length;i<len;++i){
			var hotkeyid = 'opt.hotkey.'+ hotkey[i].id;
			var hotkeyval = hotkey[i].key;
			var keycode = (hotkeyval & 0x0000ffff);
			var modify = (hotkeyval>>16);
			var hotkeyctrl = $('[name="' + hotkeyid +'"]');
			if (hotkeyid=="opt.hotkey.menu_openFolder")
			{
				window.alert(modify+"+"+keycode);
			}
			hotkeyctrl.hotkey({
				modifiers: modify,
				keyCode: keycode,
				changing : function(event, ui) {
					if(0 == ui.modifiers && 0==ui.keyCode){
						cltOpt.SetValue(this.name,0)
						return true;
					}
					if(0x00 == ui.modifiers && 0x20==ui.keyCode) return false;	//保留VK_SPACE
					if(0x07 == ui.modifiers && 0x43==ui.keyCode) return false;	//保留Ctrl + Shift + Alt + C
					var bossoption = $('[name="opt.bosskeyvalue"]').hotkey('option');
					var bosskeycode = bossoption.keyCode;
					var bossmodify = bossoption.modifiers;
					if(bossmodify == ui.modifiers && bosskeycode==ui.keyCode){
						for(var j = 0; j < shine.length; j++)
						{
							oldshine[j] = shine[j];
						}
						shine[0] = $('[name="opt.bosskeyvalue"]');
						shine[1] = $(this);
						Utils.ShowTips('快捷键与 老板键 冲突',2000,2);
						return false;
					}
					var allhotkey = $('[name^="opt.hotkey."]');
					for(var i=0,len=allhotkey.length;i<len;++i){
						if(allhotkey[i].name!=this.name){
							var option = $(allhotkey[i]).hotkey('option');
							if(option.modifiers == ui.modifiers && option.keyCode==ui.keyCode){
								for(var j = 0; j < shine.length; j++)
								{
									oldshine[j] = shine[j];
								}
								shine[0] = $(allhotkey[i]);
								shine[1] = $(this);
								Utils.ShowTips('快捷键与 ' + $(allhotkey[i]).attr('txt') + ' 冲突',2000,2);
								return false;
							}
						}
					}
					var keyval = (ui.modifiers<<16) | (ui.keyCode & 0x0000ffff);
					var result = cltOpt.SetValue(this.name,keyval);
					return (result.err==0)?true:false;
				},
				changed : function(event,ui){
					if(this.name=='opt.hotkey.key_screenshot'){
						$('[name="span.key_screenshot"]').html($(this).val());
					}
				}
			});
			if(hotkeyid=='opt.hotkey.key_screenshot'){
				$('[name="span.key_screenshot"]').html(hotkeyctrl.val());
			}
		}
	};
	function ResetHotKey(){
		var hotkey = JSON.parse(cltOpt.GetValue('opt.hotkey'))['hotkey'];
		for(var i=0,len=hotkey.length;i<len;++i){
			var hotkeyid = 'opt.hotkey.'+ hotkey[i].id;
			var hotkeyval = hotkey[i].key;
			var keycode = (hotkeyval & 0x0000ffff);
			var modify = (hotkeyval>>16);
			var hotkeyctrl = $('[name="' + hotkeyid +'"]');
			hotkeyctrl.hotkey('SetHotKey',modify,keycode);
		}
		$('[name="span.key_screenshot"]').html($('[name="opt.hotkey.key_screenshot"]').val());
	};
	utils.ResetHotKey = ResetHotKey;
	InitHotKey();
})(Utils);
//文件关联
(function(utils){
	function each(arr, callbcak, scope) {
		var ss = [];
		for (var i = 0, len = arr.length; i < len; i++) {
			if (callbcak.apply(scope, [arr[i], i, ss]) === true) {
				break;
			}
		}
		return ss;
	}

	var dts = $(".file_con dt");
	var dds = $(".file_con dd");

	var _tabs = [];
	var tabs = {};
	var objs = {};

	function checkTabs(inputs,i){
		var n = inputs.length;
		var nChecked = 0 , nUnChecked = 0;
		each(inputs,function(input,k){
			(input.checked)? nChecked++:nUnChecked++;
		});
		if (nChecked == n){
			_tabs[i].indeterminate = false;
			_tabs[i].checked = true;
		} else if (nUnChecked == n){
			_tabs[i].indeterminate = false;
			_tabs[i].checked = false;
		} else {
			_tabs[i].indeterminate = true;
		}
	}
	
	each(dds,function(dd,i){
		var spans = $("span",dd);
		var inputs = $("input[type=checkbox]",dd);
		
		each(spans,function(span,j){
			var name = span.innerHTML;
			objs[name] = inputs[j];
			inputs[j].onclick = function(){
				checkTabs(inputs,i);

				if ($('.file_pop select').val() != 4){
					$('.file_pop select').val(4);
				}
			}
		});
		tabs[i] = inputs;
	});

	each(dts,function(dt,i){
		var input = $("input[type=checkbox]",dt)[0];
		input.setAttribute('jsvalue',i);
		input.onclick = function(){
			if (this.indeterminate){
				return true;
			}

			var jsvalue = this.getAttribute('jsvalue');
			var checked = this.checked;
			each(tabs[jsvalue],function(checkbox,j){
				checkbox.checked = checked;
			});

			if ($('.file_pop select').val() != 4){
				$('.file_pop select').val(4);
			}
		}
		_tabs.push(input);
	});

	//初始化状态
	 function init(){
		var f = cltOpt.GetValue('opt.file');
		f = eval('('+f+')');
		each(f.file,function(obj,i){
			try{
				objs[obj.suffix].checked = (obj.link == "1")? true:false;
			} catch (e){try{console.log(obj.suffix+' '+obj.link);}catch(e){};}
		});

		for (var p in tabs){
			checkTabs(tabs[p],p);
		}
	}

	function checkVal(){
		function isIn(s,arr){
			var bIn = false;
			for (var i = 0; i < arr.length; i++){
				if (s == arr[i]){
					bIn = true;
					break;
				}
			}
			return bIn;
		}

		var val = 4;
		var t = 0;  //总共
		var c = 0;  //选中
		var r = 0; var rs = ['.rp','.dat'];//推荐
		var m = 0; var ms = ['.wav','.midi','.aac','.ape','.amr','.mp3','.ac3','.dts','.m4a'];//音频
		var v = 0; var vs = ['.wav','.midi','.aac','.ape','.amr','.mp3','.ac3','.dts','.m4a'];//视频

		for (var p in objs ){
			if (objs[p].checked){  //选中
				if (isIn(p,ms)){m++;} else {v++;}
				c++;
			} else {               //未选中
				if (isIn(p,rs)){r++;}
			}
			t++;
		}

		if (c == t){ //全选
			val = 2;
		} else if (c + r == t){ //推荐
			val = 0;
		} else if (m == c && m == 9){ // 音频
			val = 1;
		} else if (v == t - vs.length){ //视频
			val = 3;
		}
		return val;
	}

	utils.initFile = init;
	$('.file_pop select').bind('change', function(){
		var value = this.value;
		
		var ss = [];
		var checkall = true;
		if (value == 0){ //推荐
			ss = ['.rp','.dat'];
		} else if (value == 1){ //音频
			checkall = false;
			ss = ['.wav','.midi','.aac','.ape','.amr','.mp3','.ac3','.dts','.m4a'];
		} else if (value == 2){ //所有
			ss = [];
		} else if (value == 3){ //视频
			ss = ['.wav','.midi','.aac','.ape','.amr','.mp3','.ac3','.dts','.m4a'];
		} else if (value == 4){ //自定义
			return false;
		}

		var check = true;

		for (var p in objs ){
			objs[p].checked = checkall;
		}

		if (checkall){
			check = false;
		}

		each(ss,function(s,i){
			try{objs[s].checked = check;}catch(e){try{console.log(s);}catch(e){}}
		});

		for (var p in tabs){
			checkTabs(tabs[p],p);
		}
	});

	//确定
	$(".file_pop .sure_btn").click(function(evt){
		//确认设置
		var ss = [];
		for(var p in objs){
			ss.push('{\\"suffix\\":\\"'+p+'\\",\\"link\\":'+((objs[p].checked)? 1:0)+'}');
		}

		var optval = '{\\"file\\":['+ss.join(",")+']}';

		clientCommon.call(function(api,optval){
			try{
				var OptClt = external.GetObject("@pplive.com/options;1");
				OptClt.SetValue('opt.file',optval);
			}catch(e){}
		},[optval]);
		evt.preventDefault();
		$(".file_pop").hide();
		Utils.ShowTips('设置已保存！',2000,0);
	});
	$(".file_pop .cancel_btn").click(function(evt){
		evt.preventDefault();
		$(".file_pop").hide();
	});
	init();
	$('.file_pop select').val(checkVal());
	$('.file_pop select').change();

	for (var p in tabs){
		checkTabs(tabs[p],p);
	}

	return {
		init:init
	};

})(Utils);
function isExistSelect(objSelect, objItemValue){
	var isExit = false;
    for (var i = 0; i < objSelect.options.length; i++) {
        if (objSelect.options[i].value == objItemValue) {
            isExit = true;
            break;
        }
    }
    return isExit;
}

function addItemToSelect(objSelect, objItemText, objItemValue) {
    //判断是否存在
    if (isExistSelect(objSelect, objItemValue)) {
        return;
    } else {
        var varItem = new Option(objItemText, objItemValue);
        objSelect.options.add(varItem);
    }
}
