// Add trim support to Javascript
String.prototype.lTrim=new Function("return this.replace(/^\\s+/,'')");
String.prototype.rTrim=new Function("return this.replace(/\\s+$/,'')");
String.prototype.trim=new Function("return this.replace(/^\\s+|\\s+$/g,'')");
String.prototype.reverse = function(){return this.split("").reverse().join("");}
/* Usage:
var myString = "sysadminmp ";
alert(myString.trim());
alerts "sysadminmp"
*/
function initFontChange(){}
function checkAll(cFormName) {
	var oForm = document.forms[cFormName];
	for (var i = 0; i < oForm.elements.length; i++){
		if(oForm.elements[i].type == 'checkbox'){
			oForm.elements[i].checked = true;
		}
	}
}

function uncheckAll(cFormName) {
	var oForm = document.forms[cFormName];
	for (var i = 0; i < oForm.elements.length; i++){
		if(oForm.elements[i].type == 'checkbox'){
			oForm.elements[i].checked = false;
		}
	}
}
function GetCookie (c_name) {
	
	if (document.cookie.length>0)
	  {	  
	  c_start=document.cookie.toUpperCase().indexOf(c_name.toUpperCase() + "=")
	  if (c_start!=-1)
	    { 
	    c_start=c_start + c_name.length+1 
	    c_end=document.cookie.indexOf(";",c_start)
	    if (c_end==-1) c_end=document.cookie.length
	    return unescape(document.cookie.substring(c_start,c_end))
	    } 
	  }
	return null
}


function DeleteCookie( name, path, domain ) {
if ( GetCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function SetCookie (name, value , nExpireHours) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : "/";
	var cHostName = window.location.hostname;
	var domain = (argc > 4) ? argv[4] : (cHostName.match(/\./g).length > 1 ? cHostName.substr(cHostName.indexOf('.') + 1,cHostName.length) : cHostName);
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + (new Date((new Date()).getTime() + nExpireHours*3600000)).toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}


function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
}

function changeBG(elmID, color) {
	document.getElementById(elmID).style.backgroundColor = color
}
function isSSL(){
	var cProtocol = window.location.protocol.toString();
	if(!cProtocol.match(/https:/i))
	    return false;
	else
	    return true;
}

function getDisplayDate(elementToPut, whatToDisplay) {
	var oElement = document.getElementById(elementToPut);
	var currentData = oElement.innerHTML;
	var myDate = new Date();
	switch(whatToDisplay){	
		case "year":
			thisYear = myDate.getFullYear();
			oElement.innerHTML = currentData+thisYear;
		break;
		case "month":
			thisMonth = (myDate.getMonth())+1;
			oElement.innerHTML = currentData+thisMonth;
		break;
		case "day":
			thisDay = myDate.getDate();
			oElement.innerHTML = currentData+thisDay;
		break;		
	}
}

// ********** Get current date and update select list **********

function setSelectCurrDate(elmID, numDig, output) {
	var myDate = new Date();
	var thisOutput = null;
	
	if (output == "month") {
		thisOutput = (myDate.getMonth())+1;
	} else if (output == "day") {
		thisOutput = myDate.getDate();
	} else if (output == "year") {
		thisOutput = myDate.getFullYear();
	}
	
	if (thisOutput < 10) {
		thisOutput = "0"+thisOutput
	}
	
	thisOutput += '';
	
	var outputLen = thisOutput.length;
	var outputOffset = outputLen-numDig
	
	thisOutput = thisOutput.substring(outputOffset, outputLen)
	
	var optionElm = document.getElementById(elmID).options
	var optionLen = optionElm.length
		
	for (i=0; i<optionLen; i++) {
		if (optionElm[i].value == thisOutput) {
			optionElm[i].selected = true;
			i = optionLen
		}
	}
}

