/********************************************************************************************************
 * 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 CPFTextAddMethod(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.CPFTextInArray = 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 CPFTextResize (val) {
	var aSizeList = new Array();
	aSizeList[1] = "90%";
	aSizeList[2] = "95%";
	aSizeList[3] = "xx-small";
	aSizeList[4] = "x-small";
	aSizeList[5] = "small";
	aSizeList[6] = "medium";		
	aSizeList[7] = "large";
	aSizeList[8] = "x-large";
	
	var aExcludeTag = new Array();
	aExcludeTag[0] = "#DOCUMENT";
	aExcludeTag[1] = "HTML";
	aExcludeTag[2] = "HEAD";
	aExcludeTag[3] = "TITLE";
	aExcludeTag[4] = "SCRIPT";
	aExcludeTag[5] = "#comment";
	aExcludeTag[6] = "BR";
	
	var aExcludeFixTag = new Array();
	aExcludeFixTag[0] = "TABLE";
	aExcludeFixTag[1] = "TH";
	aExcludeFixTag[2] = "TBODY";
	aExcludeFixTag[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 = '/Style%20Library/Images/';
	
	var mDefaultIncreaseImage =  mImagePath + 'font_plus.gif';	
	var mDefaultDecreaseImage = mImagePath + 'font_minus.gif';
	var mDefaultDisabledAddImage = mImagePath + 'font_plus.gif'; // default disabled image for plus
	var mDefaultDisabledMinusImage = mImagePath + 'font_minus.gif'; // default disabled image for minus
	var mPrinterImage = mImagePath + 'printer.gif';
	
	var mIncreaseImageAltText = 'Click here for bigger text';
	var mDecreaseImageAltText = 'Click here for smaller text';
	var mDisabledAltText =      'This icon is deactivated';
	var mPrinterImageAltText =  'Printer-friendly page';
	
	var mSizeRangeLow = 0;
	var mSizeRangeHigh = 3;
	var intSizeCtr = 0; // Size stopper
	
	var isIncrease;
	var isFix = false;
	var mObjName = val;
	var isPrinterIconInstalled = false;
	try { var isNewToolTipInstalled = (Tip != undefined) } catch(e) { var isNewToolTipInstalled = false }
	var isPageTracked = false;
	var tracker = '/cpf/TextResizeCall.aspx';
	
	CPFTextAddMethod(this, 'showNewToolTip', function(sFrom) {
		if (sFrom == "increase")
			Tip(intSizeCtr == mSizeRangeHigh ? mDisabledAltText : mIncreaseImageAltText, WZ_BGCOLOR, '#FFFFCC', WZ_SHADOW, true, WZ_FONTSIZE, '14px')
		else //decrease
			Tip(intSizeCtr == mSizeRangeLow  ? mDisabledAltText : mDecreaseImageAltText, WZ_BGCOLOR, '#FFFFCC', WZ_SHADOW, true, WZ_FONTSIZE, '14px')
	});	
	
	CPFTextAddMethod(this, 'getMaxSize', function() { return mSizeRangeHigh; });	
	CPFTextAddMethod(this, 'getMinSize', function() { return mSizeRangeLow; });	
	
	CPFTextAddMethod(this, 'installIncreaseIcon', function() { this.installIncreaseIcon(mDefaultIncreaseImage); });	
	CPFTextAddMethod(this, 'installDecreaseIcon', function() { this.installDecreaseIcon(mDefaultDisabledMinusImage); });	
	CPFTextAddMethod(this, 'installIncreaseIcon', function(image) { 
		document.write ('<span><image style="cursor: hand;" id="CPFTextIncreaseIcon" src="' + image + '" onclick="javascript:' + mObjName + '.doIncrease();" ' + 
		                (isNewToolTipInstalled ? 'onMouseOver="' + mObjName + '.showNewToolTip(\'increase\')" onMouseOut="UnTip()"' : 'title= "' + mIncreaseImageAltText + '"') +
		                '></span>'); 
	});		

	CPFTextAddMethod(this, 'installDecreaseIcon', function(image) { 
		document.write ('<span><image style="cursor: hand;" id="CPFTextDecreaseIcon" src="' + image + '" onclick="javascript:' + mObjName + '.doDecrease();" ' + 
				(isNewToolTipInstalled ? 'onMouseOver="' + mObjName + '.showNewToolTip(\'decrease\')" onMouseOut="UnTip()"' : 'title= "' + mDecreaseImageAltText + '"') +
		                '></span>');
	});
	
	CPFTextAddMethod(this, 'installPrinterIcon', function() {  
		document.write ('<span><image style="cursor: hand;" id="CPFPPrinterIcon" title= "' + mPrinterImageAltText + '" src="' + mPrinterImage + '" onclick="javascript:' + mObjName + '.print();"></span>');	
		isPrinterIconInstalled = true;
	});
	
	CPFTextAddMethod(this, 'install', function() { if (this.isURLIncluded()) {this.install(0);} });
	CPFTextAddMethod(this, 'install', function(numSpace) { 
		document.write ('<nobr>');		
		this.installIncreaseIcon(); 
		for (var i = 0; i < numSpace; i++) document.write ('<image src="' + mImagePath +'spacer.png">');//spacing
		this.installDecreaseIcon();
		if (ICON_PRINT_SHOW) this.installPrinterIcon();
		document.write ('</nobr>');
	});
	
	CPFTextAddMethod(this, 'print', function() { try {return ICON_PRINT_ON_CLICK()} catch(e) {} });
	
	CPFTextAddMethod(this, 'fixHTML', function(obj) { 		
		try {			 			 
		  
			  for (var i = 0; i < obj.childNodes.length; i++) {
			  	   var l = obj.childNodes[i];
				   this.setupFontStyle(l);   
					   if ((!aExcludeFixTag.CPFTextInArray(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.fixHTML(obj.childNodes[i]); 
		} catch(err){};
		isFix = true;
	});
	CPFTextAddMethod(this, 'setupFontStyle', 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){}
				}
		}
	});
	CPFTextAddMethod(this, 'toggleIcons', function() {
		CPFTextCreateCookie("CPFTextSize", intSizeCtr);
	    if (intSizeCtr == mSizeRangeLow) {
			//disable Decrease
			window.document.getElementById("CPFTextDecreaseIcon").src = mDefaultDisabledMinusImage;
			if (!isNewToolTipInstalled)
				window.document.getElementById("CPFTextDecreaseIcon").title = mDisabledAltText;							
		} else 
			if (intSizeCtr == mSizeRangeHigh) {
				//disable Increase
				window.document.getElementById("CPFTextIncreaseIcon").src = mDefaultDisabledAddImage;
				if (!isNewToolTipInstalled)
					window.document.getElementById("CPFTextIncreaseIcon").title = mDisabledAltText;
			} else {
				//enable All
				window.document.getElementById("CPFTextIncreaseIcon").src = mDefaultIncreaseImage;
				window.document.getElementById("CPFTextDecreaseIcon").src = mDefaultDecreaseImage;
				if (!isNewToolTipInstalled) {
					window.document.getElementById("CPFTextIncreaseIcon").title = mIncreaseImageAltText;
					window.document.getElementById("CPFTextDecreaseIcon").title = mDecreaseImageAltText;
				}
			}
	});

	CPFTextAddMethod(this, 'increase', function() {
		if (!isFix) this.fixHTML(window.document.body);
	    	isIncrease = true;
		if (intSizeCtr < mSizeRangeHigh) {
			this.setFontSize(window.document.body);	
			intSizeCtr++;
		} 
		
		this.toggleIcons();
	});
	
	CPFTextAddMethod(this, 'trackThisPage', 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", tracker + '?host='+ window.location.hostname +'&path=' + window.location.pathname + '&action=' + (isIncrease ? 'plus' :'minus'), true);
				xmlHttp.send(null);
			} catch (e) {}
			
			isPageTracked = true;
			return true;
	});

	CPFTextAddMethod(this, 'doIncrease', function() {
		this.increase();
		if (!isPageTracked) this.trackThisPage();
	});
	
	CPFTextAddMethod(this, 'doDecrease', function() {
		this.decrease();
		if (!isPageTracked) this.trackThisPage();
	});
	
	CPFTextAddMethod(this, 'decrease', function() {
		if (!isFix) this.fixHTML(window.document.body);
	    	isIncrease = false;
		if (intSizeCtr > mSizeRangeLow) {
		    	this.setFontSize(window.document.body);
			intSizeCtr--;
		} 

		this.toggleIcons();
	});

	CPFTextAddMethod(this, 'applySize', function() { var mSavedSize = CPFTextReadCookie("CPFTextSize"); this.applySize(mSavedSize == "" ? 0 : mSavedSize); });	
	CPFTextAddMethod(this, 'applySize', function(theSize) {
		if (intSizeCtr != theSize) 
			if (intSizeCtr < theSize) 
				for (var i = intSizeCtr; i < theSize; i++) this.increase();				
			else 
				for (var i = intSizeCtr; i > theSize; i--) this.decrease();
		else
			this.toggleIcons();	
	});
	
	CPFTextAddMethod(this, 'getStyle', 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;
	});
	
	
	CPFTextAddMethod(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;
	});
	
	CPFTextAddMethod(this, 'setFontSize', function(obj) {
		if (obj.id != 'CPFToolTip') {
			if (!aExcludeTag.CPFTextInArray(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 = isIncrease ? parseInt(currFontSize2) + 1 : parseInt(currFontSize2) - 1;											
						} else {
							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 = isIncrease ? currComputedFontSize + 1 : currComputedFontSize - 1;											
									obj.style.fontSize = aSizeList[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 = isIncrease ? (parseFloat(currComputedFontSize) + 0.2) : (parseFloat(currComputedFontSize) - 0.2);						
									else 
										currComputedFontSize = isIncrease ? currComputedFontSize + 2 : currComputedFontSize - 2;						

									obj.style.fontSize = currComputedFontSize + strCurrentTag;
									bolBrowserFF = 0;
								}						
							}
						}	

						var nextSize = intSizeCtr + (isIncrease ? 1 : -1);					
						if (obj.style.lineHeight != '' || obj.getAttribute('ccshra')) {
							if (nextSize ==  mSizeRangeLow)	 {//getback
								if (obj.getAttribute('ccshra')) {							
									obj.style.lineHeight = obj.getAttribute('ccshra');
								}
							}
							else if (parseInt(nextSize) == (parseInt(mSizeRangeLow) + 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.setFontSize(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");
	
	CPFTextAddMethod(this, 'isURLIncluded', 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 oCPFTextResize = new CPFTextResize('oCPFTextResize');
var CPFTextBodyOnloadFunc = function () { oCPFTextResize.applySize(); };

// Cookie procedures
function CPFTextCreateCookie (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 >= oCPFTextResize.getMinSize() && value <= oCPFTextResize.getMaxSize())		
		document.cookie = name + "=" + value + expires + "; path=/";
	else
		return null;
}

function CPFTextReadCookie(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 >= oCPFTextResize.getMinSize() && result <= oCPFTextResize.getMaxSize() && result != "")
		return result;			
	else
		return null;
}

try {
 	if (window.addEventListener) window.addEventListener ("load", CPFTextBodyOnloadFunc, false);
	else if (window.attachEvent) window.attachEvent ("onload", CPFTextBodyOnloadFunc);	
} catch (e) {}

var ICON_PRINT_SHOW;
try {
	if (ICON_PRINT_SHOW==null) {
		ICON_PRINT_SHOW = false;
	}
} catch (e) {}
/////////////////////////////////////////////////////////////////////////////////////////////