﻿// Autosuggestion for Find Committees
var oTextbox;
function CreateFindCom() {
	oTextbox = new AutoSuggestControl(document.getElementById("search"), new AllComSuggestions());
}

//Know the LegCo -- Start
var know_displaying=0;
var knowTime;
var knowPause=false;

function changeKnow(knowId) {
	if (document.getElementById("knowBanner") != null)
		document.getElementById("knowBanner").src=knowImage[knowId];
	if (document.getElementById("knowLink") != null)
		document.getElementById("knowLink").href=knowLink[knowId];
	if (document.getElementById("knowtitle") != null)
		document.getElementById("knowtitle").innerHTML=knowTitle[knowId];

	for (var i=0; i<knowImage.length; i++) {
		if (document.getElementById("know"+i) != null) {
			if (knowId == i) {
				document.getElementById("know"+i).src="skin/1/images/chinese/main/p_dot_on.gif";
			} else {
				document.getElementById("know"+i).src="skin/1/images/chinese/main/p_dot_off.gif";
			}
		}
	}
	know_displaying=knowId;
}

function imageChangerK() {
	if (knowPause == false) {
		changeKnow(know_displaying);
		know_displaying++;
		if (know_displaying>=knowImage.length) know_displaying = 0;
	}
	knowTime = setTimeout("imageChangerK()", 15000);
}

function initKnow() {
	document.write('<a href="'+knowLink[0]+'" id="knowLink"><img border="0" height="160" id="knowBanner" onmouseout="knowPause=false;" onmouseover="knowPause=true;" src="'+knowImage[0]+'" width="100%" alt=""/></a><br>');
	document.write('<div id="knowtitle" style="line-height:14px;background-color:white;margin:0px 1px;padding-top:3px;padding-left:3px;padding-right:3px;padding-bottom:3px;height:20px;color:black;font-size:16px;text-decoration:none;text-align:center;">'+knowTitle[0]+'</div>');
	document.write('<table align="center" border="0" cellpadding="2" cellspacing="0">');
	document.write('<tr>');
	for (var i=0; i<knowLink.length; i++) {
		var on_or_off_dot = (i==0) ? "p_dot_on.gif" : "p_dot_off.gif";
		if (i < knowLink.length -1) {
			document.write('<td><a href="#" onmouseout="imageChangerK();" onmouseover="changeKnow('+i+');clearTimeout(knowTime);"><img id="know'+i+'" src="skin/1/images/chinese/main/'+on_or_off_dot+'" width="11" height="11" border="0" alt=""/></a>&nbsp;</td>');
		} else {
			document.write('<td><a href="#" onmouseout="imageChangerK();" onmouseover="changeKnow('+i+');clearTimeout(knowTime);"><img id="know'+i+'" src="skin/1/images/chinese/main/'+on_or_off_dot+'" width="11" height="11" border="0" alt=""/></a></td>');
		}
	}	
	document.write('</tr>');
	document.write('</table>');
}
//Know the LegCo -- End

//Flash banners -- Start
var promotionTime;
//default prom_displaying=0 (count from 0), prom_zone=1 (count from 1 to 3) for showing the first banner in the first zone
//var prom_displaying=0;
//var prom_zone=1;
var prom_zone=3;	    //to show third zone (Topics of the week)
var prom_displaying=4;  //to show 5th banner first
var promPause=false;

function changeBanner2(imgFile,imglink,altText){
	if(document.getElementById("promotionBanner") != null)
	{
		document.getElementById("promotionBanner").src=imgFile;
		document.getElementById("promotionBanner").title=altText;
	}
	if(document.getElementById("bannerLink") != null)
		document.getElementById("bannerLink").href=imglink;
}

function changeBack(){
	for (var i=1; i<=3; i++) {
		document.getElementById("promotion"+i).className='onout1';
	}
}

