/********************************************************************************************************
 * CPF TEXT RESIZE Project
 * Last update : Mar 2009 (Herbert Ambos/Adrian Lee)
 *
 * Install Notes:
 *	1. Include this JS file in every page or ideally in the header templates
 *	2. On the exact position on where you want the icons to be installed just do a
 *		oCPFTextResize.install()				
 *
 ********************************************************************************************************/

//
//  Helper functions
//  Note:  All helper functions should be named as CPFText<function name> to not to
//         conflict with any JS var declared in the page
//
 function rzCC(s){
   // thanks http://www.ruzee.com/blog/2006/07/\
   // retrieving-css-styles-via-javascript/
   for(var exp=/-([a-z])/; 
       exp.test(s); 
       s=s.replace(exp,RegExp.$1.toUpperCase()));
   return s;
 }

 function _setStyle(element, declaration) {
   if (declaration.charAt(declaration.length-1)==';')
     declaration = declaration.slice(0, -1);
   var k, v;
   var splitted = declaration.split(';');
   for (var i=0, len=splitted.length; i<len; i++) {
      k = rzCC(splitted[i].split(':')[0]);
      v = splitted[i].split(':')[1];
      eval("element.style."+k+"='"+v+"'");

   }
 }
// addMethod - By John Resig (MIT Licensed)
function CPF2TextAddMethod(object, name, fn){
    var old = object[ name ];
    object[ name ] = function(){
        if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
        else if ( typeof old == 'function' )
            return old.apply( this, arguments );
    };
}

Array.prototype.CPF2TextInArray = function (value) {
	for (var i = 0; i < this.length; i++) 
		if (this[i] === value) return true;
	return false;
};

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
String.prototype.isWholeNumber = function () {
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   for (i = 0; i < this.length && IsNumber == true; i++) { 
      Char = this.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) IsNumber = false;
   }
   return IsNumber;
}

