function loadMusicData(type) {
	$('.operaterefresh li').removeClass().addClass('refreshing');
	$.getJSON('Music/Json?now=' + new Date().getTime() + '&type=' + type, function(result) {
		$.each(result, appendListItems(type, result));
	})
}

function appendListItems(type, data) {
	if (data.custom.length > 0) {
		if (type != 'Favorite' && type != 'Recordings')
			$('.playListCustomTitle').show();

		for (var i = 0; i < data.custom.length; i++) {
			var str = '<table class="playListTableCon" width="100%" border="0" cellpadding="0" cellspacing="0"><tbody class="playListTbody"><tr>';
			str += getFormateString(data.custom[i], 'custom')
			$('td.playListCustomParent').append(str);
		}
		if (type == 'Favorite' || type == 'Recordings') {
			$('.playListTableCon td').css('padding-left', '5px');
			$('.ckMusicItem').css('padding-left', '8px');
		}
	} else {
		$('.playListCustomTitle').hide();
	}
	//if (type != 'IsMusic' && type != 'Favorite' && type !='Recordings' && data.system.length > 0)
	if (type != 'Favorite' && type != 'Recordings' && data.system.length > 0) {
		$('.playListSystemTitle').show()
		for (var i = 0; i < data.system.length; i++) {
			var str = '<table class="playListTableCon" width="100%" border="0" cellpadding="0" cellspacing="0"><tbody class="playListTbody"><tr>';
			str += getFormateString(data.system[i], 'system')
			$('td.playListSystemParent').append(str);
		}
		if (type == 'Favorite' || type == 'Recordings') {
			$('.playListTableCon td').css('padding-left', '5px');

		}
	} else {
		$('.playListSystemTitle').hide()
	}
	if (data.finished) {
		$('.operaterefresh li').removeClass().addClass('refresh');
	}
	doDataInit();

}

var changeFlag;
var audioObj;

function getFormateString(data, type) {
	var str = '<td width="5%" id="ckMusicID" class="ckMusicItem"><input name="musicCheck" type="checkbox" class="allCheck" index="' + data.MusicID + '"/><span class="showCheck"></span></td>';
	if (type == 'custom') {
		if (data.IsFavorite) {
			str += '<td width="5%" id="favoriteID"><span class="favorites selected"></span></td>';
		} else {
			str += '<td width="5%" id="favoriteID"><span class="favorites"></span></td>';
		}
	} else {
		str += '<td width="5%"></td>';
	}
	var listArr = ['IsRingtone', 'IsNotification', 'IsAlarm'];
	if (data.DefaultType != -1 && $.inArray(loadType, listArr) != -1) {
		if (data.DefaultType == 1) {
			str += '<td width="5%" id ="defaultRingID"><span class="defaultRing call"></span></td>';
		} else if (data.DefaultType == 2) {
			str += '<td width="5%" id ="defaultRingID"><span  class="defaultRing bell"></span></td>';
		} else if (data.DefaultType == 4) {
			str += '<td width="5%" id ="defaultRingID"><span  class="defaultRing clock"></span></td>';
		}
	} else {
		str += '<td width="5%" class="defaultRing"></td>';
	}
	str += '<td width="25%"><span class="naming" rel="' + data.Path + '">';
	var tempstr = data.Path;
	indexLast = tempstr.lastIndexOf('/');
	filename = data.filename;
	if (indexLast != -1)
	{
		filename = tempstr.substr(indexLast + 1)
	}
	
	str += filename;
	str +='<wbr>';
	str += '</span></td>';

	//str += '<td width="10%">';
	if (1) {
		str += '<td width="10%"><span class="play"><img src="/static/imgs/play.gif" /></span><span class="pause"><img src="/static/imgs/playing.gif" />&nbsp;<img src="/static/imgs/pause.gif" /></span><span class="loading"><img src="/static/imgs/loading.gif" style="width:16px; height:16px"/></span></td>';
	}
	str += '<td width="10%">'
	str += data.Time + '</td>';
	str += '<td width="15%">' + data.Artist + '</td>';
	str += '<td width="25%">' + data.Album + '</td>';
	str += '</tbody></tr></table>';
	return str;
}