function promotionPlaceBanner(zone) {
	var img_arr = eval("promotionImage" + zone);
	for (var i = 0; i<img_arr.length; i++) {
		document.write('<a class="promo" href="#" onmouseout="promPause=false;" onmouseover="promotionRowMouseOver(document.getElementById(\'promotion'+zone+'\'),'+i+')">'+(i+1)+'</a>&nbsp;');
	}
}

function promotionBannerChanger(promotionImg,promotionLink,promotionAlt,num){
	if (promPause == false) {
		if (prom_zone!=num){
			prom_displaying=0;
			prom_zone=parseInt(num,10);
		}
		changeBanner2(promotionImg[prom_displaying],promotionLink[prom_displaying],promotionAlt[prom_displaying]);
		prom_displaying++;
		if (prom_displaying>promotionImg.length){
			prom_displaying=0;
			var next_zone = parseInt(num,10) + 1;
			if (next_zone > 3) next_zone = 1;
			var next_row = document.getElementById("promotion" + next_zone);
			promotionRowMouseClick(next_row);
			num = next_zone;
		}
	}
	clearTimeout(promotionTime);
	if(num==1)
		promotionTime=setTimeout("promotionBannerChanger(promotionImage1,promotionLink1,promotionAlt1,'1')",15000);
	else if(num==2)
		promotionTime=setTimeout("promotionBannerChanger(promotionImage2,promotionLink2,promotionAlt2,'2')",15000);
	else if(num==3)
		promotionTime=setTimeout("promotionBannerChanger(promotionImage3,promotionLink3,promotionAlt3,'3')",15000);
}

function promotionRowMouseClick(row) {
	var rowNum
	rowNum=row.id.replace('promotion','')

	changeBack();
	row.className='onover1';
	promotionBannerChanger(eval('{' + "promotionImage" + rowNum + '}'),eval('{' + "promotionLink" + rowNum + '}'),eval('{' + "promotionAlt" + rowNum + '}'),rowNum);
}

function promotionRowMouseOver(row, key) {
	var rowNum
	rowNum=row.id.replace('promotion','')

	changeBanner2(eval('{' + "promotionImage" + rowNum + '}')[key],eval('{' + "promotionLink" + rowNum + '}')[key],eval('{' + "promotionAlt" + rowNum + '}')[key]);
	//clearTimeout(promotionTime);
	promPause = true;
}
//Promotion flash banners -- End

//Calendar -- Start
var weekDay=new Array("日","一","二","三","四","五","六");
var monthName=new Array("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月");

var previousDate="";
function selectSchedule(date2){
	if(document.getElementById(previousDate)!=null){
		document.getElementById(previousDate).style.backgroundColor="#f4f4f4";
	}
	previousDate=date2;
	document.getElementById(date2).style.backgroundColor ="lightblue";
}

var scheduleList=new Array();
var scheduleListIndex = {};

function initSchedule(){
    //1st entry point
  	$.ajax({
  		type: "GET",
  		url: "xml/schedule.xml",
  		dataType: "xml",
  		success: function(xml) {
			$('DetailSchedule', xml).each(function(){
				var s =new schedule();

				var date = new Date($('Date', this).text().replace(/-/g,"/"));
				s.date=date;

				if ( !$('Show_StartTime', this) || $('Show_StartTime', this).text() != 'N')
					s.time = $('Time', this).text();
				else
					s.time = "";

				s.time_for_sort = $('Time', this).text();

				$('Venue', this).each(function(){
					s.venue = $('CH', this).text();
				});
					
				$('Subject', this).each(function(){
					s.subject = $('CH', this).text();
				});

				$('Agenda_Path', this).each(function(){
					s.agenda_Path = $('Ch_Url', this).text();
				});
				
				if (s.agenda_Path != "") s.agenda_Path = s.agenda_Path.replace(new RegExp("http:\/\/www.legco.gov.hk\/", "gi"), '\/');

				s.meettype = $('ChiMeetType', this).text();

				if ((s.meettype == "閉門會議") || (s.agenda_Path == "")){
					$('Committees', this).each(function(){
						$('Committee', this).each(function(){
							s.agenda_Path = $('Ch_Url', this).text();
						});
					});
				}

				scheduleList.push(s);
			})

			var prevdate = new Date(1980, 0, 1);
			for (var i=0; i<scheduleList.length; i++) {
				if (formatDate(prevdate) != formatDate(scheduleList[i].date)) {
					scheduleListIndex[scheduleList[i].date] = i;
					prevdate = scheduleList[i].date;
				}	
			}
			
			//2nd entry point
			initHoliday();
		}
  	});
}

