/*
 * Functions to load and parse news feed
 *
 * @author: kien wai
 * @version: 0.1
 */

// template variables
var announcementsElemTag = ['headline', 'open', 'link'];
var announcementsOutput = '<div class="announcementsItem"><a href="elem2"elem1>elem0</a></div>';
// 15 Oct 2010: Added codes from GERMS: For 3 has no hyperlink.
var announcementsOutput2 = '<div class="announcementsItem">elem0</div>';
var newsElemTag = ['image', 'HeadLine', 'storyid'];
//var newsOutput = '<div class="newsItem"><img src="elem0" alt="" width="70" height="47" border="0" />elem1</div>';
var newsOutput = '<div class="newsItem"><img src="/images/news/cna.jpg" alt="" width="39" height="39" border="0" /><a href="http://www.channelnewsasia.com/stories/singaporelocalnews/view/elem2/1/.html" target="_blank">elem1</a></div>';

var date = new Date();

var NEWSPODLET = function () {	
	var ctl = {};
	var divID = '#';
	var totalItems;
	var intervalID;
	var tickerInterval = 5000;
	
	
	ctl.load = function(container, feedurl, node) {
		//alert("ajax loading " + feedurl);
		divID += container;
		
		$.ajax({type: 'GET',
				url: feedurl + "?" + date.getTime(),
				dataType: 'xml',
				error: function(xhr, status, errorThrown) {
					//alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
		        },
				success: function(xml) {
					
					$(xml).find(node).each(function() {
						var item = $(this);
						
						var elements = eval(container+'ElemTag');
						var output =  eval(container+'Output');
						
						for (var i=0; i<elements.length; ++i) {
							//create a regular expression to find the position for the element tag
              var position = new RegExp('elem' + [i], 'g');
							
							// 15 Oct 2010: Added codes from GERMS: For 3 has no hyperlink. (start)
							if(elements[i] == "headline" && elements[1] == "open" && item.find(elements[1]).text()*1 == 3)
							{
								output = eval(container+'Output2');
							//	alert(output);
							}
							// 15 Oct 2010: Added codes from GERMS: For 3 has no hyperlink. (end)

							// extract replacement text from the xml
							var newText = item.find(elements[i]).text();
							if(elements[i]=="open"){
								switch (item.find(elements[i]).text() * 1) 
								{
									case 0:
										newText = "/about/announcements/#elem2";
										break;
										
									case 1:
										newText = " target='_self'";
										break;
										
									case 2:
										newText = " target='_blank'";
										break;
								}
							}
							
							if(elements[i]=="open" && item.find(elements[i]).text() * 1 == 0)
							{
								output = output.replace(/elem2/g, newText);
								output = output.replace(/elem1/g, "");
							}
							else
							{
								//alert(position);
								output = output.replace(position, newText);
							}
						}
						//alert(output);	
						$(divID).append(output);
						
					});
					
					init();
				}
		});
	};
	
	
	// private methods
	
	function init() {
		$(divID + ' .preloader').remove();
		
		totalItems = $(divID+' div').length - 1;
		
		$(divID+' div').css('display', 'none');
		$(divID+' div:first').css('display', '');
		
		initTicker();
		
		// init nav btn, only for announcement podlet
		$(divID+'Navi a:not("#readAll")').click(function(evt){
			evt.preventDefault();
			
			var btnID = $(this).attr('id');
			
			if ((btnID == 'prev') || (btnID == 'next'))
				showItem(btnID);
		});
	}
	
	
	function initTicker() {
		// setup ticker timer
		intervalID = setInterval(showItem, tickerInterval);
		
		$(divID+' div').mouseover(function() {
			clearInterval(intervalID);
		});
		
		$(divID+' div').mouseout(function() {
			intervalID = setInterval(showItem, tickerInterval);
		});
	}
	
	
	function currentItemIndex() {
		return $(divID+' div').index($(divID+' div:visible'));
	}
	
	
	function showItem(id) {
		var currentIdx = currentItemIndex();
		
		$(divID+' div').css('display', 'none');
		
		if (id == 'prev') {
			if (currentIdx != 0)
				$(divID+' div:eq('+ currentIdx +')').prev().fadeIn('slow');
			else	
				$(divID+' div:eq('+ totalItems +')').fadeIn('slow');
		} else {
			if (currentIdx < totalItems)
				$(divID+' div:eq('+ currentIdx +')').next().fadeIn('slow');
			else	
				$(divID+' div:eq(0)').fadeIn('slow');
		}
		
	}
	
	return ctl;

};

