var rmskype;
var chkskype = 0;

/* POSB Script */
$(document).ready(function() {

	if ($("#dykbnr").length) dykrnd();
	if ($("#remit").length) remitcountryselect();
	
	if ($("#content").length) addsocialmedia();
	if ($("#content2").length) addsocialmedia();
	if ($("#content3").length) addsocialmedia();
	
	if ($("#image_rotator").length) rotatingbanner();
	if($("#newsHeader").length) insertmaintenance();
	
	//remove old share buttons
	removeShare();
	removeHelpbox();
	
	removeSkype();
  
/* Used for accordion in Investments - Treasury Products - Foreign Exchange, TRIBALDDB, Arie Ganapathi */
  jQuery('.toggler').hide();
	jQuery('.toggler').prev('h4').click(function(e){
		e.preventDefault();
		jQuery(this).next().animate({height:'toggle'})
		jQuery(this).toggleClass("expanded")
		
	});
/* End for accordion in Investments - Treasury Products - Foreign Exchange, TRIBALDDB, Arie Ganapathi */
	
});


function insertmaintenance() {
	
	$.get("/sg/personal/ibanking/additionalinfo/scheduledmaintenance/maintenance.xml", function(xml) {
		mtmp = $(xml).find("whatsnewmessage").text();
		message = $.trim(mtmp);
		if (message!="none") {
			$('#news #newsContent a').css('display','none');
			$("#newsContent").append("<a href='/posb/ibanking/additionalinfo/scheduledmaintenance'>" + message + "</a>");
		}
	});
}


function removeSkype() {
	//loop this function for 100 times
	if (chkskype < 100) {
		
		$('.skype_pnh_container').html('');
		$('.skype_pnh_print_container').removeClass('skype_pnh_print_container');

		chkskype++;
		rmskype = setTimeout(removeSkype, 10);
	}
	
}