function separateTime(time){
	t=time.split(":")
	times=t[0]*60
	times+=t[1]*1;

	return times;
}

var holidayList=new Array();
function initHoliday(){
	$.ajax({
		type: "GET",
		url: "xml/holiday.xml",
		dataType: "xml",
		success: function(xml) {
			$('Holiday', xml).each(function(){
				var holiday = new Date($(this).text().replace(/-/g,"/"));
				holidayList.push(holiday);
			});

			//3rd entry point
			init();
        }
  	});
}

function schedule(){
	this.date;
	this.time;
	this.venue;
	this.subject;
	this.agenda_path;
	this.getSchedule=function(){
		var venue_desc = "";
		var meettype_desc = "";
		if (this.venue != "") venue_desc = " ("+this.venue+")";
		if (this.meettype == "閉門會議") meettype_desc = " ("+this.meettype+")";
		if (this.agenda_Path == "") {
			return "<tr>"+
					"<td valign='top'><span class='purple_title2'>"+ this.time + venue_desc + meettype_desc + "<br/>"+
					"</span><span class='content'>"+this.subject +"</span></td>"+
				"</tr>";
		} else {
			return "<tr>"+
					"<td valign='top'><span class='purple_title2'>"+ this.time + venue_desc + meettype_desc + "<br/>"+
					"</span><span class='content'>"+this.subject +"<a href='"+this.agenda_Path +"' class='orange_link' target='_agendawin'>...<b>&rsaquo;&rsaquo;</b></a></span></td>"+
				"</tr>";
		}
	}
}