var NEWSLISTING = function (value) {	
	// template variables
	var yearOutput = '<li id="elemYear"><span id="year-top"></span><p>elemYear</p><span id="year-btm"></span></li>';
	var contentOutput = '<div id="elemYear-content" class="news-content hide"></div>';
	var listingElemTag = ['date', 'headline', 'link','id', 'desc', 'open'];
	var listingOutput = '<p class="newsitem"><span class="date">elem0</span><a id="elem3" href="elem2" class="headline" elem5>elem1</a></p>';
	
	if ( value != 'news')
	{
		yearOutput = '<li id="elemYear"><span id="year-top"></span><p>elemYear</p><span id="year-btm"></span></li>';
		contentOutput = '<div id="elemYear-content" class="news-content hide"></div>';
		listingElemTag = ['date', 'headline', 'link','id', 'desc', 'open'];
		listingOutput = '<p class="newsitem"><a id="elem3" href="elem2" class="headline" elem5>elem1</a><br>elem4</p>';
	}
	
	var ctl = {};
	
	ctl.load = function(feedurl) {
		$.ajax({type: 'GET',
				url: feedurl + "?" + date.getTime(),
				dataType: 'xml',
				error: function(xhr, status, errorThrown) {
					//alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
		        },
				success: function(xml) {
					var output;
					
					// update years listing
					var years = new Array();
					
					$(xml).find('date').each(function() {
						
						var yearArray = jQuery(this).text().split(' ');
						var year = yearArray[yearArray.length - 1];
						//var year = $(this).text().split(' ')[2]; //modified by vinay@germs
						if ($.inArray(year, years) == -1)
							years.push(year);
					});
					
					
					for (var yr in years) {
          				var yearPos = new RegExp('elemYear', 'g');
						
						output = yearOutput.replace(yearPos, years[yr]);
						$('ul#years').append(output);
						
						output = contentOutput.replace(yearPos, years[yr]);
						$('ul#years').after(output);
					}
					
					// select the first year in year listing
					$('ul#years li:first').addClass('selected');
					
					// unhide the latest year listing
					$('div#'+years[0]+'-content').removeClass('hide');
					
					// update news listing
					$(xml).find('item').each(function(count) {
						var item = $(this);
						var yearToInsert;
						
						var elements = listingElemTag;
						output = listingOutput;
						
						for (var i=0; i<elements.length; ++i) {
							//create a regular expression to find the position for the element tag
              var position = new RegExp('elem' + [i], 'g');
							var node = elements[i];
							
							// extract replacement text from the xml
							var newText = item.find(node).text();
							if(node=="id"){
								newText= item.find("link").text().split('/')[2].split('.')[0];
							}
							if (node == 'date') {
								// grab the year that this news item belong to
								
								var yearArray = newText.split(' ');
								var yearToInsert = yearArray[yearArray.length - 1];
								
								//yearToInsert = newText.split(' ')[2]; //modified by vinay@germs 
							}
							if(node=="open"){
								switch (item.find('open').text() * 1) 
								{
									/*case 0:
										newText = "/about/announcements/#"+newText;
										break;*/
										
									case 1:
										newText = " target='_self'";
										break;
										
									case 2:
										newText = " target='_blank'";
										break;
								}
							}

							//alert(output);
							output = output.replace(position, newText);
						}
							
						$('div#'+yearToInsert+'-content').append(output);
						
					});
					
					newsDidFinishLoading();
				}
		});
	};
	
	
	// private methods
	function newsDidFinishLoading() {
		$('ul#years li').click(function(evt){
			evt.preventDefault();

			var el = $(this), eid = '#' + $(this).attr('id');

			$('ul#years li').removeClass('selected');
			el.addClass('selected');
			
			$('.news-content').addClass('hide');
			$(eid+'-content').removeClass('hide');
			
			// Modified by vinay@germs 13 Aug 2010
			
			$(eid+'-content').children('.item, p.backButton')
				.remove()
				.end()
				.children('.newsitem')
				.show();
		});
		
		// Hash Tags
		checkHashAnnouncement();
		// Bind the event.
		  $(window).hashchange( function(){
			checkHashAnnouncement();
		  })
		
		
	}
	function checkHashAnnouncement(){
		var location = jQuery.url.setUrl(document.location).attr("anchor");
		if(location)
		{
			var fileExt = location.split('.')[1];
			//console.log(fileExt);
			if(fileExt!="pdf"){
				var yearhref = location.split('/')[3].split('.')[0].substr(0,4);
		
				jQuery('ul#years li').removeClass("selected");
				jQuery('ul#years li#'+yearhref).addClass("selected");
				jQuery('.news-content').addClass("hide");
				jQuery('#'+yearhref+'-content').removeClass("hide");
				
				jQuery('#'+yearhref+'-content').prepend('<div class="item"><img src="/images/common/loader.gif" alt="" /></div>');
				jQuery('#'+yearhref+'-content').prepend('<p class="backButton"><a href="#">Back</a></p>');
				jQuery('#'+yearhref+'-content').children('.item').load(location)
					.end()
					.children('.newsitem')
					.hide();
			}
		}
	}
	
	
	return ctl;
	
};

	function checkHashAnnouncement(){
		var location = jQuery.url.setUrl(document.location).attr("anchor");

		if(location)
		{
			var fileExt = location.split('.')[1];
			//console.log(fileExt);
			if(fileExt!="pdf"){
				var yearhref = location.split('/')[3].split('.')[0].substr(0,4);
		
				jQuery('ul#years li').removeClass("selected");
				jQuery('ul#years li#'+yearhref).addClass("selected");
				jQuery('.news-content').addClass("hide");
				jQuery('#'+yearhref+'-content').removeClass("hide");
				
				jQuery('#'+yearhref+'-content').prepend('<div class="item"><img src="/images/common/loader.gif" alt="" /></div>');
				jQuery('#'+yearhref+'-content').prepend('<p class="backButton"><a href="#">Back</a></p>');
				jQuery('#'+yearhref+'-content').children('.item').load(location)
					.end()
					.children('.newsitem')
					.hide();
			}
		}
	}