//function getMusicStatus(){
//	showPlayOrPause();
//	timer = setTimeout("getMusicStatus()", 5000);
//}
function showPlayOrPause() {
	//
	$("#HP").attr("state",0);
	initPage();
	if (true) {
		$('.playListTableCon.hover span.play').show();
		
		//$('span.play').show();
	} else {
	}

	//$(this).siblings('.pause').show();
}


function OnDSPlayStateChangeEvt(state) {
	if (8 == state) {
		showPlayOrPause();
	}
}


$(document).ready(function() {

	//$('#niftyplayer').bind('ended', function() {
	//	showPlayOrPause();
	//});
	

	$('.wrapAuto').height($(window).height() - 70);
	$(window).resize(function() {
		$('.wrapAuto').height($(window).height() - 70);
	})
	if (connectState == "False") {
		return;
	}
	var listArr = ['IsRingtone', 'IsNotification', 'IsAlarm'];
	if ($.inArray(loadType, listArr) != -1) {
		$("#liExpo").hide();
		$("#liDelete").hide();
	}
	loadMusicData(loadType)

	//添加音乐
	$("#addMusic").click(function() {

		$.post("/Music/AddMusic", "", function() {
		});

		/**art.dialog({
		 title: '添加yige音乐文件',
		 content: $("#addMusicFile")[0],
		 background:'#fff',
		 opacity: 0.7,
		 lock: true,
		 ok: function(){
		 var fileName = $("#addMusicFile input[type=file]").val();
		 var data = {};
		 data.file = fileName;
		 //提交数据
		 $.post("/Music/Add",data,function(){

		 })
		 },
		 cancel: true
		 })**/
	})

	$('.showCheck').live('click', function() {
		var len = $("input[name = musicCheck]").length;
		//复制个数
		var subListLen = $(this).parents('#listParent').find(':checkbox').length;
		var parobj = $(this).parents('#listParent').parent('tr').siblings('tr').find('.selectAll');
		if ($(this).hasClass("showCheckSe")) {
			$(this).removeClass("showCheckSe");
			$(this).siblings(':checkbox')[0].checked = false;
			changeFlag();
			if (parobj.children('a').hasClass("selected")) {
				parobj.children('a').removeClass("selected");
				parobj.children('input').checked = false;
			}
			if ($(".showAllCheck").hasClass("showCheckSe")) {
				$(".showAllCheck").removeClass("showCheckSe");
				$("#musicCheck")[0].checked = false;
			}
		} else {
			$(this).addClass("showCheckSe");
			$(this).siblings(':checkbox')[0].checked = true;
			var cksubListLen = $(this).parents('#listParent').find('input:checked[name = musicCheck]').length;
			changeFlag();
			if (len == checkedLen) {
				$(".showAllCheck").addClass("showCheckSe");
				$("#musicCheck")[0].checked = true;
			}
			if (subListLen == cksubListLen) {
				parobj.children('a').addClass("selected");
				parobj.children('input').checked = true;
			}
		}
	})
	changeFlag = function() {
		checkedLen = $("input:checked[name = musicCheck]").length;
		//已复制个?
		setRingFlag = checkedLen == 1 ? true : false;
		listFlag = checkedLen == 0 ? false : true;
		sysLen = $("#system input:checked[name = musicCheck]").length;
		delFlag = (sysLen == 0 && checkedLen != 0) ? true : false;
		if (sysLen != 0) {
			if (loadType != 'IsMusic') {
				$("#ringList2 a").filter(function() {
					return $(this).attr("ringType") != loadType;
				}).hide();
			}
		} else {
			$("#ringList2 a").show();
		}
		if (delFlag) {
			$('.operateUl li[rel=needDel]').removeClass('disabled');
		} else {
			$('.operateUl li[rel=needDel]').removeClass().addClass('disabled');
		}
		if (setRingFlag) {
			$('.operateUl li[rel=needRing]').removeClass('disabled');
		} else {
			$('.operateUl li[rel=needRing]').removeClass().addClass('disabled');
		}
	}
	//全部操作
	$('.showAllCheck').click(function() {
		setRingFlag = false;
		if ($(this).hasClass("showCheckSe")) {
			listFlag = false;
			delFlag = false;
			$(this).removeClass("showCheckSe");
			$('.selectAll a').removeClass("selected");
			$('.selectAll input').checked = false;
			$('.showCheck').each(function() {
				$(this).removeClass("showCheckSe");
				$(this).siblings(':checkbox')[0].checked = false;
			})
		} else {
			listFlag = true;
			$(this).addClass("showCheckSe");
			$('.selectAll a').addClass("selected");
			$('.selectAll input').checked = true;
			$('.showCheck').each(function() {
				$(this).addClass("showCheckSe");
				$(this).siblings(':checkbox')[0].checked = true;
			})
			//checkedLen = $("input:checked[name = musicCheck]").length;
			//sysLen = $("#system input:checked[name=musicCheck]").length;
			//delFlag = (sysLen == 0 && checkedLen != 0) ? true : false;
		}
		changeFlag();
	})
	$('.operateUl li').hover(function() {
		if (($(this).attr('rel') == "needList" && !listFlag) || ($(this).attr('rel') == "needDel" && !delFlag) || ($(this).attr('rel') == "needRing" && !setRingFlag))
			return false;
		$(this).addClass('hover').siblings().removeClass('hover');
	}, function() {
		$(this).removeClass('hover');
	}).mousedown(function() {
		if (($(this).attr('rel') == "needList" && !listFlag) || ($(this).attr('rel') == "needDel" && !delFlag) || ($(this).attr('rel') == "needRing" && !setRingFlag))
			return false;
		$(this).removeClass('hover').addClass('down');
	}).mouseup(function() {
		if (($(this).attr('rel') == "needList" && !listFlag) || ($(this).attr('rel') == "needDel" && !delFlag) || ($(this).attr('rel') == "needRing" && !setRingFlag))
			return false;
		$(this).removeClass('down');
	})

	$('.playListTableCon').live('hover', function() {
		if ($(this).hasClass('hover')) {
			$(this).removeClass('hover').find('span[class = play]').filter(function() {
				return $(this).attr("rel") == "play";
			}).hide();
		} else {
			$(this).addClass('hover').find('span[class = play]').filter(function() {
				return $(this).siblings('.pause').css('display') == "none";

			}).show();
		}
	})

	$('.operaterefresh li').hover(function() {
		$(this).addClass('hover').siblings().removeClass('hover');
	}, function() {
		$(this).removeClass('hover');
	}).mousedown(function() {
		$(this).removeClass('hover').addClass('down');
	}).mouseup(function() {
		$(this).removeClass('down');
	})
	//播放列表
	$("#playingList").click(function() {
		if (!listFlag)
			return false;
	})
	//删除
	$("#delete").click(function() {
		if (!delFlag)
			return false;
		art.dialog({
			title : WEBSMS_DEL_SMS,
			content : WEBSMS_DEL_SMS_OR_NOT,
			okVal : PB_BUTTON_OK,
			cancelVal : PBMainView_WEB_CANCEL,
			icon : 'question',
			background : '#fff',
			opacity : 0.7,
			lock : true,
			ok : function() {
				var data = {};
				data.indexes = [];
				data.type = loadType
				var delArr = $("#music input:checked");
				$(delArr).each(function(i, n) {
					data.indexes.push($(this).attr("index"));
				})
				//提交数据
				$.post("/Music/Del", data, function() {

				}, "json")
			},
			cancel : true
		})
	})
	//设为铃声
	$("#ringList2 a").click(function() {
		if (!setRingFlag)
			return false;
		var data = {};
		data.id = $(this).attr("rel");
		data.indexes = $("input:checked[name=musicCheck]").attr("index");
		$.post("/Music/SetAlarm", data, function(result) {
			if (result.result == 'Success') {

			}
		})
	})
	//收藏
	var favFlag = true;
	$('.playListTableCon .favorites').live('click', function() {
		if (!favFlag)
			return;
		favFlag = false;
		var that = $(this);
		var data = {};
		var haveClass = $(this).hasClass('selected');
		data.operation = $(this).hasClass('selected') ? "remove" : "add";
		data.index = $(this).parent().siblings("td:eq(0)").find("input").attr("index");
		$(this).removeClass('selected').addClass("loading");
		$.post("/Music/Favorite", data, function(result) {
			that.removeClass('loading');
			if (haveClass && result.result == 'Success') {
				that.removeClass('selected');
			} else {
				if (result.result == 'Success')
					that.addClass('selected');
			}
			favFlag = true;
		})
	})
	//刷新
	$("#refresh").click(function() {
		$(this).removeClass().addClass('refreshing');
		$.post("/Music/Refresh", "", function() {
		})
	})
	//搜索
	$("#musicSer").bind('keyup', function() {
		var valKey = $(this).val();
		var data = {};
		data.val = valKey;
		data.type = loadType;
		$.post("/Music/Search", data, function(result) {
			$('td.playListCustomParent').empty();
			$('td.playListSystemParent').empty();
			$.each(result, appendListItems(loadType, result));
		})
	})
	//导出
	$("#expo").click(function() {
		if (!delFlag)
			return false;
		var data = {};
		data.indexes = [];
		data.type = loadType;
		var delArr = $("#music input:checked");
		$(delArr).each(function(i, n) {
			data.indexes.push($(this).attr("index"));
		})
		//提交数据
		$.post("/Music/Expo", data, function() {

		}, "json")
	})

	$('.selectAll a').hover(function() {
		$(this).addClass('hover')
	}, function() {
		$(this).removeClass('hover')
	})

	$('.selectAll a').live('click', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');

			$(this).parents('tr').siblings('tr').find('#ckMusicID').each(function() {
				$(this).children('.showCheck').removeClass("showCheckSe");
				$(this).children('.allCheck')[0].checked = false;
				if ($(".showAllCheck").hasClass("showCheckSe")) {
					$(".showAllCheck").removeClass("showCheckSe");
					$("#musicCheck")[0].checked = false;
				}

			})
			changeFlag();
		} else {
			$(this).addClass('selected');
			$(this).parents('tr').siblings('tr').find('#ckMusicID').each(function() {
				$(this).children('.showCheck').addClass("showCheckSe");
				$(this).children('.allCheck')[0].checked = true;
			});

			var ckLen = $("input:checked[name = musicCheck]").length;
			var len = $("input[name = musicCheck]").length;
			if (len == ckLen) {
				$(".showAllCheck").addClass("showCheckSe");
				$("#musicCheck")[0].checked = true;
			}
			changeFlag();
		}
	})
})
function initPage() {
	$("span.play,span.pause,span.loading").hide();
	$("span.play").attr("rel", "play");
	var hpindex = $("#HP").attr("index");
	var tempstr = "index=" +hpindex;
	if(hpindex != "")
	{
		var sets = $(".ckMusicItem input[" + tempstr + "]");
		if(sets.length && $("#HP").attr("state") != 0)
		{
			if($("#HP").attr("state") == 1)
			{
				sets.parent().siblings('td:eq(3)').find('span.pause').show();
				sets.parent().siblings('td:eq(3)').find('span.play').attr("rel","play");
			}
			else
			{
				sets.parent().siblings('td:eq(3)').find('span.play').show();
				sets.parent().siblings('td:eq(3)').find('span.play').attr("rel","pause");
			}
			
		}
		
	}
	
	/*if(loadType != 'IsMusic' && loadType != 'Favorite')
	 {
	 $('.favorites').removeClass('favorites');
	 }*/
	if ($('.showAllCheck').hasClass("showCheckSe")) {
		$('.showCheck').each(function() {
			$(this).addClass("showCheckSe");
			$(this).siblings(':checkbox')[0].checked = true;
		})
		changeFlag();
	}
	changeFlag();
}