//
// Text Resize Main Class
//
function CPF2TextResize (val) {

	var aSizeList2 = new Array();
	aSizeList2[1] = "90%";
	aSizeList2[2] = "95%";
	aSizeList2[3] = "xx-small";
	aSizeList2[4] = "x-small";
	aSizeList2[5] = "small";
	aSizeList2[6] = "medium";		
	aSizeList2[7] = "large";
	aSizeList2[8] = "x-large";
	
	var aExcludeTag2 = new Array();
	aExcludeTag2[0] = "#DOCUMENT";
	aExcludeTag2[1] = "HTML";
	aExcludeTag2[2] = "HEAD";
	aExcludeTag2[3] = "TITLE";
	aExcludeTag2[4] = "SCRIPT";
	aExcludeTag2[5] = "#comment";
	aExcludeTag2[6] = "BR";
	
	var aExcludeFixTag2 = new Array();
	aExcludeFixTag2[0] = "TABLE";
	aExcludeFixTag2[1] = "TH";
	aExcludeFixTag2[2] = "TBODY";
	aExcludeFixTag2[3] = "TR";

	var mImagePath;
	if (document.domain == 'dev.CPF.gov.sg' || document.domain == 'www.CPF.gov.sg') mImagePath = '/js/';
	else if (document.domain == 'dev-crms.CPF.gov.sg' || document.domain == 'myCPF.CPF.gov.sg') mImagePath = '/CPF/images/NewFeatures/';
	else mImagePath = '/CPF/images/NewFeatures/';
	

	mImagePath = "/Home/Hybrid/Themes/CPF/Images/";
	var mDefaultIncreaseImage2 =  mImagePath + 'mg_plus.gif';	
	var mDefaultDecreaseImage2 = mImagePath + 'mg_minus.gif';
	var mDefaultDisabledAddImage2 = mImagePath + 'mg_plus-grey.gif'; // default disabled image for plus
	var mDefaultDisabledMinusImage2 = mImagePath + 'mg_minus-grey.gif'; // default disabled image for minus
	var mPrinterImage2 = mImagePath + 'printer.gif';
	
	var mIncreaseImageAltText2 = 'Click here for bigger text';
	var mDecreaseImageAltText2 = 'Click here for smaller text';
	var mDisabledAltText2 =      'This icon is deactivated';
	var mPrinterImageAltText2 =  'Printer-friendly page';
	
	var mSizeRangeLow2 = 0;
	var mSizeRangeHigh2 = 3;
	var intSizeCtr2 = 0; // Size stopper
	
	var isIncrease2;
	var isFix2 = false;
	var mObjName2 = val;
	var isPrinterIconInstalled2 = false;
	try { var isNewToolTipInstalled2 = (Tip != undefined) } catch(e) { var isNewToolTipInstalled2 = false }
	var isPageTracked2 = false;
	var tracker2 = 'http://www.cpf.gov.sg/webcounter/TextSizeCounter.asp';
	
	CPF2TextAddMethod(this, 'showNewToolTip2', function(sFrom) {
		if (sFrom == "increase2")
			Tip(intSizeCtr2 == mSizeRangeHigh2 ? mDisabledAltText2 : mIncreaseImageAltText2, WZ_BGCOLOR, '#FFFFCC', WZ_SHADOW, true, WZ_FONTSIZE, '14px')
		else //decrease
			Tip(intSizeCtr2 == mSizeRangeLow2  ? mDisabledAltText2 : mDecreaseImageAltText2, WZ_BGCOLOR, '#FFFFCC', WZ_SHADOW, true, WZ_FONTSIZE, '14px')
	});	
		
	CPF2TextAddMethod(this, 'getMaxSize2', function() { return mSizeRangeHigh2; });	
	CPF2TextAddMethod(this, 'getMinSize2', function() { return mSizeRangeLow2; });	
	
	CPF2TextAddMethod(this, 'installIncreaseIcon2', function() { this.installIncreaseIcon2(mDefaultIncreaseImage2); });	
	CPF2TextAddMethod(this, 'installDecreaseIcon2', function() { this.installDecreaseIcon2(mDefaultDisabledMinusImage2); });	
	CPF2TextAddMethod(this, 'installIncreaseIcon2', function(image) { 
		document.write ('<span><image style="cursor: hand;" id="CPF2TextIncreaseIcon" src="' + image + '" onclick="javascript:' + mObjName2 + '.doIncrease2();" ' + 
		                (isNewToolTipInstalled2 ? 'onMouseOver="' + mObjName2 + '.showNewToolTip2(\'increase2\')" onMouseOut="UnTip()"' : 'title= "' + mIncreaseImageAltText2 + '"') +
		                '></span>'); 
	});		

	CPF2TextAddMethod(this, 'installDecreaseIcon2', function(image) { 
		document.write ('<span><image style="cursor: hand;" id="CPF2TextDecreaseIcon" src="' + image + '" onclick="javascript:' + mObjName2 + '.doDecrease2();" ' + 
				(isNewToolTipInstalled2 ? 'onMouseOver="' + mObjName2 + '.showNewToolTip2(\'decrease2\')" onMouseOut="UnTip()"' : 'title= "' + mDecreaseImageAltText2 + '"') +
		                '></span>');
	});
	
	CPF2TextAddMethod(this, 'installPrinterIcon2', function() {  
		document.write ('<span><image style="cursor: hand;" id="CPF2PPrinterIcon" title= "' + mPrinterImageAltText2 + '" src="' + mPrinterImage2 + '" onclick="javascript:' + mObjName2 + '.print();"></span>');	
		isPrinterIconInstalled2 = true;
	});
	
	CPF2TextAddMethod(this, 'install2', function() { if (this.isURLIncluded2()) {this.install2(0);} });
	CPF2TextAddMethod(this, 'install2', function(numSpace) { 
		document.write ('<nobr>');		
		this.installIncreaseIcon2(); 
		for (var i = 0; i < numSpace; i++) document.write ('<image src="' + mImagePath +'spacer.png">');//spacing
		this.installDecreaseIcon2();
		if (ICON_PRINT_SHOW) this.installPrinterIcon2();
		document.write ('</nobr>');
	});
	
	CPF2TextAddMethod(this, 'print2', function() { try {return ICON_PRINT_ON_CLICK()} catch(e) {} });
	
	CPF2TextAddMethod(this, 'fixHTML2', function(obj) { 		
		try {			 			 
		  
			  for (var i = 0; i < obj.childNodes.length; i++) {
			  	   var l = obj.childNodes[i];
				   this.setupFontStyle2(l);   
					   if ((!aExcludeFixTag2.CPF2TextInArray(l.nodeName)) && (obj.nodeName != "SPAN" || obj.className != "")){				   
					   try {
						   var r = obj.childNodes[i + 1];
						   var strOrgRNodeValue = r.nodeValue;						
						   if (r.nodeName == '#text' && String(r.nodeValue).trim() != '') { 
								var kStyle = this.getStyle2(obj);
								var sp = document.createElement('SPAN');
								sp.setAttribute("style","font-size: " + kStyle + ";");
								sp.className = obj.className;
								sp.innerHTML = strOrgRNodeValue.replace(/ /,"&nbsp;");

															
								try { obj.insertBefore(sp, r); r.nodeValue = ''; } catch (err) {}
								i++;
						   }else{
								//fix to cater cases : <td><a></a>#text</td> 
								if(l.nodeName == "A" && (obj.nodeName == "TD" || obj.nodeName == "FONT")){
								   var r2 = obj.childNodes[i + 1];							   
								   var strOrgRNodeValue2 = r2.nodeValue;
								   if(strOrgRNodeValue2 != '' && String(strOrgRNodeValue2).trim() != ""){
										if(r2.nodeName == "#text"){
											var kStyle2 = this.getStyle2(obj);
											var sp2 = document.createElement('SPAN');
											sp2.setAttribute("style","font-size: " + kStyle + ";");
											sp2.className = obj.className;
											sp2.innerHTML = strOrgRNodeValue2.replace(/ /,"&nbsp;");
											try { obj.insertBefore(sp2, r2); r2.nodeValue = ''; } catch (err) {}
											i++;
										}
								   }			
									
								}
						   }
					   } catch (err) {}
					   						  
					   }
				}
			
			for (var i = 0; i < obj.childNodes.length; i++) this.fixHTML2(obj.childNodes[i]); 
		} catch(err){};
		isFix2 = true;
	});
	CPF2TextAddMethod(this, 'setupFontStyle2', function(obj) { 
		
		for (var i = 0; i < obj.childNodes.length; i++) {
		var CStyle ;
				try{
					CStyle = this.getStyle2(obj.childNodes[i]);
				}catch(e){}
				if(CStyle != 'undefined' && obj.childNodes[i].nodeName != "FONT"){
					try{	
						if(obj.nodeName != "FONT" ){				
							_setStyle(obj.childNodes[i], 'font-size: '+CStyle);
						}
						if(obj.nodeName == "FONT" && (obj.childNodes[i].nodeValue != "SELECT" || obj.childNodes[i].nodeValue != "OPTION")){
							if(obj.childNodes[i].nodeValue == null){
								switch (CStyle) {
									case '-1':										
										_setStyle(obj, 'font-size:' + '13px');
										break;	
									case '2':										
										_setStyle(obj, 'font-size:' + '13px');
										break;	
									case '-2':										
										_setStyle(obj, 'font-size:' + '10px');
										break;	
									case '+1':
										_setStyle(obj, 'font-size:' + '18px');
										break;
									case '+2':
										_setStyle(obj, 'font-size:' + '22px');
										break;													
									case '+3':
										_setStyle(obj, 'font-size:' + '36px');
										break;
									case '+0':										
										_setStyle(obj, 'font-size:' + '16px');
										break;
									case '0':
										_setStyle(obj, 'font-size:' + '10px');
										break;
									default:
										//try {
										//	_setStyle(obj.childNodes[i], 'font-size:' + CStyle);
										//} catch (err) {}
								}
							}else{
								CStyle45 = this.getStyle2(obj);
								switch (CStyle45) {
									case '-1':										
										_setStyle(obj, 'font-size:' + '13px');
										break;	
									case '2':										
										_setStyle(obj, 'font-size:' + '13px');
										break;	
									case '-2':										
										_setStyle(obj, 'font-size:' + '10px');
										break;	
									case '+1':
										_setStyle(obj, 'font-size:' + '18px');
										break;
									case '+2':
										_setStyle(obj, 'font-size:' + '22px');
										break;
									case '+3':
										_setStyle(obj, 'font-size:' + '36px');
										break;
									case '+0':										
										_setStyle(obj, 'font-size:' + '16px');
										break;
									case '0':
										_setStyle(obj, 'font-size:' + '10px');
										break;
									default:
										//try {
										//	_setStyle(obj.childNodes[i], 'font-size:' + CStyle);
										//} catch (err) {}
								}
							}
						}								
					}catch(e){}
				}
		}
	});
	CPF2TextAddMethod(this, 'toggleIcons2', function() {
		CPF2TextCreateCookie("CPF2TextSize", intSizeCtr2);
	    if (intSizeCtr2 == mSizeRangeLow2) {
			//disable Decrease
			window.document.getElementById("CPF2TextDecreaseIcon").src = mDefaultDisabledMinusImage2;
			if (!isNewToolTipInstalled2)
				window.document.getElementById("CPF2TextDecreaseIcon").title = mDisabledAltText2;							
		} else 
			if (intSizeCtr2 == mSizeRangeHigh2) {
				//disable Increase
				window.document.getElementById("CPF2TextIncreaseIcon").src = mDefaultDisabledAddImage2;
				if (!isNewToolTipInstalled2)
					window.document.getElementById("CPF2TextIncreaseIcon").title = mDisabledAltText2;
			} else {
				//enable All
				window.document.getElementById("CPF2TextIncreaseIcon").src = mDefaultIncreaseImage2;
				window.document.getElementById("CPF2TextDecreaseIcon").src = mDefaultDecreaseImage2;
				if (!isNewToolTipInstalled2) {
					window.document.getElementById("CPF2TextIncreaseIcon").title = mIncreaseImageAltText2;
					window.document.getElementById("CPF2TextDecreaseIcon").title = mDecreaseImageAltText2;
				}
			}
	});

	CPF2TextAddMethod(this, 'increase2', function() {
		if (!isFix2) this.fixHTML2(window.document.body);
	    	isIncrease2 = true;
		if (intSizeCtr2 < mSizeRangeHigh2) {
			intSizeCtr2++;
			this.setFontSize2(window.document.body);	
		} 
		
		this.toggleIcons2();
	});
	
	CPF2TextAddMethod(this, 'trackThisPage2', function() {
			var xmlHttp;
			try {
				// Firefox, Opera 8.0+, Safari
				xmlHttp=new XMLHttpRequest();
			} catch (e) {
				// Internet Explorer
				try {
					xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {
						//alert("Your browser does not support AJAX!");
						return false;
					}
				}
			}
	
			xmlHttp.onreadystatechange = function() {
				//if (xmlHttp.readyState==4) {alert(xmlHttp.responseText);}
			} //ignore the output
	
			try {
				xmlHttp.open("GET", tracker2 + '?host='+ window.location.hostname +'&path=' + window.location.pathname + '&action=' + (isIncrease2 ? 'plus' :'minus'), true);
				xmlHttp.send(null);
			} catch (e) {}
			
			isPageTracked2 = true;
			return true;
	});

	CPF2TextAddMethod(this, 'doIncrease2', function() {
		this.increase2();
		if (!isPageTracked2) this.trackThisPage2();
	});
	
	CPF2TextAddMethod(this, 'doDecrease2', function() {
		this.decrease2();
		if (!isPageTracked2) this.trackThisPage2();
	});
	
	CPF2TextAddMethod(this, 'decrease2', function() {
		if (!isFix2) this.fixHTML2(window.document.body);
	    	isIncrease2 = false;
		if (intSizeCtr2 > mSizeRangeLow2) {
		    	intSizeCtr2--;
		    	this.setFontSize2(window.document.body);
		} 

		this.toggleIcons2();
	});

	CPF2TextAddMethod(this, 'applySize2', function() { var mSavedSize = CPF2TextReadCookie("CPF2TextSize"); this.applySize2(mSavedSize == "" ? 0 : mSavedSize); });	
	CPF2TextAddMethod(this, 'applySize2', function(theSize) {
		if (intSizeCtr2 != theSize) 
			if (intSizeCtr2 < theSize) 
				for (var i = intSizeCtr2; i < theSize; i++) this.increase2();				
			else 
				for (var i = intSizeCtr2; i > theSize; i--) this.decrease2();
		else
			this.toggleIcons2();	
	});
	
	CPF2TextAddMethod(this, 'getStyle2', function(oElm, strCssRule) {
	    var strValue = "";
	    if (document.defaultView && document.defaultView.getComputedStyle)
		    strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	    else if (oElm.currentStyle) { 
		    try {
			    strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); });
			    strValue = oElm.currentStyle[strCssRule];
		    } catch(e) {/* Used to prevent an error in IE 5.0*/}
	    }
	    return strValue;
	});
	
	
	CPF2TextAddMethod(this, 'getStyle2', function(oElm) {
	   var strValue = "";
	   if (oElm.style && oElm.style.fontSize)
            strValue = oElm.style.fontSize;         
       else if (typeof(getComputedStyle) != 'undefined')  //get the styles on an element that aren't set in-line
	        strValue = getComputedStyle(oElm,'').getPropertyValue('font-size');			 
	   else if (oElm.currentStyle)
	        strValue = oElm.currentStyle.fontSize;

       return strValue;
	});
	
	CPF2TextAddMethod(this, 'setFontSize2', function(obj) {
		if (obj.id != 'CPF2ToolTip2') {
			if (!aExcludeTag2.CPF2TextInArray(obj.nodeName) && String(obj.nodeName).indexOf('/'))	{	
				try {
					var currFontSize2;//aids
					var currComputedFontSize;			
					var bolBrowserFF = 0; // value of fontsize in IE is x-small,small,etc while PX in FF
					currFontSize2 = this.getStyle2(obj);		    		
						if (String(currFontSize2).isWholeNumber() && obj.size) {
							obj.size = isIncrease2 ? parseInt(currFontSize2) + 1 : parseInt(currFontSize2) - 1;											
						} else {
							var attribCPFTextSize = obj.getAttribute('CPFTextSize');
							
							if (attribCPFTextSize != intSizeCtr2) {						
								switch (currFontSize2) {
									case '90%':
										currComputedFontSize = 1;
										break;	
									case '95%':
										currComputedFontSize = 2;
										break;	
									case 'xx-small':
										currComputedFontSize = 3;
										break;	
									case 'x-small':
										currComputedFontSize = 4;
										break;	
									case 'small':
										currComputedFontSize = 5;
										break;
									case 'medium':
										currComputedFontSize = 6;
										break;
									case 'large':
										currComputedFontSize = 7;
										break;
									case 'x-large':
										currComputedFontSize = 8;
										break;
									default:
										x = /([\d.]+)(.+)/.exec(currFontSize2); //if px, split the numeric and unit
										intCurrentSize = x[1];// numeric size
										strCurrentTag = x[2];// unit
										if (strCurrentTag == 'em') 
											currComputedFontSize = parseFloat(intCurrentSize);
										else
											currComputedFontSize = parseInt(intCurrentSize);							
										bolBrowserFF = 1;
								}
								if (bolBrowserFF == 0) {	 // if IE just jump from array, becuase no way to get actual px from absolute keyword fnt size
									if( obj.firstChild.nodeValue != null || obj.nodeName == "SELECT"){
										currComputedFontSize = isIncrease2 ? currComputedFontSize + 1 : currComputedFontSize - 1;											
										obj.style.fontSize = aSizeList2[currComputedFontSize];
									}
								} else { //if FF just add 2 or minus 2 from actual pixel font-size
									if( obj.firstChild.nodeValue != null || obj.nodeName == "SELECT") {
										if (strCurrentTag == 'em') 
											currComputedFontSize = isIncrease2 ? (parseFloat(currComputedFontSize) + 0.2) : (parseFloat(currComputedFontSize) - 0.2);						
										else 
											currComputedFontSize = isIncrease2 ? currComputedFontSize + 2 : currComputedFontSize - 2;						

										obj.style.fontSize = currComputedFontSize + strCurrentTag;
										bolBrowserFF = 0;
									}						
								}

								obj.setAttribute('CPFTextSize', intSizeCtr2);								
							}
						}	

						var nextSize = intSizeCtr2 + (isIncrease2 ? 1 : -1);					
						if (obj.style.lineHeight != '' || obj.getAttribute('ccshra')) {
							if (nextSize ==  mSizeRangeLow2)	 {//getback
								if (obj.getAttribute('ccshra')) {							
									obj.style.lineHeight = obj.getAttribute('ccshra');
								}
							}
							else if (parseInt(nextSize) == (parseInt(mSizeRangeLow2) + 1)) {//replace
								var attr = document.createAttribute('ccshra');
								attr.value = obj.style.lineHeight;
								obj.setAttributeNode(attr);
								obj.style.lineHeight = 'normal';
							}
						}					
				} catch (err) {};
			}

			for (var i = 0; i < obj.childNodes.length; i++) this.setFontSize2(obj.childNodes[i]); 
		}
	});
		
	var aNOTOKList = new Array(
		"/cpf_trans/ssl/portal/personalised/mymsg.asp",
		"/cpf_trans/ssl/portal/personalised/lifeevent.asp",
		"/cpf_trans/ssl/portal/personalised/myesvactivities.asp",
		"/cpf_trans/ssl/portal/personalised/mymsg_ewdl.asp");
	
	CPF2TextAddMethod(this, 'isURLIncluded2', function() {
		try {
			var result = true;
			var pathname = window.location.pathname
			pathname = String(pathname).toLowerCase();
						
			//NOT OK List
			for (i = 0; i < aNOTOKList.length; i++) {
				if (String(pathname).indexOf(aNOTOKList[i]) == 0) {									
					result = false;
				}
			}
			
			return result;
		} catch (e) {}; 	
		return false;
	});	
} 

var oCPF2TextResize = new CPF2TextResize('oCPF2TextResize');
var CPF2TextBodyOnloadFunc = function () { oCPF2TextResize.applySize2(); };

// Cookie procedures
function CPF2TextCreateCookie (name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	if(value >= oCPF2TextResize.getMinSize2() && value <= oCPF2TextResize.getMaxSize2())		
		document.cookie = name + "=" + value + expires + "; path=/";
	else
		return null;
}

function CPF2TextReadCookie(name) {
	var nameEQ = name + "=";
	var result = "";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') 
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
			result = c.substring(nameEQ.length,c.length);
	}
	
	if(result >= oCPF2TextResize.getMinSize2() && result <= oCPF2TextResize.getMaxSize2() && result != "")
		return result;			
	else
		return null;
}

try {
 	if (window.addEventListener) window.addEventListener ("load", CPF2TextBodyOnloadFunc, false);
	else if (window.attachEvent) window.attachEvent ("onload", CPF2TextBodyOnloadFunc);	
} catch (e) {}

var ICON_PRINT_SHOW;
try {
	if (ICON_PRINT_SHOW==null) {
		ICON_PRINT_SHOW = false;
	}
} catch (e) {}
/////////////////////////////////////////////////////////////////////////////////////////////