function truncate( text, length )
{
   if (typeof length == 'undefined') var length = 100;

   if (text.length < length) return text; 
	 
   for (var i = length-1; text.charAt(i) != ' '; i--) {
     length--;
   }

   return text.substr(0, length) + '...';
	 //alert(text.substr(0, length) + '...');
}

////////////////////////////////////

function setRightSidebar() {
		/*$(function() {
			$("form.jqtransform").jqTransform();
		});*/

	$('#searchInput')
	.focus(function(){
		if (this.value == 'Type keywords')
		{
			this.value = '';
		}
	})
	.blur(function(){
		if (this.value == '')
		{
			this.value = 'Type keywords';
		}
	});
	
	checkConcierge();
	
}

function checkConcierge()
{
	if ($('#concierge form div select').length == 5)
	{
		$(function() {
			$("form.jqtransform").jqTransform();
		});
		showConcierge();
		
	}
	else
	{
		setTimeout (setRightSidebar, 1000);
	}
}

function showConcierge()
{
	
	$('#concierge').removeClass('hide');
	$('#conciergeA').removeClass('hide');
	$('#conciergeB').removeClass('hide');
		
	$("#concierge div.jqTransformSelectWrapper ul li a").click(function(){
		var thisIndex = $(this).attr('index');
		//window.location = $(this).parent().parent().next('select').find('option:eq('+ thisIndex +')').attr('value');
		var url = $(this).parent().parent().next('select').find('option:eq('+ thisIndex +')').attr('value');
		switch (url) {
			case "#":
				break;
			case "formbranchenquiry":
			case "formenquiryfeedback":
			case "formhpcsenquiry":
			case "formcscenquiry":
				popUp(url + ".html");
				break;
			default:
				window.location = url;
				break;
		}
	});
   	    
	var announcements = new NEWSPODLET();
	announcements.load('announcements', '/about/announcements/announcements_side.xml', 'item');
		
	var news = new NEWSPODLET();
	news.load('news', '/news/cna.xml', 'article');
	
	$('#share1').click(function() {sharePage('digg'); });
	$('#share2').click(function() {sharePage('facebook'); });
	$('#share3').click(function() {sharePage('delicious'); });
	$('#share4').click(function() {sharePage('stumbleupon'); });
	$('#share5').click(function() {sharePage('twitter'); });
	$('#share6').click(function() {sharePage('mail'); });
		
}

