var IsUseIE = (navigator.userAgent.toLowerCase().indexOf("ie") != -1);

/* menu use */
var HTML_HOME_URL = "home.htm";
var HTML_INTRODUCE_URL = "introduce.htm";
var HTML_MEMO_URL = "memo.htm";
var HTML_CLASSINTRO_URL = "classintro.htm";
var HTML_CLASSLINK_URL = "classlink.htm";
var HTML_TEACHERS_URL = "teachers.htm";
var HTML_FOOD_URL = "food.htm";
var HTML_FAMILY_URL = "family.htm";

var MenuHref = new Array();
var ArrayHtmlUrl = 
[
	HTML_HOME_URL, HTML_INTRODUCE_URL, HTML_MEMO_URL, HTML_CLASSINTRO_URL,
	HTML_TEACHERS_URL, HTML_CLASSLINK_URL, HTML_FOOD_URL, HTML_FAMILY_URL
];

/* init timer*/
var initTimer = 2500;

/* header images */ 
var HeaderImageBox;
var ActiveTimer = 8000;
var IsActiveChageImage = true;


/* news use */
var NewsBox;

/* student pic use */
var StudentPicBox;

$(document).ready(function(){

	var today = new Date();
	if (today.getMonth() == 11 && today.getDay() < 26){
		$('body').css('overflow-y', 'hidden').addClass('christmas_body');
		$('#bk').addClass('christmas_bk');
		$('#bk_left').addClass('christmas_left').delay(400).fadeIn('slow');
		$('#bk_right').addClass('christmas_right').delay(400).fadeIn('slow');

		initTimer += 1000;
	}
	else{
		$('#bk_left').delay(400).fadeIn('slow');
		$('#bk_right').delay(400).fadeIn('slow');

	}

	$('#menu a').each(function(i){
		MenuHref[i] = $(this).attr('href');
	});
	
	if (!($.fragment().page)){
		ShowHome();
	}

	var welcomeTop = (document.body.offsetHeight - $('#welcome').height()) / 2;
	$('#welcome').css({'top': welcomeTop.toString() + 'px'});
	
	if (IsUseIE)
		$('#welcome').fadeIn(0).delay(initTimer).fadeOut(0, AfterWelcome);
	else
		$('#welcome').fadeIn('slow').delay(initTimer).fadeOut('slow', AfterWelcome);
		
	
});

function AfterWelcome()
{
	$('#main').show('slide', { direction: 'up', easing: 'easeOutBack'}, 1500, function(){
		$('body').css('overflow-y', 'auto');
		setTimeout(function(){
			
			ShowHeaderImage();
			$('#headerZoon').click(function(){
				DisplayLightBox($(this).attr('display'));
			});
			
		},1000);
	});

}

$(window).resize(function(){
	if ($('#FullPictureBox:visible').size() > 0)
		DisplayLightBox();
});

function ShowHeaderImage(){
	$.getJSON("data/header.js", function(json){
		HeaderImageBox = json;
		
		//preload images
		
		$.each(json.HeaderImages, function(i, images){
			var preloadimage = $('<img />').attr('src', HeaderImageBox.HeaderImagePath + images.MinSrc);
			$('#preloadTemp').append(preloadimage);
		});
		
		HeaderImageBox.ImageIndex = HeaderImageBox.MainImage;
		
		DisplayActiveHeaderImages(HeaderImageBox.MainImage, true);
	});
	
}

function ShowAngel(){
	var randomNumber = Math.floor(Math.random() * 5) + 1;
	//background-image: url(../images/angelpic/angel1.png);
	$('#angelpic').attr('class', 'angelpic' + randomNumber.toString());
}


function OpenChurch(){
	window.open('http://www3.slpct.org.tw/');
}

function DisplayActiveHeaderImages(index, isStart){
	
	setTimeout(DisplayActiveHeaderImages, ActiveTimer);
	
	if (!IsActiveChageImage)
		return;
	
	var imageIndex = (index > 0) ? index : HeaderImageBox.ImageIndex + 1;
	imageIndex = (imageIndex > HeaderImageBox.HeaderImages.length) ? 1 : imageIndex;
	var imagePath = HeaderImageBox.HeaderImagePath + HeaderImageBox.HeaderImages[imageIndex - 1].MinSrc;
	var displayPath = HeaderImageBox.HeaderImagePath + HeaderImageBox.HeaderImages[imageIndex - 1].Src;
	
	if (!isStart){
		$('#headerPicBk').hide().css('background-image', 'url('+imagePath+')').fadeIn('slow');
	}
	$('#headerZoon').attr('display', displayPath);
	HeaderImageBox.ImageIndex = imageIndex;
}

