/**
 * Common utility related javascript module. It contains common utility 
 * functions related to strings, validation, positions, notification operations.
 *
 * @author Veeresh D.
 * @date March 2008
 */

/**
Trims white spaces around a given string
*/
function trim(str, chars) 
{
	if ( str != null )
    {
        str = ltrim(rtrim(str, chars), chars);
    }
    else
        str = "";   //To replace null with blank
    return str;
}

/*
OR - This will protytpes the trim builtin fuction
String.prototype.trim = function () 
{
    return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.find=function(what)
{
    return(this.indexOf(what)>=0 ? true : false);
}
*/

/**
Trims white spaces around left portion of a given string
*/
function ltrim(str, chars) 
{
    if ( str != null )
    {
        chars = chars || "\\s";
        str = str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }
    else
        str = "";   //To replace null with blank
    return str;
}

/**
Trims white spaces around right portion of a given string
*/
function rtrim(str, chars) 
{
    if ( str != null )
    {
        chars = chars || "\\s";
        str = str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    }
    else
        str = "";   //To replace null with blank
    return str;
}   

/**
Enclosed a given string with quotes and returns it
*/
String.prototype.quote = function () {
    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') 
        {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};

/**
Returns the type of object. It will be useful in comparision of type of objects
*/
function ObjTypeOf(value) 
{
    var s = typeof value;
    if (s === 'object') 
    {
        if (value) 
        {        
            if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function') 
            {
                s = 'array';
            }
        } 
        else 
        {
            s = 'null';
        }
    }
    return s;
}

/**
Checks whether the object is empty or not
*/
function isEmpty(o) 
{
    var i, v;
    if (typeOf(o) === 'object') 
    {
        for (i in o) 
        {
            v = o[i];
            if (v !== undefined && typeOf(v) !== 'function') {
                return false;
            }
        }
    }
    return true;
}

/**
Increase font size of a body content
*/
function IncreaseFontSize()
{
	var OldSize = document.getElementById("ctl00_ContentPlaceHolder1_DlstNewsDtls_ctl00_LblDtls").style.fontSize;
	newSize = OldSize.substring(0, OldSize.indexOf("px"));
	if (newSize == "")
		document.getElementById("ctl00_ContentPlaceHolder1_DlstNewsDtls_ctl00_LblDtls").style.fontSize=11;
	else
		document.getElementById("ctl00_ContentPlaceHolder1_DlstNewsDtls_ctl00_LblDtls").style.fontSize=parseInt(newSize) + 1;	
}

/**
Decrease font size of a body content
*/
function DecreaseFontSize()
{
	var OldSize = document.getElementById("ctl00_ContentPlaceHolder1_DlstNewsDtls_ctl00_LblDtls").style.fontSize;
	newSize = OldSize.substring(0, OldSize.indexOf("px"));
	if (newSize == "")
		document.getElementById("ctl00_ContentPlaceHolder1_DlstNewsDtls_ctl00_LblDtls").style.fontSize=9;
	else
		document.getElementById("ctl00_ContentPlaceHolder1_DlstNewsDtls_ctl00_LblDtls").style.fontSize=newSize - 1;
}

/**
Compares two strings and checks for equality

@param s1 String paramter1
@param s2 String paramter2
www.corpbank.in/asp/branchList.asp
@return Boolean True if both strings are equal, False if not
*/
function isSameString(s1, s2)
{
    if ( s1 != null & s2 != null )
    {
        if ( s1.toString() == s2.toString() )
   	        return true;
        else
            return false;
    }
        return false;
}

/**
Resets or clears the text fields. Innovatively, this function takes multiple
Id of text fields as a arguments and resets or empty all these fields together

@param idList List of ids of text fields seperated by commas'
*/
function resetTextField(idList)
{
    var textboxIdList = idList.split(",");
    for( var i = 0; i < textboxIdList.length; i++)
    {
        document.getElementById( trim(textboxIdList[i]) ).value = "";
    }
}

/**
Validate input fields for non-empty

@param idList List of ids of text fields seperated by commas'
*/
function validateTextField(idList)
{
    var textboxIdList = idList.split(",");
    for( var i = 0; i < textboxIdList.length; i++)
    {
        if ( document.getElementById( trim(textboxIdList[i]) ).value != "" )
        {
            return true;
        }
    }
    return false;
}

/**
Displays the notification information for a given object(body, Div)

@param divId Parent id of an object to that notification message is displayed
@param alertMessage Notification information
@param alertTime Notification status
*/
function showNotification(divId, alertMessage, alertTime)
{
	var notifyObj = document.getElementById("notifyDIV" + divId);
	if (notifyObj)
	{
		notifyObj.innerHTML = alertMessage; //Do nothing, because notification message is still active		
		notifyObj.style.display = ''; //Do nothing, because notification message is still active				
	}
	else
	{
		document.getElementById(divId).innerHTML += "<DIV id=notifyDIV" + divId +" class=notification>&nbsp;&nbsp;&nbsp;" + alertMessage +" &nbsp;&nbsp;&nbsp;</DIV>";
		notifyObj = document.getElementById("notifyDIV" + divId);
	}
	
	var x = getPosX(document.getElementById(divId));
	var y = getPosY(document.getElementById(divId));
	
	notifyObj.style.top = y + 'px';
	notifyObj.style.left = x + 'px';
	
	if ( Number(alertTime) > 0 )
		setTimeout( function(){ notifyObj.style.display = "none";	}, Number(alertTime)*1000 );	
}

/**
Hides the notification information

@param divId Parent id of an object requesting to clear or hide its notification message
*/
function hideNotification(divId)
{
	if ( document.getElementById("notifyDIV" + divId) )
		document.getElementById("notifyDIV" + divId).style.display = "none";
}

/**
Shows the notification information on the right top most position in the homepage
*/
function showTopNotification()
{
    if ( document.getElementById("homepageNotification") )
        document.getElementById("homepageNotification").style.display = "";
}

/**
Hides the top notification information on the right top most position in the homepage
*/
function hideTopNotification()
{
    if ( document.getElementById("homepageNotification") )
        document.getElementById("homepageNotification").style.display = "none";
}

/**
Shows the fallback notification information

@param divId Parent id of an object requesting to clear or hide its notification message
*/
function showFallBackNotification(divId, notificationMessage ,callBackFunDef)
{
	//var notifyObj = document.getElementById("notifyDIV" + divId);
	var notifyObj = document.getElementById(divId);
	if (notifyObj)
	{
		//notifyObj.innerHTML = "<DIV id=\"leftPanelSubjectTreeBoxDiv\" class=\"treeComponentStyles\">";
		notifyObj.innerHTML = "<img src='" + ROOT_URL + "images/information-alert.gif' /> " + notificationMessage + "<BR>";
		notifyObj.innerHTML += "<font color=blue class='monthIssue'><A href=# onclick='" + callBackFunDef +"'>&raquo;  Please try again!</A></font><BR><BR>&nbsp;";		
	}
}

/**
Hides the notification information

@param divId Parent id of an object requesting to clear or hide its notification message
*/
function showAlertiveInformation(info)
{
	var infoData = "<img src='" + ROOT_URL + "images/information-alert.gif' /> ";
	infoData += "<font color=blue class='monthIssue'>" + info +"</font>";			
	return infoData;
}

/**
Hides the notification information

@param divId Parent id of an object requesting to clear or hide its notification message
*/
function showAlertInformation(priority, Information)
{
    /*
    priority = 0 >> For Success; 
    priority = 1 >> For Failure or Warning;
    priority = 2 >> For Information;
    */
	var infoData;
	infoData = "<DIV style='padding: 5px ; border: 1px solid " + ( (priority == 0) ? "GREEN;" : (priority == 2) ? "RED;" : (priority == 1) ? "#C2CFF1;" :"SILVER;" ) + " background-color:  " + ( (priority == 0) ? "#C3F7C2;" : (priority == 1) ? "#EBEFF9;" : (priority == 2) ? "#FBB0B0;" :"SILVER;" ) + "'>"
	infoData += "<img src='" + ROOT_URL + "images/" + ( (priority == 0) ? "alertSuccess.gif" : (priority == 1) ? "alertAttention.gif" : "alertFailure.gif" ) + "' /> ";
	infoData += "<font color=" + ( (priority == 0) ? "GREEN" : (priority == 1) ? "#2244BB" : "RED" ) + " class='monthIssue'>";			
	infoData += Information + "</font>";			
	infoData += "</DIV>"
	return infoData;
}

/**
Gets the X or Left position value of an object located in the browser

@param obj Object of an element of HTMl (DIV, Table, etc)
*/
function getPosX(obj) 
{
	var curleft = 0;
	if (obj.offsetParent) 
	{
		while (obj.offsetParent) 
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

/**
Gets the Y or Top position value of an object located in the browser

@param obj Object of an element of HTMl (DIV, Table, etc)
*/
function getPosY(obj) 
{
	var curtop = 0;
	if (obj.offsetParent) 
	{
		while (obj.offsetParent) 
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/**
Set background color of an object or tag
*/
function setBgColor(keyTextId, colorName)
{
    if ( document.getElementById(keyTextId) )
	    document.getElementById(keyTextId).style.backgroundColor = colorName;	
}

/**
Set background color of an object or tag
*/
function setFontColor(keyTextId, colorName)
{
    if ( document.getElementById(keyTextId) )
        document.getElementById(keyTextId).style.color = colorName;	
}

/**
Focuses an input box with given a text
*/
function focusSearchBox(keyTextId, keyAltText)
{
	var keyword = document.getElementById(keyTextId);	
	if( keyword.value == keyAltText )
	{
		keyword.value = '';
		keyword.style.color = "black";
	}
}

/**
Unfocuses an input box with given a text
*/
function unfocusSearchBox(keyTextId, keyAltText)
{
	var keyword = document.getElementById(keyTextId);	
	if( keyword.value == '' || keyword.value == keyAltText )
	{
		keyword.value = keyAltText;
		keyword.style.color = "silver";
	}
}

/**
Focuses a button
*/
function setButtonFocus(buttonId)
{
    if ( document.getElementById(buttonId) )
        document.getElementById(buttonId).focus();    
    return;
}

/**
Hash class utility.
*/
function Hash()
{
	this.length = 0;
	this.items = new Array();		
	for (var i = 0; i < arguments.length; i += 2) 
	{
		if (typeof(arguments[i + 1]) != 'undefined') 
		{
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
   
	this.removeItem = function(in_key)
	{
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') 
		{
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}
	   
		return tmp_value;
	}

	this.getItem = function(in_key) 
	{
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		if (typeof(in_value) != 'undefined') 
		{
			if (typeof(this.items[in_key]) == 'undefined') 
			{
				this.length++;				
			}
			this.items[in_key] = in_value;
		}
	   
		return in_value;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}
}

/*
Validates required fields
*/
function validRequired(formField,fieldLabel)
{
	var result = true;
    	
    	document.getElementById(formField).value = (document.getElementById(formField).value).replace(/^\s*|\s*$/g,'');
    	
	if (document.getElementById(formField).value == '' )
	{
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		document.getElementById(formField).focus();
		result = false;
	}
	return result;
}	

/*
Validates digits
*/
function allDigits(str)
{
	return inValidCharSet(str,"0123456789-()'x' ");
}

/*
Validates invalid character sets
*/
function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	return result;
}	
	
/*
Validates number fields
*/
function validNum(formField,fieldLabel,required)
 {
	var result = true;
	
	if (required && !validRequired(formField,fieldLabel))
		result = false;
	if (result)
	{
		if (!allDigits(document.getElementById(formField).value))
		{
			alert('Please enter a number for the "' + fieldLabel +'" field.');
			document.getElementById(formField).focus();
			result = false;
		}
	}
	return result;
}


/*
Validates Notes Field
*/
function validNotes(formField)
{
	var result = true;

	var iChars = "%&?"; 
		for (var i = 0; i < document.getElementById(formField).value.length; i++) 
		{ 
			if (iChars.indexOf(document.getElementById(formField).value.charAt(i)) != -1)
			{
			alert ("Characters % & ? are not allowed");   
			result = false;  
			return result;
			}                                
		}

	
	return result;
}


/*
Validates proper email format
*/
function validEmail(formField,fieldLabel,required)
{
	var result = true;

	if (required && !validRequired(formField,fieldLabel))
		result = false;

	if (result && ((document.getElementById(formField).value.length < 3) || !isEmailAddr(document.getElementById(formField).value)) )
	{
		alert("Please enter a complete email address in the form: yourname@yourdomain.com");
		document.getElementById(formField).focus();
		result = false;
	}
	return result;
}

/*
Validates email
*/
function isEmailAddr(email)
{
	var result = false;
	var theStr = new String(email);
	var index = theStr.indexOf("@");
	
	if (index > 0)
	{
	    var pindex = theStr.indexOf(".",index);
	    if ((pindex > index+1) && (theStr.length > pindex+1))
	    result = true;
	}
	return result;
}

/*
Validates user name
*/
function getProperName(userName)
{
    var newName = "";
    if ( typeof(userName) == "string" )
        newName = userName;
    else    
        newName = "";
    return newName;
}

/*
Validates user name
*/
function validateDataItem(prefixText, userName)
{
    if ( ( typeof(userName) == "string" || typeof(userName) == "number" ) &&  userName != "" )
        return(prefixText + userName);
    else    
    {
        return "";
    }
}

/*
Highlight word in search results
*/
function highLightKeyword(inputText, keyword)
{
    var temp = inputText;
    //var color = "#2E61AF";    //Dark Steelblue
    var color = "LIMEGREEN";    //Blue
    /* If the keyword length is more than one, because a single letter can be a part of every word, so it avoid it */
    keyword = trim(keyword);
    if ( keyword.length > 1 && inputText != null )// && loginStatus == false
	{
        /* Highlighting the searched keywords */
	    var upper = keyword.substr(0,1).toUpperCase();
        var lower = keyword.substr(1).toLowerCase();
        
        if ( inputText.indexOf(keyword +"</font>") < 0 )
            temp = temp.replaceAll(keyword, "<B><FONT color=" +color+ ">" + keyword +"</FONT></B>"); 
        if ( inputText.indexOf((upper + lower) + "</font>") < 0 )
            temp = temp.replaceAll((upper + lower), "<B><FONT color=" +color+ ">" + (upper + lower) +"</FONT></B>"); 
        if ( inputText.indexOf(keyword.toLowerCase() +"</font>") < 0 )
            temp = temp.replaceAll(keyword.toLowerCase(), "<B><FONT color=" +color+ ">" + keyword.toLowerCase() + "</FONT></B>"); 
	    if ( inputText.indexOf(keyword.toUpperCase() +"</font>") < 0 )
            temp = temp.replaceAll(keyword.toUpperCase(), "<B><FONT color=" +color+ ">" + keyword.toUpperCase() + "</FONT></B>");
        //*/
	}	
	return temp;
}

/*
It defines the croww browser style rules for color button.
It is partiuclarly written for browser which does not support
disable feature of a button.
*/
function getButtonClass()
{
    if ( getBrowserName() == "Safari" || getBrowserName() == "Mozilla"  || getBrowserName() == "Firefox" )
        return "";
    else    
        return "class=button_bluesmall";       
}

/*
Format comma seperate numbers (Ex: 12345 => 12,345, 1234567 => 1,234,567)
*/
function formatCSNumber(number)
{
    var fno = "";
	var slen;
	var ilen;
	slen = number.length;
	ilen = parseInt(slen / 3);
	
	var s = 0, e;

	if (slen <= 3)
		fno = number;
	else if (slen % 3 != 0 && slen > 3)
	{
		s = slen - (ilen) * 3;
		fno = number.substring(0, s);
	}	
	for (var i = 0; i < ilen && slen > 3; i++)
	{
		e = s + 3;
		fno = fno + ((fno == "") ? "" : ",") + number.substring(s, e);
		s = s + 3;
	}  
	return fno;
}

/*
Implements the replace all function. It replaces every occurance of s1 with s2
*/
String.prototype.replaceAll = function(s1, s2) 
{
    return this.split(s1).join(s2)
}

/*
Loads the CSS or Javascript files dynamically
*/
function loadJsCssFile( filename, filetype )
{
    if ( filetype == "js" )
    {   //if filename is a external JavaScript file
        var fileref = document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
     }
    else if ( filetype == "css" )
    {   //if filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename);
     }
     
    if ( typeof fileref != "undefined" )
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

/**
Shows the current date information over bottom right portion of tab compoent
*/
function getfullDateValue()
{
	var dateStr;
	var d = new Date();
	var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
	var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	dateStr = weekday[d.getDay()] + ", ";
	dateStr += ( (d.getDate()<10) ? "0" + d.getDate() : d.getDate()) + " "; //Rounds the date part as a two digit value
	dateStr += monthname[d.getMonth()] + ", ";
	dateStr += d.getFullYear();
	
	document.getElementById("tabbedDatePart").innerHTML = dateStr;
}

/**
Extracts the file name of the image of the tree node from the URI address

@param pf URL of the image of the tree()
@return str Document/Image file name
*/
function getURIFileName(pf)
{
	fullURL = pf;
	x = fullURL.length;
	while( (fullURL.substring(x, x-1)) != "/")
		x--;
	clipstart = x;
	return fullURL.substring(fullURL.length, clipstart);
}

/**
Converts special characters to ASCII unicode characters or entities
Following are considered:
'&' (ampersand) becomes '&amp;' 
'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set. 
''' (single quote) becomes '&#039;' only when ENT_QUOTES is set. 
'<' (less than) becomes '&lt;' 
'>' (greater than) becomes '&gt;'

@param data Data containing special characters
@return str Document/Image file name
*/
function convertSpecialCharacters(data)
{
	var str = data;
	str = str.replaceAll("&","&amp;");
	str = str.replaceAll("\"","&quot;");
	str = str.replaceAll("'","&#039;");
	str = str.replaceAll("<","&lt;");
	str = str.replaceAll(">","&gt;");	
	return str;
}

function confirmAlert(str)
{
    components.hideDialogBoxBackground();
    var answer = confirm(str);
    components.showDialogBoxBackground();        
    return answer;  
}

function mycomsocFontResize(id)
{
	var container = document.getElementById(id);
	container.style.fontsize = "20px";
}

/*
Setting Runtime Attributes
for (i=0;i<document.links.length;i++)
{
    document.links[i].setAttribute("onclick","alert('onClick')");
    document.links[i].setAttribute("href","javascript:alert('href')");
}
*/