function daysInFebruary (year){
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function formatDate(inputdate){
	var mth = "" + (inputdate.getMonth() + 1);
	var day = "" + inputdate.getDate();
	if (mth.length == 1) mth = "0" + mth;
	if (day.length == 1) day = "0" + day;
	return "" + inputdate.getFullYear() + "/" + mth + "/" + day;
}

function calendar(){
	this.styleClass;
	this.dateC;
	this.titleC;
}

function calendarM(cal){
	var year=cal.getFullYear();
	var today = new Date();
	var monthDay=new Array (31, daysInFebruary (year),31,30,31,30,31,31,30,31,30,31);
	var mthStart = new Date(year,cal.getMonth(),1);
	var minDate = mthStart.getDay();
	var numOfWeek=(monthDay[cal.getMonth()]+minDate)/7;
	var maxDate=monthDay[cal.getMonth()]+minDate;
	var calendarContent=new Array();
	for (i=0;i<numOfWeek;i++){
		for (j=0;j<7;j++){
			if(i*7+j<minDate||i*7+j>=maxDate){
				calendarContent.push(new calendar());
			} else {
				var c=new calendar();
				var count=0;
				c.dateC=new Date(cal.getFullYear(), cal.getMonth(), i*7+j-minDate+1);
				for (l=scheduleListIndex[c.dateC]; l<scheduleList.length; l++){
					if(c.dateC-scheduleList[l].date==0){
						count++;
					} else break;
				}
				if (count>0){
					c.titleC =count+ " 個會議";
					c.styleClass = "cal_day";
				} else {
					c.titleC = "沒有公開或閉門會議";
					c.styleClass = "cal_day";
				}
				if (j==0){
					c.styleClass = "cal_day_hol";
				} else {
					for (o=0;o<holidayList.length;o++){
						if (c.dateC-holidayList[o]==0){
							c.styleClass = "cal_day_hol";
						}
					}
				}
				calendarContent.push(c);
			}
		}
	}
	return calendarContent;
}

function viewCalendar(dateString){
	var myDate = new Date(dateString);
 	var year=myDate.getFullYear();
 	if (myDate.getMonth()>=10) year++;
	var monthDay=new Array(31, daysInFebruary (year),31,30,31,30,31,31,30,31,30,31);
	var myMonth=monthDay[myDate.getMonth()];

	var content= "<tbody><tr><td colspan='7' class='cal_wk_head'>";
 	for(i=0;i<3;i++){
 		var now=new Date();
		now.setDate(1);
		if(now.getMonth()+i>11){
			now.setFullYear(now.getFullYear()+1);
			now.setMonth(now.getMonth()+i-12);
		}else{
 			now.setMonth(now.getMonth()+i);
 		}
		now.setDate(1);
 		this.dateS=formatDate(now);
		var style=(myDate.getMonth()==now.getMonth())?'cal_mhighlight':'';
		content+="&nbsp;<a href='javascript:viewCalendar("+'"'+dateS+'"'+")' class='"+style+"'>"+monthName[now.getMonth()]+"</a>&nbsp;";
 	}
 	content+="</td></tr>";
	
	content+="<tr>";
 	for(i=0;i<weekDay.length;i++){
 		content+="<td width='14%' class='cal_wk_head'>"+weekDay[i]+"</td>"
 	}
	content+="</tr>";
	
	var calendarView=calendarM(myDate);
	var today = new Date();
	today.setHours(0,0,0,0);
	var numOfWeek = calendarView.length / 7;
	for (i=0;i<numOfWeek;i++){
		content+="<tr>";
		for (j=0;j<7;j++){
			if (calendarView[i*7+j] && calendarView[i*7+j].dateC){
				var compareDate = new Date(calendarView[i*7+j].dateC);
				compareDate.setHours(0,0,0,0);
				if (today.getTime() != compareDate.getTime()) {
					content +="<td id='date"+formatDate(calendarView[i*7+j].dateC)+"' "
							+ "class='" + calendarView[i*7+j].styleClass+ " handcursor' "
							+ "onMouseOver='chgCalBGColor(this, \"turquoise\")' onMouseOut='chgCalBGColor(this, \"#f4f4f4\")' "
							+ "onClick='javascript:viewdate("+'"'+calendarView[i*7+j].dateC +'"'+ "); "
							+ "javascript:selectSchedule("+'"date'+formatDate(calendarView[i*7+j].dateC)+'"'+" );' "
							+ "title='" + calendarView[i*7+j].titleC + "'>"
							+ calendarView[i*7+j].dateC.getDate()+ "</td>";
				} else {
					content +="<td id='date"+formatDate(calendarView[i*7+j].dateC)+"' "
							+ "class='" + calendarView[i*7+j].styleClass+ " handcursor' "
							+ "onMouseOver='chgCalBGColor(this, \"turquoise\")' onMouseOut='chgCalBGColor(this, \"#f4f4f4\")' "
							+ "onClick='javascript:viewdate("+'"'+calendarView[i*7+j].dateC +'"'+ "); "
							+ "javascript:selectSchedule("+'"date'+formatDate(calendarView[i*7+j].dateC)+'"'+" );' "
							+ "title='" + calendarView[i*7+j].titleC + "'>"
							+ "<span style='text-decoration:underline overline; font-weight:bold;'>" + calendarView[i*7+j].dateC.getDate()+ "</span></td>";
				}
			} else {
				content+="<td class='cal_day'>&nbsp;</td>";
			}
		}
		content+="</tr></tbody>";
	}
	$('#calendarTable').html(content);
	viewdate(dateString);
	selectSchedule('date' + dateString);
}

function chgCalBGColor(elm, color) {
	if (elm.style.backgroundColor != "lightblue") {
		elm.style.backgroundColor = color;
	}
}

function viewdate(dateString){
	 var myDate = new Date(dateString);
	 var count=0;
	 var content='<tbody>';

	for(i = scheduleListIndex[myDate]; i<scheduleList.length;i++){
		if(myDate-scheduleList[i].date==0){
			if(count!=0){
				 content+="<tr><td valign='middle'><img src='./skin/1/images/chinese/main/arrow_line.gif' width='260' height='5' alt=''></td></tr>";
			}
			count++;
			content+=scheduleList[i].getSchedule();
		} else break;
	}

	if (count<=0){
		content+="<tr><td valign='middle' align='center' class='content' width='310'>沒有公開或閉門會議</td></tr>";
	} else {
		content+="<tr><td valign='top' class='content'><span style='color:#006600'>歡迎公眾人士旁聽立法會及其委員會的公開會議。請致電中央預約熱線(852) 3919 3399，預留公眾席的座位。</span></td></tr>"
	}
	
	content+='</tbody>';
	$('#scheduleTable').html(content);
}
//Calendar -- End

//Invitation for Submission -- Start
function viewInvitation() {
	var i=0;
	var content="";
	
	for (i=0; i<invitationTitle.length;i++) {
		content+="<tr><td class='content_bullet' valign='top'>&#9632;</td>";
		content+="<td class='content' valign='top'><a href='" + invitationLink[i] + "'>";
		content+=invitationTitle[i] + "</a></td></tr>";
	}
	
	$('#tblinvitation').html(content);
}
//Invitation for Submission -- End

//The LegCo Reporter -- Start
function viewLegCoReporter() {
	$.ajax({
		type: "GET",
		url: "reporter/xml/legco_reporter.xml",
		dataType: "xml",
		success: function(xml) {
			var issue_id = "";
			var content = "";
			$('LegCo_Reporter', xml).each(function(){
				issue_id = $('issue_id', this).text();
				content = $('content_chi', this).text();
		    });

			var rpt = document.getElementById("container_reporter");
			if (rpt) {
				rpt.innerHTML = '<a align="left" href="http://app.legco.gov.hk/reporter/chinese/report.aspx?i=' + issue_id + '">' + content.replace("'", "\'") + '</a>';
			}
        }
  	});
}
//The LegCo Reporter -- End

//Feature -- Start
function viewFeature() {
	$.ajax({
		type: "GET",
		url: "xml/feature.xml",
		dataType: "xml",
		success: function(xml) {
			var title = "";
			var content = "";
			$('Feature', xml).each(function(){
				title = $('title_chi', this).text();
				content = $('content_chi', this).text();
		    });

			var ftitle = document.getElementById("feature_title");
			var fcontent = document.getElementById("feature_content");
			if (ftitle && fcontent) {
				ftitle.innerHTML = title;
				fcontent.innerHTML = content;
			}
        }
  	});
}
//Feature -- End

function init(){
	var now=new Date();
	var curDate = formatDate(now);
	viewCalendar(curDate);
    selectSchedule('date' + curDate);
	viewInvitation();
	viewLegCoReporter();
	viewFeature();
}

//For Mobile Redirection
function detectMobile()
{  
	try
	{
		if( navigator.userAgent.match(/Android/i) ||  navigator.userAgent.match(/webOS/i) ||  navigator.userAgent.match(/iPhone/i) ||  navigator.userAgent.match(/iPod/i) ||  navigator.userAgent.match(/BlackBerry/i) )
		{
			if($.cookie('mobile') == null)
			{
				location.replace("/mcindex.html");
			}
		} 
		
		if($.cookie('mobile') && $.cookie('mobile')=='true')
		{
			location.replace("/mcindex.html");
		}
	}catch(err){}

}