function ShowHtmlUrl(url, index){
	$.get(url, function(data){
		$('#menu li a').removeClass();
		$('#menu li a:eq('+ index +')').addClass('menuSelected');
		$('#content').html(data);

		$('#content img.lightbox').css({cursor: 'pointer'}).click(function(){
			DisplayLightBox($(this).attr('display'));
		});
	});	
}

function ShowHome(){

	$.get(HTML_HOME_URL, function(data){
	
		$('#menu li a').removeClass();
		$('#menu .menuHome a').addClass('menuSelected');
		$('#content').html(data);
		
		DisplayNewsList();
		DisplayStudentPics();
	});
		
	
}

function DisplayNewsList(){

	$.getJSON("data/news.js?1001", function(json){
		  
		var sbforNews = new StringBuffer();
		sbforNews.append('<ul>');
		  
        var page = 0;
        $.each(json.News, function(i, news){
			var startdate = news.Cal.split('/');
			
			if (i % 14 == 0) page++;
			
			sbforNews.append('<li group="').append(page).append('">')
			         .append('<div class="dateBox"><span class="month">').append((startdate[0] < 10) ? '0' + startdate[0] : startdate[0])
				     .append('</span><span class="day">.').append((startdate[1] < 10) ? '0' + startdate[1] : startdate[1])
				     .append('</span><span class="monthText">').append(ConvertMonth(startdate[0]))
				     .append('</span></div><div class="dateText">').append(news.Title)
				     .append('</div>');
				     
			if (news.End != '')
			{
				var enddate = news.End.split('/');
				sbforNews.append('<div class="dateBox"><span class="month">').append((enddate[0] < 10) ? '0' + enddate[0] : enddate[0])
				         .append('</span><span class="day">.').append((enddate[1] < 10) ? '0' + enddate[1] : enddate[1])
				         .append('</span><span class="monthText">').append(ConvertMonth(enddate[0]))
				         .append('</span></div>');
			}
			
			sbforNews.append('</li>');
		});
          
		sbforNews.append('</ul>');
		$('#newsBody').html(sbforNews.toString());
		
		var thisPage = 0;
		var thisMonth = new Date().getMonth() + 1;
		var monthString = (thisMonth < 10 ) ? '0' + thisMonth.toString() : thisMonth.toString();
		$('#newsBody li').hide().each(function(index){
			
			if ($(this).find('.dateBox').size() == 1)
				$(this).find('.dateText').addClass('noEnddate');
				
			if ($(this).find('.month:eq(0):contains(' + monthString + ')').size() > 0)
			{
				$(this).find('.dateBox').addClass('thisMonth');
				$(this).find('.dateText').addClass('thisMonth');
				if (thisPage == 0)
					thisPage = $(this).attr('group');
			}
			
		});
		
		NewsBox = { size: json.News.length, maxpage: page, pageIndex: parseInt(thisPage)};
		
		var sbforNewsPages = new StringBuffer();
		sbforNewsPages.append('<ul>');
		for(var i=1; i <= NewsBox.maxpage; i++)
		{
			sbforNewsPages.append('<li group=' + i + '></li>');
		}
		sbforNewsPages.append('</ul>');
		
		$('#newsPages').html(sbforNewsPages.toString());
		$('#newsPages li').click(function(){
			if ($(this).hasClass('selected')) return;
			
			var index = $(this).attr('group');
			DisplayNewsByPage(index);
		});
		
		if (IsUseIE)
			$('#newsScroll').css('right', 25);
		
		
		DisplayNewsByPage(NewsBox.pageIndex);
		$('#newsPrev').click(function(){DisplayNewsByPage(NewsBox.pageIndex - 1);});
		$('#newsNext').click(function(){DisplayNewsByPage(NewsBox.pageIndex + 1);});
		           
	});
}

function DisplayNewsByPage(pageIndex)
{
	pageIndex = (pageIndex < 1) ? NewsBox.maxpage : ((pageIndex > NewsBox.maxpage) ? 1 : pageIndex);
	NewsBox.pageIndex = pageIndex;
	
	if (IsUseIE)
		$('#newsBody li div.dateBox').hide('fade', 500).parent().hide('fade',400);
	else
		$('#newsBody li').hide('fade', 400);
		
	$('#newsScroll:visible').hide('fade' ,400);
	
	setTimeout(function(){
		if (IsUseIE)
			$('#newsBody li[group='+ NewsBox.pageIndex + ']').show('fade').find('.dateBox').show('fade');
		else
			$('#newsBody li[group='+ NewsBox.pageIndex + ']').show('fade');	
		
		$('#newsPages li.selected').removeClass('selected');
		$('#newsPages li[group='+ NewsBox.pageIndex +']').addClass('selected');
		
		$('#newsScroll:hidden').show('fade');
		
	},500);
	
}