function playMusic(that, data) {
	$.post("/Music/getPath", data, function(json) {
		if (json.path == "//") {
			var aud = audioObj;
			if( aud != undefined)
			{
			aud.pause();
			aud.src = "";
			}

			initPage();
			playing = false;
			alert(WebMusic_FileLoadFailed);
		} else if (json.path) {
			playing = false;
			$(that).siblings('.loading').hide().siblings('.pause').show();
			var wmp = document.getElementById('wmplayer');
			var aud = audioObj;
			try{
				wmp.controls.stop();
			}catch(e){
				
			}
			if(aud != undefined)
			{
				aud.pause();
				try {
				aud.currentTime = 0;
				}catch(e){
					
				}
			} 
			if (IsChrome() && json.path.toLowerCase().lastIndexOf('.mp3')!= -1) {
				
				wmp.URL = json.path;
				wmp.controls.play();
			} else {
				
				//if( aud.src.search(json.path) == -1){
				//aud.src = json.path;
				//WaitTime(2,3);
				//aud.load();
				audioObj = document.createElement("audio");
				audioObj.addEventListener('canplaythrough', myAutoPlay, false)
				audioObj.addEventListener('ended', showPlayOrPause, false);
				audioObj.src = json.path;
				audioObj.load();
				//audio.play();
			}
			$("#HP").attr("state", 1);
	
		} else {
			setTimeout(function() {
				playMusic(that, data);
			}, 500);
		}
	})
}