function checkNavi()
{
	if ($('#mainNaviC').hasClass('hide'))
	{
		if (first != null)
		{
			$('#mainNaviC li.firstNav:eq(' + first + ')').addClass("current");
			$('#mainNaviC li.firstNav:eq(' + first + ') a:first').addClass("current");
		}
		
		if (first != null && second!= null)
		{
			$('#mainNaviC li.firstNav:eq(' + first + ') ul li.secondNav:eq(' + second + ')').addClass("current");
			$('#mainNaviC li.firstNav:eq(' + first + ') ul li.secondNav:eq(' + second + ') a:first').addClass("current");
		}
		
		$('#mainNaviC').superfish({
			autoArrows: false,
			delay: 100,
			animation: {opacity:'show',height:'show'},
			speed: 1,
			pathClass: 'current'
		});

		$('#mainNaviC').removeClass('hide');
		
		$(document).pngFix(); 	
		
		$('ul.sf-menu ul ul').bgiframe();
	}
	else
	{
		setTimeout (checkNavi, 500);
	}
}

// Added 7 Oct 2010 by klt
// JavaScript: To Set Current Page for PageNavi based on filename.
function setcurrentpage()
{
  var url = document.location.pathname;
  var filename = "";

  if ((url.lastIndexOf('/')+1) == url.length)
  {
	filename = "index";
  }
  else
  {
	filename = url.substring(url.lastIndexOf('/')+1, (url.length-5));
  }

  var idname = 'pageNavi' + filename;

  if (document.getElementById(idname))
  {
	document.getElementById(idname).className = 'current';
  }

}

/*
 * BANNER
 */
jQuery.fn.banner = function(data) {
	//swfobject
	var flashvars = {};
	var params = { wmode: "transparent" }; 
	var attributes = {};
	
	//banners
	var bannerContainer = $(this).attr('id');
	var maxBanner = 5;
	var currentBanner = 1;
	var totalBanner = data.length;
	var width = 800;
	var height = 400;
	var timeout;
	
	if (totalBanner > maxBanner) 
	{
		totalBanner = maxBanner;
	}
	
	$(this).append('<div id="swfContainer" ><div id="swfContent"></div></div>');
	
	$(this).append('<a href="/home" id="jqBannerLinks" style=""></a>');
	
	var bannerNavi = 	'<div id="bannerNavi">' + 
  									'  <span id="left">&nbsp;</span>' ;
	
	for (i=1; i<=totalBanner; i++)
	{
		bannerNavi += '<a class="imageButton" id="button' + i + '"></a>'
	}
	
	bannerNavi +=	'<span id="right">&nbsp;</span>' + 
  							'</div> ';
	
	$(this).append(bannerNavi);
	
	if ($(this).css('width') != undefined)
	{
		width = $(this).css('width');
	}
	
	if ($(this).css('height') != undefined)
	{
		height = $(this).css('height');
	}
	
	showBanner(1);
	
	$('#bannerNavi a').click(function() {
		var newId = $('#bannerNavi a').index(this);
		showBanner(newId*1 + 1)
		return false;
	});
	
	function getNewId() {
		if (currentBanner != totalBanner ) {
			currentBanner += 1;
		} else {
			currentBanner = 1;
		}
		showBanner(currentBanner);
	}
	
	function showBanner(bannerId) {
		currentBanner = bannerId;
		clearTimeout(timeout);
		$('#bannerNavi a').removeClass('selected').addClass('imageButton');
		$('#bannerNavi a:eq(' + eval(bannerId*1 - 1) + ')').addClass('selected').removeClass('imageButton');
		$('a#jqBannerLinks[href]').attr('href', data[bannerId*1 - 1].linkurl);

		if ($('#swfContent').html() == "")
		{
			$('#swfContent').html('<img src="' + data[bannerId*1 - 1].imgurl + '">');
		} else {
			if ($('#swfContent').find('img').attr('src') != undefined)
			{
				$('#swfContent').html('<img src="' + data[bannerId*1 - 1].imgurl + '">');
			}
		}
		swfobject.embedSWF(data[bannerId*1 - 1].url, 'swfContent', width, height, "8.0.0", null, flashvars, params, attributes);
		timeout = setTimeout(getNewId, data[bannerId - 1].duration * 1000);
	}
	
};