function fixPng(){
	try{var cMSIEString = navigator.userAgent.match(/msie\s\d/i).toString();}catch(e){}
	if(cMSIEString){
		if(cMSIEString.replace(/msie\s/i,'') < 7){
			var bIsSSL = isSSL();
			for(var i = 0;i<arguments.length;i++){
				if(typeof(arguments[i]) == 'object'){           
					var el = arguments[i];
				}else{
					try{
						var el = document.getElementById(arguments[i]);
					}catch(e){return}
				}
				try{
					if(el.tagName == "IMG" || el.tagName == "TD"){
						var bg = el.currentStyle.backgroundImage;
						if(el.tagName == "IMG"){
							var img = el;
						}
						if (bg && bg.match(/\.png/i) != null) {
							var img = bg.substring(5,bg.length-2);
							var offset = el.style["background-position"];
							el.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img+"', sizingMethod='scale')";
							if(!bIsSSL)
								el.style.backgroundImage = "url('http://images.ifriends.net/if_v2/transparentpixel.gif')";
							else
								el.style.backgroundImage = "url('https://images.ifriends.net/if_v2/transparentpixel.gif')";
							el.style["background-position"] = offset; // reapply
						} else if (img && img.src.match(/\.png$/i) != null) {
							var src = img.src;
							el.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')"
							if(!bIsSSL)
								el.src = "http://images.ifriends.net/if_v2/transparentpixel.gif";
							else
								el.src = "https://images.ifriends.net/if_v2/transparentpixel.gif";
						}
						img = null;
						bg = null;
					}
				}catch(e){}
			}
		}
	}
}

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName);
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}