function removeHelpbox() {

	//case 1: pageviewer webpart 
	$("iframe").each(function() {
		sourcetgt = $(this).attr("src");
		if (sourcetgt.indexOf("dropdown")!=-1) {
			$(this).parent().parent().parent().parent().parent().parent().remove();
		}
	});
	
	//case 2: content editor webpart
	$("div.containerHeader").each(function() {
		helphtml = $(this).html();
		if (helphtml == "How can we help?") {
			$(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().remove();
		}
	});
	
}

/* 3 column home loan navigations for POSB - added 5 oct 2011 */
$(function(){
	// Rates Tab
	
	jQuery('.tabContent > div').hide();
	jQuery('.tabContent > div:first').show();
	jQuery('ul.ratesTab li:first').addClass("active");
	jQuery('ul.ratesTab a').click(function(e){ // Click Handler for tabs
		var tab = jQuery(this).attr("href");
		jQuery('.tabContent > div').hide();
			jQuery('.tabContent > '+tab).show();
			jQuery('ul.ratesTab li').removeClass("active");
			jQuery(this).parent().addClass("active");
		e.preventDefault();
		
		if(!jQuery(this).parent().next().length){
			jQuery(this).parent().addClass("lastActive");
		}
		else{
			jQuery(this).parent().siblings().removeClass("lastActive");
		}
	});
	
	jQuery('.content2-tabContent > div').hide();
	jQuery('.content2-tabContent > div:first').show();
	jQuery('ul.content2RightTab li:first').addClass("active");
	jQuery('ul.content2RightTab a').click(function(e){ // Click Handler for tabs
		var tab = jQuery(this).attr("href");
		jQuery('.content2-tabContent > div').hide();
			jQuery('.content2-tabContent > '+tab).show();
			jQuery('ul.content2RightTab li').removeClass("active");
			jQuery(this).parent().addClass("active");
		e.preventDefault();
		
		if(!jQuery(this).parent().next().length){
			jQuery(this).parent().addClass("lastActive");
		}
		else{
			jQuery(this).parent().siblings().removeClass("lastActive");
		}
	});
	
	// Tab Height and Vertical Align
	
	if(jQuery('.gs-tabs').length){
		var max=0;
		jQuery('.gs-tabs li').each(function(){
			jQuery(this).children().css({width:jQuery('.gs-tabs').outerWidth()/jQuery('.gs-tabs li').size() - 22})
			if(jQuery(this).height()>max) max=jQuery(this).height();
		});
		jQuery('.gs-tabs li').css({height:max});
		jQuery('.gs-tabs li.active').css({height:max-5});
		
		jQuery('.gs-tabs li').each(function(){
			var mt = ($(this).height() - $(this).children().height())/2;
			jQuery(this).children().css({paddingTop:mt});
			jQuery(this).children().css({
				
			});
		});
		
		if(jQuery('.gs-tabs li').size()<=2){
			jQuery('.gs-tabs li a').css({width:jQuery('.gs-tabs').outerWidth()/3});
		}
		
		
	}
	
	// Tabs
	
	jQuery('.sideContent').hide();
	jQuery('.sideContent:first').show();
	jQuery('ul#Aside li:first').addClass("active");
	
		// Click Handler
		jQuery('ul#Aside a').click(function(e){
			e.preventDefault();
			var tab = jQuery(this).attr("href");
			var el=this;
			var topOffset= el.offsetTop;
			if(jQuery.browser.msie && jQuery.browser.version<8) topOffset = jQuery(this).parent().offset().top-jQuery(this).parents('ul').offset().top+25;
			jQuery('.activeArrow').animate({
				top:topOffset+"px"
			},200);
			
			jQuery('.sideContent').hide();
			jQuery('ul#Aside li').removeClass("active");
			jQuery(this).parent().addClass("active");
			jQuery('.sideContent[rel='+tab.split('#')[1]+']').show();
		});	
		
		   }
)

// function for rotating banners in travellershield
var jqb_vCurrent = 0;
var img = "#image";
jqb_vTotal = 0;

function rotatingbanner()
{
	jqb_intInterval = setInterval(loop,4000);
	jqb_vTotal = $("#image_rotator").children().size() -1;
	
	$("#image_rotator .image2").css({
		position:'relative',
		display: 'none'
	});
}

function removeShare() {

	var x = $("#shareContainer").parent().parent();
	var y = x.children();
	
	if (y.length==1) {
		z = y.parent().parent().parent().remove();
	} else {
		$("#shareContainer").parent().remove();
	}
	
	$("div.container").css("display","block");
}


// function for rotating banners
function loop()
{			
	
	if(jqb_vCurrent == 0)
	{	
		jqb_vCurrent++;
		$("#image_rotator").find(img+jqb_vCurrent).each(function(i) { 
		$(this).prev().hide();
		$(this).show();
		});
	}
	else if(jqb_vCurrent < jqb_vTotal)
	{		
		jqb_vCurrent++;
		$("#image_rotator").find(img+jqb_vCurrent).each(function(i) { 
		$(this).prev().hide();
		$(this).show();
		});
	}
	else
	{
		$("#image_rotator").find(img).each(function(i) { 
		$(this).show();
		});
		
		$("#image_rotator .image2").css({
		position:'relative',
		display: 'none'
		});
		
		jqb_vCurrent =0;
	}

}


//function to add social media icons
function addsocialmedia() {
	
	var urlstring = window.location.toString();
	var afterdomain = (window.location.pathname).substr(1);
	var folders = afterdomain.split("/");
    var productpath = "";
	
	//$("#logo a").attr("href",urlstring);
	
    if (folders[0] == "posb") {
		
		switch(folders[1]) {
			case "Pages":
				productpath = "";
				break;
			case "pages":
				productpath = "";
				break;
			case "deposit":
				if (folders[2]=="kidsaccount" || folders[2]=="posbkidsacademy" || folders[2]=="landing") {
					productpath = "/posb/deposit/kidsaccount/";
					break;
				}
			case "cards":
				if (folders[2]=="multitudecard") {
					productpath = "/posb/cards/multitudecard/";
					break;
				}
			//default:
				//productpath = "/posb/" + folders[1] + "/";
				//break;
		} //end switch
	} //end if
	
	//to remove accidentally added div w socialbuttons id	
	$("div#socialbuttons").remove();
	
	if (productpath!="") {

		if ($("div#content").length) $("#content").prepend("<div id='socialbuttons'></div>");
		if ($("div#content2").length) $("#content2").prepend("<div id='socialbuttons'></div>");
		if ($("div#content3").length) $("#content3").prepend("<div id='socialbuttons'></div>");
	
		$("div#socialbuttons").load(productpath+"socialmedia.html");
	}
	
}


//function add remit countries and currencies
function remitcountryselect() {
	
	var htmlstr = "<select id='remitcountry'>";
	
	$.get("/posb/ibanking/services/remit.xml", function(xml) {
	
		$(xml).find("country").each(function() {
			htmlstr = htmlstr + "<option value='"+$(this).attr("currency")+"'>"+$(this).text()+"</option>";
		});
		htmlstr = htmlstr + "</select>";
		
		$("td#remit").html(htmlstr);
		
		//init select box
		$("select#remitcountry").change(function() {
			$("td#remitcurr").html($(this).val());
		});
		
	});
}

/*-- generic function to mark navigation --*/
function marknav(tgtelem, naviname) {
	$(tgtelem + " a").each(function() {
		var linkname = $(this).html();
		if (linkname == naviname) $(this).attr("style","color:#336699 !important; font-weight:bold;");
	});
}


function dykrnd() {

	var arr_apply = new Array("21","22","24","3","1");
	var arr_save = new Array("1","2");
	var arr_pay = new Array("6","10","11","13","14","15","16","17");
	var arr_invest = new Array("1","5","4","7");
	var arr_transfer = new Array("13","23","24","8","9");
	var arr_track = new Array("18","19","20","24","25","12");
	var arr_services = new Array("3","4","6","5","13","14","15","16");
	
	var imgpath = "/posb/img/ibanking/additionalinfo/services/banner/tip_";
	
	switch($("#dykbnr").attr("title")) {
		case "applyonline":
			$("#dykbnr").attr("src", imgpath + arr_apply[getrnd(arr_apply.length)] +".gif").show();
			break;
			
		case "saveonline":
			$("#dykbnr").attr("src", imgpath + arr_save[getrnd(arr_save.length)] +".gif").show();
			break;
			
		case "payonline":
			$("#dykbnr").attr("src", imgpath + arr_pay[getrnd(arr_pay.length)] +".gif").show();			
			break;
			
		case "investonline":
			$("#dykbnr").attr("src", imgpath + arr_invest[getrnd(arr_invest.length)] +".gif").show();			
			break;
			
		case "transferonline":
			$("#dykbnr").attr("src", imgpath + arr_transfer[getrnd(arr_transfer.length)] +".gif").show();			
			break;
			
		case "trackmanageonline":
			$("#dykbnr").attr("src", imgpath + arr_track[getrnd(arr_track.length)] +".gif").show();			
			break;
			
		case "ibankingservices":
			$("#dykbnr").attr("src", imgpath + arr_services[getrnd(arr_services.length)] +".gif").show();			
			break;
			
		default:
			break;
	}

}

function getrnd(upperlimit) {
	return Math.floor(Math.random()*upperlimit);
}


/*protection calculator*/
$(window).load(function() {
  	getInputContent();
	
$("#protection_calculator_container").keypress(function(E) {
    if(E.keyCode == 13) {
        ComputeAmount();
    }
});

 });

$("#pmt").keypress(function(J) {
    if(J.which >= 65 || J.which > 90){
		J.preventDefault();
	}
	else if(J.keyCode >= 65 || J.keyCode > 90){
		J.preventDefault();
	}
});

function ComputeAmount(){
	$('#protection_menu').hide();
	var pv;
	var temppmt = $('#pmt').val();
	var i = .0294;
	var periods = $('#periods').val();
	var base = (1+i);
	pmt = (removecommas(temppmt)*12);
	window.location = "#periods="+periods+"&expenses="+temppmt;
	if(removecommas(temppmt)>=1 && removecommas(temppmt)<=999999){
	
	pv = (Math.pow(base,-periods)*(base)*(Math.pow(base,periods)-1)*pmt)/i;
	
	$('#output').text(addCommas((Math.round(pv*100)/100).toFixed(0)));
	$('#print_output').text(addCommas((Math.round(pv*100)/100).toFixed(0)));
	$('#print_pmt').text(addCommas(temppmt));
	$('#print_periods').text(periods);
	$('#print_btn').show();
	$('#email_btn').show();
	$('#contact_btn').css('margin-left','20px');
	
	$('#protection_menu').slideDown('normal');
	$('html, body').animate({ scrollTop: $('#protection_calculator_container').offset().top}, 0);
	}else{
		alert("Average Monthly Expenses should be between S$1 - S$999,999");
		$('#pmt').focus();
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function removecommas(str){
    if(str.length>0)
        return str.split(",").join(""); 
}

function formatInputField(input)
{
    var nStr = input.value + '';
    nStr = nStr.replace( /\,/g, "");
    var x = nStr.split( '.' );
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while ( rgx.test(x1) ) {
        x1 = x1.replace( rgx, '$1' + ',' + '$2' );
    }
    input.value = x1 + x2;
}

var WindowObject;
function printpagebtn(){
	
	var output = $('#output').text();
	if(output==""){
		ComputeAmount();
	}else{
	
	var DocumentContainer = document.getElementById('printProtectionCalc');
	WindowObject = window.open("","CalculatorResult", "width=740,height=700,top=0,left=0,toolbars=no,scrollbars=yes,status=no,resizable=no");
	WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
	
	
		
	setTimeout(printTimed ,1000);
	
	}
}

function printTimed(){
	WindowObject.focus();
	WindowObject.print();
}


function sendmail(){
	var output = $('#output').text();
	var pmt = $('#pmt').val();
	var periods = $('#periods').val();
	if(output==""){
		ComputeAmount();
	}else{
		window.location="mailto:?subject=Protection%20Plan%20-%20Protection%20Calculator&body=Estimated%20Coverage%0A%0AThe%20calculator%20is%20intended%20to%20be%20used%20for%20illustrative%20purpose%20only%20and%20has%20not%20been%20tailored%20to%20your%20specific%20investment%20objectives%2C%20financial%20information%20and%20particular%20needs(1).%20You%20may%20wish%20to%20seek%20advice%20from%20a%20financial%20adviser%20before%20making%20a%20commitment%20to%20purchase%20the%20product.%20To%20assist%20you%20in%20your%20protection%20planning%2C%20you%20may%20wish%20to%20seek%20financial%20advice%20from%20our%20relationship%20managers%20in%20any%20of%20our%20DBS%2FPOSB%20branches.%0A%0A%0ANo.%20of%20years%20needed%20to%20support(2)%20for%20your%20dependents(3)%3A%20"+periods+"%0A%0AAverage%20Monthly%20Expenses(4)%3A%20S%24"+pmt+"%0A%0A%0AEstimated%20Coverage%3A%20S%24"+output+"%0A%0AShow%20this%20page%20to%20any%20DBS%2FPOSB%20branch%2C%20speak%20to%20our%20relationship%20manager%20and%20get%20S%245%20McDonald's%20voucher*.%0A%0A*while%20stocks%20last%0A%0A%0ADisclaimers%0A%0A(1)%20%20The%20Bank%20shall%20not%20be%20liable%20for%20any%20error%20and%2For%20loss%20suffered%20as%20a%20result%20of%20using%20the%20calculator.%0A%0A(2)%20%20Support%20refers%20to%20monetary%20terms%20%2F%20value%20you%20incurred%20when%20taking%20care%20of%20your%20family%0A%0A(3)%20%20Dependents%20are%20children%20who%20have%20not%20reach%20financial%20independence%2C%20or%20elderly%20parents%20who%20have%20stopped%20working%20and%20no%20longer%20earning%20regular%20income%2C%20spouse%20or%20any%20person%20you%20named%2C%20who%20rely%20on%20you%20for%20financial%20support.%0A%0A(4)%20%20Expenses%20incurred%20refers%20to%20support%20needed%20on%20your%20dependents%20based%20on%20your%20current%20lifestyle";
	}
}

function contactus_btn_click(){
	window.open("https://secure.dbs.com/Contact/sg/posb/insurance/protectionplans/default.aspx");
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function getInputContent(){
	var periods_detect = getUrlVars()["periods"];
	var expenses_detect = getUrlVars()["expenses"];
	if(typeof expenses_detect!="undefined"){
		$('#periods').val(periods_detect);
		$('#pmt').val(expenses_detect);
		ComputeAmount();
	}
	
}



//printpage.html?figures="+$('#output').val()
/* protection calculator close*/