function showRates(rates, decimal) {
	for (i=0; i < rates.length; i++)
	{
		document.write('<tr>');
		for (j=0; j<rates[i].length; j++){
			if (isNaN(rates[i][j])){
				document.write('	<td>' + rates[i][j] + '</td>');
			} else {
				document.write('	<td>' + rates[i][j].toFixed(decimal[j]) + '</td>');
				
			}
		}
		document.write('</tr>');
	}
}

function addToFavorite() { 
	var urlAddress = document.location.href; 
	var pageName = document.title; 
	
	if (window.sidebar)
	{
		window.sidebar.addPanel(pageName, urlAddress, "");
	}
	else if (window.external) { 
		window.external.AddFavorite(urlAddress, pageName);
	}
	else if (window.opera && window.print) 
	{
		window.external.AddFavorite(urlAddress, pageName);
	}
  else 
	{ 
		alert("Sorry! Your browser doesn't support this function."); 
	} 
}

function sharePage(network)
{
	var urlAddress = document.location.href; 
	var pageName = document.title; 
	
	switch (network)
	{
		case 'facebook':
			link = 'http://www.facebook.com/sharer.php?u=' + urlAddress + '&t=' + pageName;
			break;
			
		case 'digg':
			link = 'http://digg.com/submit?url=' + urlAddress;
			break;
			
		case 'delicious':
			link = 'http://del.icio.us/post?url=' + urlAddress + '&title=' + pageName;
			break;
			
		case 'stumbleupon':
			link = 'http://www.stumbleupon.com/submit?url='+  urlAddress + '&title=' + pageName;
			break;
			
		case 'twitter':
			link = 'http://twitter.com/home?status=Check this out:'+ pageName + " " + urlAddress;
			break;
			
		case 'mail':
			link = 'mailto:?body=Check this out: ' + urlAddress;
			break;
			
	}
	
	window.open(link);
}

function popUp(url) {
	window.open('https://secure.hlf.com.sg/' + url, 'feedbackwindow', 'toolbar=no,location=no, directories=no,status=yes,menubar=no,resizable=no,copyhistory=no,scrollbars=yes,width=700,height=450');
}

function showPrintCSS()
{
	$("link[type='text/css']").each( function(i){
		if ($(this).attr('id') == 'print') {
			if ($(this).attr('href') == "")
			{
				$(this).attr({href : "/css/hlf_print.css"});
			}
			else
			{
				$(this).attr({href : ""});
			}
		}
	});
}


// Print Popup

$(function(){
	
	jQuery('#print').live('click',function(e){
		window.open(document.location.href+'?print=yes', document.location.title, 'width=600,height=400,menubar=yes,resizable=yes,scrollbars=yes,status=no');
		
	});
	
	
	// Check if Print
	var curURL = document.location.href; 	
	try
           {
						 if (curURL.split('?print')[1])
						 {
       var printParam = curURL.split('?print')[1].split("=")[1];//jQuery.url.param("print");
						 }
              }
         catch(err)
        {

        }
 

	if(printParam=="yes"){
			$('head').append('<link rel="stylesheet" type="text/css" href="/css/hlf_print.css" media="print" />');
		jQuery('link[rel*=style][title]').each(function(){
			this.disabled = true;
			if (this.getAttribute('title') == "print") this.disabled = false;
		});
	}
	
});