// ********** Default a SELECT listbox to a preferred value: ********
function IFSetSelectValue(FormName, FieldName, cValue) {
	if (cValue != "" && typeof(cValue) != "undefined")
	{
		var i = 0;
		var nFound = 0;
		//alert("FormName: "+FormName+" \nFieldName: "+FieldName+"\ncValue:"+cValue);
		var selList = document.forms[FormName].elements[FieldName].options;
		var nArrayLen = selList.length;

		for( i = 0; i < nArrayLen; i++ )
		{
				if (document.forms[FormName].elements[FieldName].options[i].value == cValue)
				{
				 nFound = i;
				 i = nArrayLen;
				}
		}
		document.forms[FormName].elements[FieldName].selectedIndex = nFound;

	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}
															
// ********** Convert a string to add leading zeros **********

function Cvt_to_LeadingZeros(inputValue, numChars) {
	var currNumChars = inputValue.length;
	var addtCharsNeeded = numChars-currNumChars;
	var outputData = "";
	
	for (i=0; i<addtCharsNeeded; i++) {
		outputData += "0";
	}
	
	outputData += inputValue
	
	return outputData;
}

function IFgetTimeZoneOffset(){  //Returns the GMT offset in hours of the client (i.e., -5)
	var d = new Date()
	return (d.getTimezoneOffset()/60) * -1
}


// ********** Add page to user's favorites **********

/*
function addBookmarkForBrowser(urlAddress, pageName) {
	if (window.external) {
		window.external.AddFavorite(urlAddress,pageName)
	} else { 
		alert("Sorry! Your browser doesn't support this function.");
	}
}*/

 function addBookmarkForBrowser(urlAddress, pageName) {
	 if (window.sidebar) {
		 window.sidebar.addPanel(pageName, urlAddress,"");
	 } else if( window.external ) {
		 window.external.AddFavorite( urlAddress, pageName);
	 }else {
	 	window.location.href = urlAddress;
	 }
	 return false;
 }

function countCharacters(counterID, txtID, numCharsAllowed) {
	var counterElm = document.getElementById(counterID)
	var txtElm = document.getElementById(txtID)

	charsLeft = numCharsAllowed-txtElm.value.length;
	if (charsLeft <= 0) {
		txtElm.value = txtElm.value.substring(0, 250);
		counterElm.value = 0;
	} else {
		counterElm.value = charsLeft
	}
}


// ********** Word Counter **********
function countWords(stringCheck) {
	stringCheck.trim();
	checkWordCount = stringCheck.split(" ");	
	var wordCount = checkWordCount.length
	
	return wordCount;
}

//********** Wrench Icon **************

/*
This function appends name value pairs to a URL. (Often used for the Standard VCH-Edit Links present in self-edit facilities 
(i.e., appendUrlNameValue('pVchEdit', 'true') appends "&pVchEdit=true" to the URL and redirect to that location).
*/
function appendUrlNameValue(cName, cValue){
	var cLocation = window.location.toString();
	if(cLocation.lastIndexOf("#") > -1){
		//var cNamedAnchor = cLocation.substr(cLocation.lastIndexOf("#"), cLocation.length)
		cLocation = cLocation.substr(0,cLocation.lastIndexOf("#"));		
	}		
	var cUrlParams = "";
	for(var i=0;i<arguments.length;i+=2){
		cUrlParams += '&' + arguments[i] + '=' + arguments[i+1]
	}
	window.location = cLocation + cUrlParams;
}
/*
This function removes name value pairs from a URL. (Often used for the Standard VCH-Edit Links present in self-edit facilities 
(i.e., removeUrlNameValue('pVchEdit', 'true') removes "&pVchEdit=true" from the URL and redirect to that location). 
*/
function removeUrlNameValue(cName, cValue){
	var cLocation = window.location.toString();
	var myRegEx = null;
	for(var i=0;i<arguments.length;i+=2){
		if(arguments[i+1] != "*"){
			myRegEx = new RegExp("&"+arguments[i] + '=' + arguments[i+1] ,"i");
		}else{
			myRegEx = new RegExp("&"+arguments[i] + "=\\w{0,}","i");			
		}		
		cLocation = cLocation.replace(myRegEx,'');
	}
	window.location = cLocation;
}

//********** Add to Private Collection button **************
function add2PrivateCollection(cPClub , cArchiveRef, cArchivePath, cFilterStatus, cIsCensorDesignated, cImagepathType, cPostDateTimeStamp , cArchiveOverlayType){
	SetCookie("Add2PrivateArchivePath",encodeURI(cArchivePath));
	SetCookie("Add2PrivateOverlayType",cArchiveOverlayType);
	SetCookie("Add2PrivatePostDateTimeStamp",cPostDateTimeStamp);	
	SetCookie("Add2PrivateImagePathType",cImagepathType);	
	SetCookie("Add2PrivateArchiveRef",cArchiveRef);		
	if(cFilterStatus.match(/teaser/i)){
		SetCookie("Add2PrivateFilterStatus","Teaser");
	}else{
		SetCookie("Add2PrivateFilterStatus","FansOnly");
	}
	SetCookie("Add2PrivateIsCensorDesignated",cIsCensorDesignated);	
	window.location='/ifpage.dll?t=site/fanclubs/misc/Add2privatecollection/main&pClub='+cPClub;
}

function swapUnavailableImage(oImage, nWidth , nHeight, cArchiveOverlayType, fnOnComplete){
	if(nWidth <= 80){
		oImage.src = "http://images.ifriends.net/if_v2/ifriends/Generic_Image_Unavailable_12.jpg";
	}else{
		oImage.src = "http://images.ifriends.net/if_v2/ifriends/Generic_Image_Unavailable.jpg";
	}
	oImage.onerror = null;
	var oParentDiv = oImage.parentNode;	
	var arrAnchors = oParentDiv.getElementsByTagName('A');	
	for(var i=0;i<arrAnchors.length;i++){
		if(arrAnchors[i].className.match(/anchArchiveImageHyperlink/)){
			arrAnchors[i].removeAttribute("href")
			i=arrAnchors.length;
		}	
	}
	if(cArchiveOverlayType.toUpperCase() == "NONE"){
		document.getElementById('divUnavailableArchiveImageOuter').style.height = nHeight;
		var oOverlayImage = document.getElementById('imgUnavailableArchiveImageOverlay');
		oOverlayImage.style.width = nWidth;
		oOverlayImage.style.height = nHeight;
		var oImageUnavailableTopDiv = document.getElementById('divImageUnavailableTop').cloneNode(true);
		var oImageUnavailableBottomDiv = document.getElementById('divImageUnavailableBottom').cloneNode(true);
		oParentDiv.appendChild(oImageUnavailableTopDiv);
		oParentDiv.appendChild(oImageUnavailableBottomDiv);
		oImageUnavailableTopDiv.style.display = '';
		oImageUnavailableBottomDiv.style.display = '';
	}
	if(typeof(fnOnComplete) != 'undefined')
		fnOnComplete();
}

function swapUnavailableProfileImage(oImage, opts){
	oImage.onerror = null;
	var nHeight = opts['height'];	
	if(nHeight > 120){
		var cFileSuffix = '';
	}else if(nHeight > 30){
		var cFileSuffix = '12';
	}else{
		var cFileSuffix = 'sm';
	}
	if(!window.location.href.toString().match(/\.ifriends/gi)){	
		cFileSuffix = '_gray' + cFileSuffix;
	}else if(GetCookie('SiteCodeLast') != null){
		if(!GetCookie('SiteCodeLast').match(/ifriends/gi)){
			cFileSuffix = '_gray' + cFileSuffix;
		}
	}
	var cGender = 'unisex';
	cGender = (typeof(opts['gender']) != 'undefined' ? opts['gender'] : cGender);
	cGender = (cGender == '' || cGender == 'null' || cGender.toUpperCase() == 'TS'  ? 'unisex' : cGender);
	oImage.src = "http://images.ifriends.net/if_v2/Ifriends/Lang1/generic_" + cGender + cFileSuffix+".jpg";
	oImage.width = (typeof(opts['width']) != 'undefined' ? opts['width'] : oImage.width);
	oImage.height = (typeof(opts['height']) != 'undefined' ? opts['height'] : oImage.height);
	if(typeof(opts['removeImageOnError'])){
		if(opts['removeImageOnError'] == true){
			var oParent = oImage.parentNode;
			oParent.removeChild(oImage);
			oImage = null;
		}
	}
	return oImage;
}
function templatePager(cPlusOrMinus ,cUniqueID,  nMaxRecords, cStartCounter , nCurrStart , nCurrEnd){
	var cLocation=window.location.toString();
	if(cStartCounter != ''){
		var regExpStart = new RegExp("pStartCounter"+cUniqueID+"=(\\d{1,})","i");
		var regExpEnd = new RegExp("pEndCounter"+cUniqueID+"=(\\d{1,})","i");
		var cCurrStart = cLocation.match(regExpStart)[1]
		var cCurrEnd = cLocation.match(regExpEnd)[1]
		if(cPlusOrMinus == "+"){
			cLocation = cLocation.replace(regExpStart,'pStartCounter'+cUniqueID+'=' + ((cCurrEnd * 1) + 1))
			cLocation = cLocation.replace(regExpEnd,'pEndCounter'+cUniqueID+'=' + ((cCurrEnd * 1)  + nMaxRecords))
		}else{
			cLocation = cLocation.replace(regExpStart,'pStartCounter'+cUniqueID+'=' + ((cCurrStart * 1) - nMaxRecords))
			cLocation = cLocation.replace(regExpEnd,'pEndCounter'+cUniqueID+'=' + ((cCurrEnd * 1)  - nMaxRecords))
		}
		window.location = cLocation;
	}else{
		if(cPlusOrMinus == "+"){
			window.location = cLocation + '&pStartCounter'+cUniqueID+'=' + ((nCurrEnd * 1) + 1) + '&pEndCounter'+cUniqueID+'=' +  ((nCurrEnd * 1)  + nMaxRecords);
		}
	}
}
function openPopupWindow(cURL , cName , cPopupOptions){
  var win= window.open(cURL, cName, cPopupOptions);
  win.focus();	   
}

String.prototype.appendOrReplaceURLParameter = function(cURLParamToReplaceOrAppend , cNewValue){
	var regExpURLParam = new RegExp("(\\?|&)"+cURLParamToReplaceOrAppend +"=[a-zA-Z0-9_\-]*" , "gi");
	var cURLString = this;
	var cNamedAnchor = '';
	if(cURLString.lastIndexOf("#") > -1){
		cNamedAnchor = cURLString.substr(cURLString.lastIndexOf("#"), cURLString.length)
		cURLString = cURLString.substr(0,cURLString.lastIndexOf("#"));
	}
	var cFoundString = cURLString.match(regExpURLParam)
	if(cFoundString != null){
		cURLString= cURLString.replace(cURLString.match(regExpURLParam) , cFoundString.toString().substr(0,1) + cURLParamToReplaceOrAppend + '=' + cNewValue)+cNamedAnchor
	}else{
		cURLString= cURLString+ (cURLString.match(/\?/) ? '&' : '?' ) + cURLParamToReplaceOrAppend +'=' + cNewValue+cNamedAnchor
	}
	return cURLString;
}


function purgeImage(cImagePath){
	var cURL = '/ifpage.dll?t=tools/purgeAKImage&pImageURL='+cImagePath;
	Ajax.Execute(cURL , function(cResponse){});
}

function swapMissingLanguageSpecificImage(oImage){
	oImage.onerror = null;
	var cSource = oImage.src;
	var regExpLangFolder = new RegExp("\/lang\\d{1,}\/" , "gi");
	if(cSource.match(regExpLangFolder)){
		oImage.src = cSource.replace(regExpLangFolder , "/lang1/");
	}
}