function GetCurrentTimeSeconds() {

	var d = new Date();

	var hour = d.getHours();

	var minute = d.getMinutes();

	var second = d.getSeconds();

	return hour * 60 * 60 + minute * 60 + second;
}

function WaitTime(sec, timeout) {

	var startPos = GetCurrentTimeSeconds();

	var pass;
	while (true) {
		pass = GetCurrentTimeSeconds() - startPos;

		if (pass >= sec) {
			break;
		}
		if (pass >= timeout) {
			break;
		}
	}
}

function myAutoPlay()
{
	audioObj.play();
}

function audioCanPlay(url, obj) {
	if(url.toLowerCase().lastIndexOf('.mp3') != -1 && obj.canPlayType("audio/mpeg")){
		return true;
	}else if(url.toLowerCase().lastIndexOf('.ogg') != -1 && obj.canPlayType("audio/ogg")){
		return true;
	}else if(url.toLowerCase().lastIndexOf('.wav') != -1 && obj.canPlayType("audio/wav")){
		return true;
	}
	return false;
}

function IsChrome(){
	var browserName = navigator.userAgent.toLowerCase();
	 if(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)){
	 	return true;
	 }
	 return false;
}


function doPlay(obj){
	playing = true;
	var data = {};
	data.path = obj.parent('td').siblings('td:eq(0)').find('input').attr('index');
	$("#HP").attr("index", data.path);
	var that = obj;
	initPage();
	obj.siblings('.loading').show();
	playMusic(that, data);
}