function DisplayStudentPics()
{
	$.getJSON("data/studentpic.js", function(json){
	
		StudentPicBox = json;
		var path = json.HeaderImagePath;
		var sbforImages = new StringBuffer();
		sbforImages.append('<ul>');
		
		$.each(json.StudentPics, function(i, pic){
			sbforImages.append('<li><img src="').append(path).append(pic.MinSrc)
			           .append('" alt="').append(pic.Title)
			           .append('" display="').append(path).append(pic.Src)
			           .append('"></img></li>');
		
		});
		
		sbforImages.append('</ul>');
		$('#ListPics').html(sbforImages.toString());
		
		var totalWidth = 100;
		$('#ListPics li').each(function(){
			totalWidth += parseInt($(this).css('width'));
		});
		
		$('#ListPics ul').css('width', totalWidth);
		StudentPicBox.ImageIndex = 0;
		
		//click image
		$('#ListPics img').click(function(){
			$('#ListPics img.imgSelect').removeClass('imgSelect');
			$('#MainStudentPic').attr('src', $(this).attr('display'));
			$('#titlePanel').text($(this).attr('alt'));
			$('#picloading').show();
			$(this).addClass('imgSelect');
			
			setTimeout(function(){
				$('#picloading').hide();
			},1000);
		});
		
		$('#ListPics li:first img').click();
		
		//click left or right
		$('#picleft').click(function(){
			var ul = $('#ListPics');
			
			StudentPicBox.ImageIndex -= 5;
			StudentPicBox.ImageIndex = (StudentPicBox.ImageIndex < 0) ? 0 : StudentPicBox.ImageIndex;
			
			ul.scrollTo('li:eq('+ StudentPicBox.ImageIndex.toString() +')',800);
			
		});
		
		$('#picright').click(function(){
			var ul = $('#ListPics');
			
			StudentPicBox.ImageIndex += 5;
			StudentPicBox.ImageIndex = 
				(StudentPicBox.ImageIndex >= StudentPicBox.MainImage) 
				? StudentPicBox.MainImage - 5
				: StudentPicBox.ImageIndex;
			
			ul.scrollTo('li:eq('+ StudentPicBox.ImageIndex.toString() +')',800);
			
		});
		
	});
}

function DisplayLightBox(imgSrc)
{
	var newImage = new Image();
	newImage.src = (imgSrc != null) ? imgSrc : $('#imgFullPicture').attr('src') ;
	var arrPageSizes = GetPageSize();
	
	$('#FullPictureBox').css({
		width: arrPageSizes[0],
		height: arrPageSizes[1]
	}).click(function(){
		$(this).hide();
		$('#FullPictureWhiteBorder').hide();
		$('#imgFullPicture').attr('src', 'images/ajax-loader.gif');
	}).show();
	
	setTimeout(function(){
	
		var picWidth = newImage.width;
		var picHeight = newImage.height;
		var oldWidth = $('#imgFullPicture').width();
		var oldHeight = $('#imgFullPicture').height();
		
		
		$('#imgFullPicture').attr('src', imgSrc);
		
		
		var arrPageScroll = GetPageScroll();
		
		$('#imgFullPicture').hide();
		$('#FullPictureWhiteBorder').show().css({
			top:	(arrPageScroll[1] + ((arrPageSizes[3] > oldHeight) ? parseInt((arrPageSizes[3] - oldHeight) / 2) : parseInt(arrPageSizes[3] / 10))),
			left:	(arrPageSizes[0] > oldWidth) ? parseInt((arrPageSizes[0] - oldWidth) / 2) : 0,
			width:  (oldWidth + 20), 
			height: (oldHeight + 30)
		}).animate({
			top:	(arrPageScroll[1] + ((arrPageSizes[3] > picHeight) ? parseInt((arrPageSizes[3] - picHeight) / 2) : parseInt(arrPageSizes[3] / 10))),
			left:	(arrPageSizes[0] > picWidth) ? parseInt((arrPageSizes[0] - picWidth) / 2) : 0,
			width:  (picWidth + 20), 
			height: (picHeight + 30)
		}, 1500, function(){
			$('#imgFullPicture').fadeIn();
		});
	}, 1500);
}

function GetPageScroll() 
{
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

function GetPageSize() 
{
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}