var playing = false;
function doDataInit() {
	initPage();
	$("span.play").click(function(){
		if(playing)return;
		$("#HP").attr("state",0);
		var url = $(this).parent('td').siblings('td:eq(3)').find('span').attr('rel');
		var that = $(this)
		if(IsChrome() && url.toLowerCase().lastIndexOf('.mp3') != -1){
			var wmp = document.getElementById('wmplayer');
			if(wmp.playState == 2 && ($(this).attr('rel') == "pause")){
				wmp.controls.play();	
				initPage();
				$(this).siblings('.pause').show();
				$("#HP").attr("state",1);
			}else{
				doPlay(that);
			}
			
		}
		else {
			//aud = document.getElementById('niftyplayer');
			if(audioObj == undefined)
			{
			aud = new Audio("");
			}
			else
			{
				aud = audioObj;
			}
			if (!audioCanPlay(url, aud)) {
				var data = {};
				data.Message = "WebMusic_FileTypeNotCorrect";
				$.post("/Music/ShowMessage", data, function() {

				}, "json")
				return false;
			}
			if (url == "" || url.lastIndexOf('.') == -1) {
				var data = {};
				data.Message = "WebMusic_FileTypeNotCorrect2";
				$.post("/Music/ShowMessage", data, function() {

				}, "json")
				return false;
			}
			if (aud.paused && ($(this).attr('rel') == "pause")) {
				aud.play();
				initPage();
				$(this).siblings('.pause').show();
				$("#HP").attr("state",1);
			} else {
				doPlay(that);
			}
		}

		//getMusicStatus();
	})
	$("span.pause").click(function(){
		var url = $(this).parent('td').siblings('td:eq(3)').find('span').attr('rel');
		
		if(IsChrome() && url.toLowerCase().lastIndexOf('.mp3')!= -1){
			var wmp = document.getElementById('wmplayer');
			wmp.controls.pause();
		}
		else {
			//var aud = document.getElementById('niftyplayer');
			audioObj.pause();
		}
		$("#HP").attr("state",2);
		$(this).hide();
		$("span.play").attr("rel", "play");
		$(this).siblings('.play').attr("rel", "pause").show();
	})
}
