/**
  *		Created by : Kathirvel.P
  */
var g_content_max_allowed = 10000;
function ce( t ) { return document.createElement( t ); }
function ge( t ) { return document.getElementById( t ); }

function insertAfter(node, referenceNode) {
  referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
}

function isdefined( variable) {
	return (typeof(variable) == "undefined")?  false: true;
}

function isnumber( variable) {
	return (typeof(variable) == "number")?  false: true;
}

//	common error handler.
function alertError(pmErrorObject)	{
	try	{
		if(browser.isIE) {
			vErrNo	=	pmErrorObject.number  & 0xFFFF
			alert("Err No	: " + vErrNo +"\nErr Desc   : "+ pmErrorObject.description);
		} else {
			alert("File	: " + pmErrorObject.fileName +"\nLine	: " +pmErrorObject.lineNumber +"\nErr Desc: "+ pmErrorObject.message);
		}			
	} catch(error) {
		alert(error.description);
	}
}

//	Check & evaluvate pressed key.
function gPauseSplKeys(pmKeyType) {
	/* Function that allows only Alpahabets,Numbers. This is to be called in the "KeyPress" event of a Text control 
	   pmKeyType  - 1 (Only Alphabets) and some special character  "white space - / ,'"
	   pmKeyType  - 2 (Only Numeric)
	   pmKeyType  - 3 (For Alphanumeric)
	   pmKeyType  - 4 (For Email)
	   pmKeyType -  5 (For Phone) */
	   
	// Variable to store the value of "KeyCode".		
	vKeyCode = window.event.keyCode;		
	if((vKeyCode > 64 && vKeyCode < 91) && (pmKeyType == 1 || pmKeyType == 3 || pmKeyType == 4))	{
		// Check if the "KeyCode" is from "A" to "Z".
		window.status ="Done";
		window.event.keyCode = vKeyCode; 
	} else if((vKeyCode > 96 && vKeyCode < 123) && (pmKeyType == 1 || pmKeyType == 3 || pmKeyType == 4))	{
		// Check if the "KeyCode" is from "a" to "z".
		window.status = "Done";
		window.event.keyCode = vKeyCode; 
	} else if((vKeyCode > 47 && vKeyCode < 58) && (pmKeyType == 2 || pmKeyType == 3 || pmKeyType == 4 || pmKeyType == 5)) 	{
		// Check if the "KeyCode" is from "0" to "9".
		window.status ="Done";
		window.event.keyCode = vKeyCode; 
	}	else if(((vKeyCode == 40) || (vKeyCode == 41) || (vKeyCode == 45)) && (pmKeyType == 5)) 	{
		// Check if the "KeyCode" is  "()-"
		window.status ="Done";
		window.event.keyCode = vKeyCode; 
	} else if((vKeyCode == 32 || vKeyCode == 47 || vKeyCode == 45 || vKeyCode == 39 || vKeyCode == 44) && (pmKeyType == 1 || pmKeyType == 3)) {
		// Check if the "Keycode" is "white space - / '"
		window.status ="Done";
		window.event.keyCode = vKeyCode; 
	} else if(((vKeyCode == 64) || (vKeyCode == 46) || (vKeyCode == 95)) && (pmKeyType == 4))	{
		// Check if the "KeyCode" is "@._"
		window.status ="Done";
		window.event.keyCode = vKeyCode; 
	} else 	{
		// Check if the "KeyCode" is anyother character, mentioned above.
		window.status = "Invalid Character."
		window.event.keyCode = 0; 
	}
}

//	Trim
function trim(str)	{
	if(typeof(str) != "string" ) return "";
	var	str = str.replace(/^\s\s*/, ''),
	ws = /\s/,
	i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
	
	/* Function will remove the left and right white spaces within the string */
	return pmString.replace( /^ +/, "" ).replace( / +$/, "" );
}

function maxAllowedCharacter(pmObject, pmAllowedLength)	{
	/* Function will check whether the object contains the character within the specified limit. */
	if(!pmObject) return false;
	else if (trim(pmObject.value).length > parseInt(pmAllowedLength,10)) {
		pmObject.value = pmObject.value.substring(0,parseInt(pmAllowedLength,10));
		return false;	
	} 
	else return true;	
} 

function isProperString(pmString, pmDisAllowedChars) {
	/* Function will check whether the string does not contains the disallowed characters. */
   if (!pmString) return false;	   
   var vLength = pmString.length;
   for (var i = 0; i < vLength; i++) {
	  if (pmDisAllowedChars.indexOf(pmString.charAt(i)) != -1)	 return false;
   }
   return true;
}

function isValidEmail(pmEmail)	{
	/* Function will check whether the given email is valid or not. */
	if (!pmEmail) return false;
	pmEmail = trim(pmEmail);
	pmEmail = pmEmail.replace(/\r\n|\r|\n/g, ''); 
	
	if (isRegExpSupported()) {
		var vPattern = "^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9_]+)*)@([A-Za-z0-9]+)(([\\_.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$";
		var vRegExp = new RegExp(vPattern);
		return (vRegExp.test(pmEmail));
	} else	{
		if(pmEmail.indexOf('@') == -1 || pmEmail.indexOf('.') == -1 || pmEmail.indexOf(' ') != -1) return false;
		else {
			var vSplit = pmEmail.split("@");
			if(vSplit.length > 2) return false;
			else 	{
				var vDomain = vSplit[1].split('.');
				var vLength = vDomain.length;
				for(var vLoop = 0; vLoop < vLength; vLoop++)
					if(vDomain[vLoop].length <= 0)	return false;
				return true;
			}
		} 
	}
}

function isValidMultiEmail(pmEmail, pmMultiple, pmCharLimit)	{
	/* Function will check whether the given mails are valid or not. */
	if(!pmCharLimit) pmCharLimit = 100;
	if (!pmEmail) return false;
	var vStatus = true;
	if(pmMultiple)	{
		pmEmail = pmEmail.replace(/;/g, ",");
		var aEmailId = pmEmail.split(",");
		
		for(var vLoopEmail = 0; vLoopEmail < aEmailId.length; vLoopEmail++)	{
			aEmailId[vLoopEmail] = trim(aEmailId[vLoopEmail]);
			aEmailId[vLoopEmail] = aEmailId[vLoopEmail].replace(/\r\n|\r|\n/g, '');
			aEmailId[vLoopEmail] = aEmailId[vLoopEmail].replace(/^"(.*)"/g, ''); 
			aEmailId[vLoopEmail] = aEmailId[vLoopEmail].replace(/\r\n\s|\r|\n|\s/g, ''); 
			aEmailId[vLoopEmail] = aEmailId[vLoopEmail].replace(/^</g, ''); 
			aEmailId[vLoopEmail] = aEmailId[vLoopEmail].replace(/>$/g, ''); 
			if(aEmailId[vLoopEmail] != "")	{
				if(aEmailId[vLoopEmail].length > parseInt(pmCharLimit))	{
					vStatus = false;
					break;
				} else if(!isValidEmail(aEmailId[vLoopEmail]))	{
					vStatus = false;
					break;
				}
			}
		}
	} else 	{
		vStatus = isValidEmail(pmEmail)
	}
	return vStatus;
} 

function isValidUrl(pmUrl) {
	/* Function will check whether the given mails are valid or not. */
	if(!pmUrl) return false;		
	pmUrl = pmUrl.toLowerCase()
	var vStatus    = true;
	var vLength    = pmUrl.length;
	var vValidChar = "1234567890qwertyuiopasdfghjklzxcvbnm_./-:"		
	
	for(var vLoop=0; vLoop <= vLength; vLoop++)	{
		if (vValidChar.indexOf(pmUrl.substr(vLoop,1)) < 0)	{
			vStatus = false;
			return vStatus;				
		}
	}
	return vStatus;
}

function isValidSiteUrl(pmUrl){
	if (pmUrl.indexOf(" ")!=-1) return false;
	urlPat = /^(http:\/\/|https:\/\/|www.){1}([\w]+)(.[\w]+){1,2}[A-Za-z0-9-_%&#!\?\/.=\-\*\$]+$/;
	urlPat1 = /^([\w]+)(.[\w]+){1,2}[A-Za-z0-9-_%&#!\?\/.=\-\*\$]+$/;
	if( pmUrl.match(urlPat) != null ) 
		return true;
	else if( pmUrl.match(urlPat1) != null ) 
		return true
	return false;
}

function isRegExpSupported() {
	/* Function will check whether the regular expression supported by the browser */
	if (window.RegExp)	{
		var vTempStr = "a";
		var vTempReg = new RegExp(vTempStr);
		return (vTempReg.test(vTempStr));
	}
	return false;
}

function isExtendedChars(pmStr){
	if(!pmStr) return false;		
	var vValidChar = "�����������������������������������������������������������������������������������";
	var vLength = pmStr.length;
	var val;
	for(var vLoop = 0; vLoop < vLength; vLoop++) {   
		val = pmStr.charAt(vLoop);
		if(vValidChar.indexOf(val) >= 0  ) return true;
	}
	return false;
}

function isValidPhoneNo(pmPhNo, pmMinLength, pmMaxLength) { 
	/* Function will check whether the given phone number is valid or not */
	if(!(pmPhNo && pmMinLength && pmMaxLength)) return false;		
	var vValidChar = "0123456789()-+,  ext.";
	var vLength = pmPhNo.length;
	var vPhoneNo;
	
	for(var vLoop = 0; vLoop < vLength; vLoop++) {   
		vPhoneNo = pmPhNo.charAt(vLoop);
		if(vPhoneNo == "-") pmMinLength++;
		if(vValidChar.indexOf(vPhoneNo) == -1) return false;
	}
	if(vLength > pmMaxLength || vLength < pmMinLength) return false;
	else return true;
}

function isFloat(pmVal) { 
	/* Function will check whether the given phone number is valid or not */
	if(!pmVal ) return false;		
	var vValidChar = "0123456789.";
	var vLength = pmVal.length;
	var val;
	
	for(var vLoop = 0; vLoop < vLength; vLoop++) {   
		val = pmVal.charAt(vLoop);
//			if(val == ".") pmMinLength++;
		if(vValidChar.indexOf(val) == -1) return false;
	}
	return true;
}

function isValidUSPhone(pmPhNo,pmMultiple){
	/* Function will check whether the given US phone number is valid or not */
	isMultiple = isdefined(pmMultiple) ? pmMultiple : false;
	//var vPattern = '^(\\(?\\d\\d\\d\\)?)?( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$';
	var vPattern = '^[ ]*[0-9]{0,2}[ ]*[0-9]{0,1}[ ]*[-|.]{0,1}[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-|.]{0,1}[ ]*[0-9]{3,3}[ ]*[-|.]{0,1}[ ]*[0-9]{4,4}[ ]*$';
	var vRegExp = new RegExp(vPattern);
	var vStatus = true;
	if ( isMultiple ){
		pmPhNo	 	 = pmPhNo.replace(/;/g, ",");
		var aPhoneNo = pmPhNo.split(",");
		for(var vLoop = 0; vLoop < aPhoneNo.length; vLoop++){
			aPhoneNo[vLoop] = trim(aPhoneNo[vLoop]);
			if ( aPhoneNo[vLoop] != '' ){
				if ( !( vRegExp.test(aPhoneNo[vLoop]) ) ){
					vStatus = false;
					break;
				}
			}
		}
	}else{			
		vStatus = vRegExp.test(pmPhNo);
	}
	return vStatus;
}

function isZipcode(pmZipCode) {
	reZip = new RegExp(/(^\d{5}$)|(^\d{6}$)/);
	if (!reZip.test(pmZipCode))  return false;
	return true;
}

function validateMultiZipCode( zipcodes ){
	/*zipcodes is comma seperated value*/
	if ( trim(zipcodes) == '' ) return false;
	var aZip = zipcodes.split(',');
	var loop,flag = 0;
	for ( loop=0; loop < aZip.length; loop++ ){
		var zip = trim(aZip[loop])
		if (  zip != '' && !isZipcode( zip ) ){
			flag = 1;
			break;
		}
	}
	if ( flag == 1 ) return false;
	else return true;
}

function isPersonName(pmString)	{
	/* Function will check whether the person name is valid or not */
	if(!trim(pmString)) return false;
	if(isRegExpSupported())	{
		var vPattern = "(^([a-zA-Z0-9 ''-]+)?)$";	
		var vRegExp = new RegExp(vPattern);
		return (vRegExp.test(pmString));
	} else {
		var vPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '";
		var vLength  = pmString.length;
		for (var vLoop = 0; vLoop < vLength; vLoop++) 
			if (vPattern.indexOf(pmString.charAt(vLoop)) == -1) return false;
		return true;
	}
}

function isUserName(pmString){
	/* Function will check whether the user name is valid or not */
	if(!trim(pmString)) return false;
	if(isRegExpSupported())	{
		var vPattern = "(^([a-zA-Z0-9_]+)?)$";	
		var vRegExp = new RegExp(vPattern);
		return (vRegExp.test(pmString));
	} else {
		var vPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
		var vLength  = pmString.length;
		for (var vLoop = 0; vLoop < vLength; vLoop++) 
			if (vPattern.indexOf(pmString.charAt(vLoop)) == -1) return false;
		return true;
	}
}

function showHint( obj, text, classn ) {
	if( !obj ) return;
	if( obj.value == '' ) obj.value = text;
	obj.className = classn;
}

function removeHint( obj, text, classn ) {
	if( !obj ) return;
	if( obj.value == text ) obj.value = '';
	obj.className = classn;
}

function stopBubbling( e ){
	if (!e) var e = window.event;
	if ( e == null ) return false;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

/* Common Function for Checking for Given File is Valid */
function ffCheckFileExtension( pmArrayFileExtension, pmFile ){
	//if (pmFile.indexOf(" ") !=-1 ) return false;
	var vPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-. ";
	var aSplitFile = (pmFile.indexOf('\\') != -1) ? pmFile.split("\\") : pmFile.split("/");
	var vExt = aSplitFile[aSplitFile.length - 1];
	var vLength  = vExt.length;
	for (var vLoop = 0; vLoop < vLength; vLoop++) {
		if (vPattern.indexOf(vExt.charAt(vLoop)) == -1) return false;
	}
	
	if(pmFile.indexOf('.') != -1){
		var vFileExt = getFileExtension(pmFile);
		vFileExt = vFileExt.toLowerCase();
		//# - check the fileextension in array
		if(!in_array( vFileExt, pmArrayFileExtension))
			return false;	
	}
	else{
		if ( pmFile == '' )	return true;
		else return false;	
	}
}

function getFileExtension(vFile){
	var aSplitFile = vFile.split("/");
	var vExt = aSplitFile[aSplitFile.length - 1];
	if(vExt.indexOf(".") != -1){
		aSplitExt = vExt.split(".");
		vSplitExt =aSplitExt[aSplitExt.length - 1]
		return vSplitExt;
	}
	else return 0;
}

function in_array( needle, haystack){
	if( !haystack) return false;
	var count = haystack.length;		
	for( var i = 0; i < count; i++){
		if( haystack[i] == needle){				
			return true;
			break;
		}
	}		
	return false;
}	

function CheckSpecialChars( string ) {
	flag = 1;
   for (var i = 0; i < string.length; i++){
	   pNumKeyCode = string.charCodeAt(i);
	   if(!(pNumKeyCode > 64 && pNumKeyCode < 91) && !(pNumKeyCode > 96 && pNumKeyCode < 123) && !(pNumKeyCode == 32) && !(pNumKeyCode > 47 && pNumKeyCode < 58)){
			flag = 0;
			break;
	   }
   }
   if(flag)	
		return true;
   else	
		return false;
}

//	To seralize like php serialization
function getObjectClass(obj)	{
	if (obj && obj.constructor && obj.constructor.toString())		{
		var arr = obj.constructor.toString().match(/function\s*(\w*)/);
		if (arr && arr.length == 2)		{
			return arr[1];
		}
	}	
	return undefined;
}

function serialize( mixed_value ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Arpad Ray (mailto:arpad@php.net)
	// +   improved by: Dino
	// +   bugfixed by: Andrej Pavlovic
	// %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
	// %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
	// *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
	// *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
	// *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
	// *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
	var _getType = function( inp ) {
		var type = typeof inp, match;
		var key;
		if (type == 'object' && !inp) {
			return 'null';
		}
		if (type == "object") {
			if (!inp.constructor) {
				return 'object';
			}
			var cons = inp.constructor.toString();
			if (match = cons.match(/(\w+)\(/)) {
				cons = match[1].toLowerCase();
			}
			var types = ["boolean", "number", "string", "array"];
			for (key in types) {
				if (cons == types[key]) {
					type = types[key];
					break;
				}
			}
		}
		return type;
	};
	var type = _getType(mixed_value);
	var val, ktype = '';
	
	switch (type) {
		case "function": 
			val = ""; 
			break;
		case "undefined":
			val = "N";
			break;
		case "boolean":
			val = "b:" + (mixed_value ? "1" : "0");
			break;
		case "number":
			val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
			break;
		case "string":
			val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
			break;
		case "array":
		case "object":
			val = "a";
			/*
			if (type == "object") {
				var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
				if (objname == undefined) {
					return;
				}
				objname[1] = serialize(objname[1]);
				val = "O" + objname[1].substring(1, objname[1].length - 1);
			}
			*/
			var count = 0;
			var vals = "";
			var okey;
			var key;
			for (key in mixed_value) {
				ktype = _getType(mixed_value[key]);
				if (ktype == "function" && ktype == "object") { 
					continue; 
				}
				
				okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
				vals += serialize(okey) +
						serialize(mixed_value[key]);
				count++;
			}
			val += ":" + count + ":{" + vals + "}";
			break;
	}
	if (type != "object" && type != "array") val += ";";
	return val;
}	

function phpSerialize(val) {
	switch (typeof(val)) {
	case "number":
		if (val == NaN || val == Infinity)
			return false;
		return (Math.floor(val) == val ? "i" : "d") + ":" +
		val + ";";
	case "string":
		return "s:" + val.length + ":\"" + val + "\";";
	case "boolean":
		return "b:" + (val ? "1" : "0") + ";";
	case "object":
		if (val == null)	return "N;";
		else if (val instanceof Array)	{
			var idxobj = { idx: -1 };
			vSerializeStr = "a:" + val.length + ":{";
			for(index =0; index < val.length; index++){
				ser = phpSerialize(val[index]);
				vSerializeStr += ser ? phpSerialize(index) + ser : ''; 
			}
			vSerializeStr += "}";
			return vSerializeStr;			
		}	else	{
			var class_name = getObjectClass(val);
			if (class_name == undefined)
				return false;
			var props = new Array();
			for (var prop in val)	{
				var ser = phpSerialize(val[prop]);	
				if (ser)
					props.push(phpSerialize(prop) + ser);
			}
			return "O:" + class_name.length + ":\"" +
				class_name + "\":" + props.length + ":{" +
				props.join("") + "}";
		}
	case "undefined":
		return "N;";
	}
	return false;
}

//	End seralize like php serialization
//	Date function
String.prototype.string = function(l) { var s = '', i = 0; while (i++ < l) { s += this; } return s; }	
Number.prototype.zf = function(l) { return this.toString().zf(l); }
String.prototype.zf = function(l) { return '0'.string(l - this.length) + this; }
var gsMonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var gsDayNames = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
Date.prototype.format = function(f)	{
	if (!this.valueOf())
		return ' ';	
	var d = this;	
	return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
		function($1) {
			switch ($1.toLowerCase())	{
			case 'yyyy': return d.getFullYear();
			case 'mmmm': return gsMonthNames[d.getMonth()];
			case 'mmm':  return gsMonthNames[d.getMonth()].substr(0, 3);
			case 'mm':   return (d.getMonth() + 1).zf(2);
			case 'dddd': return gsDayNames[d.getDay()];
			case 'ddd':  return gsDayNames[d.getDay()].substr(0, 3);
			case 'dd':   return d.getDate().zf(2);
			case 'hh':   return ((h = d.getHours() % 12) ? h : 12);
			case 'nn':   return d.getMinutes().zf(2);
			case 'ss':   return d.getSeconds().zf(2);
			case 'a/p':  return d.getHours() < 12 ? 'AM' : 'PM';
			}
		}
	);
}

//	Cookie Related Functions
function setCookie(cookieName, cookieValue,id)	{
	//var g_cookie_prefix = 'ww';
	
	delCookie(cookieName); 
	var cookieid=g_cookie_prefix+"cookieid";
	delCookie(cookieid); 
	nDays=100;

	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	if(trim(cookieValue) != ''){		
		document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString()+";path=/;";
	}
}

function delCookie (name) 	{
	var expireNow = new Date();
	document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
}

function getCookie (name) 	{
	var dcookie = document.cookie; 
	var cname = name + "=";
	var clen = dcookie.length;
	var cbegin = 0;
			while (cbegin < clen) 	{
				var vbegin = cbegin + cname.length;
				if (dcookie.substring(cbegin, vbegin) == cname) { 
					var vend = dcookie.indexOf (";", vbegin);
					if (vend == -1) vend = clen;
					return unescape(dcookie.substring(vbegin, vend));
				}
				cbegin = dcookie.indexOf(" ", cbegin) + 1;
				if (cbegin == 0) break;
			}
	return '';

}
	
//	End	Cookie Related Functions
//Compare the end date is greater than start date
function CompDate( pmStartDate, pmEndDate ){
	/* format of input date is, MM-DD-YYYY */
	aStartDate = pmStartDate.split("-");
	aEndDate   = pmEndDate.split("-");
	var refStart = new Date(aStartDate[2],aStartDate[0],aStartDate[1]);
	var refEnd   = new Date(aEndDate[2],aEndDate[0],aEndDate[1]);
	if ( Date.parse(refEnd) < Date.parse(refStart) ) return 0;
	return 1;
}	

function traceKey( code, callback ) {            
	if( code == 13 ){
		if (isdefined(callback)) eval(callback);			
	}
}	

function striptags(a){
	return a.replace(/<\/?[^>]+>/gi,"")
}

function urldecode( str ) {
	var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
	var ret = str.toString();
	
	// The histogram is identical to the one in urlencode.
	histogram['!']   = '%21';
	histogram['%20'] = '+';
 
	for (replaces in histogram) {
		searches = histogram[replaces]; // Switch order when decoding
		tmp_arr = ret.split(searches); // Custom replace
		ret = tmp_arr.join(replaces);   
	}
	// End with decodeURIComponent, which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);
 
	return ret;
}

function validateExtendedChars(pmStr, pmDiv, pmErrDiv){
	if(isExtendedChars(pmStr)){
		ge(pmErrDiv).innerHTML = 'Extended characters are not allowed.';
		ge(pmDiv).focus();
		return 0;
	}
	return 1;
}

/*equvialent to php htmlspecialchars*/
function htmlspecialchars(string, quote_style) {
	string = string.toString();		
	// Always encode
	string = string.replace(/&/g, '&amp;');
	string = string.replace(/</g, '&lt;');
	string = string.replace(/>/g, '&gt;');		
	// Encode depending on quote_style
	if (quote_style == 'ENT_QUOTES') {
		string = string.replace(/"/g, '&quot;');
		string = string.replace(/'/g, '&#039;');
	} else if (quote_style != 'ENT_NOQUOTES') {
		// All other cases (ENT_COMPAT, default, but not ENT_NOQUOTES)
		string = string.replace(/"/g, '&quot;');
	}		
	return string;
}

/*equvialent to php array_flip*/
function array_flip( trans ) {
	var key, tmp_ar = {};
 
	for( key in trans ) {
		tmp_ar[trans[key]] = key;
	}
 
	return tmp_ar;
}

function phpInArray(needle, haystack, strict) {
	var found = false, key, strict = !!strict;	 
	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}	 
	return found;
}

/*Character limit validation for textarea*/	
function checkMaxCharacters(id, maxChars, isTiny, noalert ){
	var maxLimit;
	var isNoAlert = !isdefined(noalert) ? 0 : noalert;
	if ( isdefined(isTiny) && isTiny ){			
		//inputcontent = tinyMCE.getInstanceById(id).getWin().document.body.innerHTML;			
		inputcontent = tinyMCE.getContent();
		nonhtml 	 = striptags(inputcontent);
		taLength 	 = nonhtml.length; // look at current length
		maxLimit	 = maxChars+(inputcontent.length-nonhtml.length);
		//alert(inputcontent.length+" "+nonhtml.length)
	}else{
		inputcontent = ge(id).value;		
		taLength 	 = inputcontent.length; // look at current length
		maxLimit	 = maxChars;
	}
	
	if ( isNoAlert ){
		var diff = parseInt(maxChars-taLength) <=0 ? 0 : parseInt(maxChars-taLength);
		if ( parseInt(taLength) == 0 ) 
			$('#count-alert').html(""+maxChars);
		else
			$('#count-alert').html(""+diff);
	}
	
	if ( taLength > maxChars ){ // clip characters			
		actual = inputcontent.substring(0, maxLimit);
		if( striptags(actual).length > maxChars ){
			var diff = striptags(actual).length - maxChars;				
			actual   = actual.substring(0, maxChars+diff);
			//alert(striptags(actual).length)
		}
		if ( isdefined(isTiny) && isTiny ){
			//inputcontent = tinyMCE.getInstanceById(id).getWin().document.body.innerHTML;
			//actual = inputcontent.substring(0, maxChars);				
			tinyMCE.setContent( actual );
		}else{				
			ge(id).value = actual;
		}
		if ( isNoAlert )
			return false;
		else
			alert('Sorry Text cannot exceed more than '+maxChars+' characters');
	}
}
/*end*/

function phpArrayUnique( array ) {
	var p, i, j, tmp_arr = array, matches = [];
	for(i = tmp_arr.length; i;){
		for(p = --i; p > 0;){
			if(tmp_arr[i] === tmp_arr[--p]){					
				matches.push(p);
				for(j = p; --p && tmp_arr[i] === tmp_arr[p];);
				i -= tmp_arr.splice(p + 1, j - p).length;					
			}
		}
	}		
	return [tmp_arr,matches];
}

function ConvertBR(pmString)	{
	/* Function will Remove control characters from a string */
	if (!pmString) return false;
	pmString = trim(pmString);		 
	
	if (isRegExpSupported()) { 
		//return s.replace(/[\n\r\t]/g, ' '); 
		return pmString.replace(/[\n\r\t]/g, ' ');
	} else	{
		var r = "";
		for (i=0; i < pmString.length; i++) {
			if (s.charAt(i) != '\n' && s.charAt(i) != '\r' && s.charAt(i) != '\t') {
				r += pmString.charAt(i);
			} else{
				r += ' ';
			}
		}
		return r;		
	}
}

function detectKey( event, type ){
	if ( event.keyCode == 13 ){			
		if( type == 1 ){
			login();			
		} else if( type==2 ){
			funCaptchaValues();		
		} else if( type==3 ){
			call_searching();		
		} else if( type==4 ){
			call_networksearching();	
		}
	}
}

function check_all_box(main, name ) {
	$('input[name='+name+']').each( function() {
		$(this).attr('checked', $(main).is(':checked') );
	} ) 
}

function set_opacity( obj ){
	$(obj).css( 'opacity','0.5' );
}

function set_hover_style( ele, clsover ) {
	$(ele).addClass(clsover);
	$(ele).bind('mouseout', function() { $(ele).removeClass(clsover) } )
}	

function go_back() { history.go('-1') }	

function hasValue(val, errdiv, fld, msg, isTiny){
	$('#'+errdiv).html('');
	if ( val == "" ){			
		$('#'+errdiv).html(msg);
		if(isTiny)
			MoveFocusToEditor(fld);				
		else
			if(ge(fld)) ge(fld).focus();
		return 0;
	}
	return 1;
}

function clearAllErrorFields(pmArray){
	for(vIndex = 0; vIndex < pmArray.length; vIndex++)
		if(ge(pmArray[vIndex]))	ge(pmArray[vIndex]).innerHTML = '';
}

function disableWidget() {
	var param = 'rand='+Math.random();
	var url = g_site_path + 'ajax/disable-widget';
	
	$.ajax({
		type: "POST",
		url: url,
		dataType: "html",
		data:param,
		success: function(html) {
			//window.location.href = g_site_path;                    
		}
	});
}

function stickyCancel(){
	$("#dialog-modal" ).dialog("destroy");
}

function checkDomain() {
	var param = 'rand='+Math.random();
	var url = g_site_path + 'ajax/check-domain';
	$('#check-domain').removeAttr('onclick');
	$.ajax({
		type: "POST",
		url: url,
		dataType: "json",
		data:param,
		success: function(json) {
			if(json.success == 1) {
				window.location = json.url+'/fans';
				return false;
			} else if(json.success == 0) {
				return false;
			}	                    
		}
	});
}

function enablewidget(htm){ 
	
	$( "#dialog-modal" ).dialog( "destroy" );
	var html	= htm;
	$( "#dialog-modal" ).html(html);
	$( "#dialog-modal" ).dialog({ 							
		width:800,
		modal: true,
		draggable:false,
		resizable:false
	});
	$(".ui-dialog-titlebar").remove();
	$(".ui-widget-overlay").css( 'height', '1390px' ) ;
}

function enablefanwidget(htm){ 	
	$( "#dialogfan-modal" ).dialog( "destroy" );
	var html	= htm;
	$( "#dialogfan-modal" ).html(html);
	$( "#dialogfan-modal" ).dialog({ 							
		width:1100,
		modal: true,
		draggable:false,
		resizable:false
	});
	$(".ui-dialog-titlebar").remove();
	$(".ui-widget-overlay").css( 'height', '1390px' ) ;
}

function referralPopup( ) {
	
	$('#dialog-modal').load(g_site_path+'ajax/referral-popup', '', function() {
	   $("#dialog-modal").dialog({                        
				width:680,
				modal: true,
				draggable:false,
				resizable:false,
				closeOnEscape: false
		});
		$(".ui-dialog-titlebar").remove();
	});
}

function checkReferral() {
	var url	= $('#youtubeurl').val();
	
	var matches = url.match("youtube.com");
	if( url == "Please enter your Youtube URL here"){
			$('#refererrmsg').html('<p style="color:red; margin:0; clear:both;">Please enter the Youtube url</p>');
			$('#youtubeurl').focus();
			return false;
	}
	if (matches != "youtube.com" )	 {
	  	$('#refererrmsg').html('<p style="color:red; margin:0; clear:both;">Please enter valid Youtube URL</p>');
		$('#youtubeurl').focus();
		return false;
	 }
	if(isValidSiteUrl(url)==false){
			 $('#refererrmsg').html('<p style="color:red;margin:0; clear:both;">Please enter valid Youtube URL <span style="color:green">eg. "http://www.youtube.com/user/example"</span></p>');
			$('#youtubeurl').focus();
			return false;
	}
	urlPat = /^(http:\/\/|https:\/\/){1}$/;
	if( url.match(urlPat) == null ) {
		$('#youtubeurl').val(url);
	}
	$('#refer').hide('slow');
	$('#refererrmsg').html('<p style="color:red;clear:both;">Please Wait...</p>');
	var param = 'pageurl='+escape(url)+'&rand='+Math.random();
	var url1 = g_site_path + 'ajax/check-vaild-yturl';
	
	$.ajax({
		type: "POST",
		url: url1,
		dataType: "json",
		data:param,
		success: function(json) {
			if(json.status == 1) { 
				referURL();
				$('#refererrmsg').html('');
			} else {
				$('#refererrmsg').html('<p style="color:red;clear:both;">'+json.message+'</p>');
				$('#youtubeurl').focus();
				return false;
			}				
		}
	});
	
}

function referURL() {	
	var pageurl	= $('#youtubeurl').val();
	
	var param = 'pageurl='+escape(pageurl)+'&rand='+Math.random();
	var url1 = g_site_path + 'ajax/refer-friend';
	
	$.ajax({
		type: "POST",
		url: url1,
		dataType: "json",
		data:param,
		success: function(json) {
			if(json.success == 1) { 
				$('#refer_Url').html(json.hash);
				$('#referCount').html('(Referred: '+json.count+')');
				$('#refer').show('slow');				
			} 			
		}
	});	
}

function earnSubscribePopup( ) {
	
	$('#dialog-modal').load(g_site_path+'ajax/subscribe-popup', '', function() {
	   $("#dialog-modal").dialog({                        
				width:680,
				modal: true,
				draggable:false,
				resizable:false,
				closeOnEscape: false
		});
		$(".ui-dialog-titlebar").remove();
	});
}

function earnSubscribers() {
	var url	= $('#youtubeurl').val();
	
	var matches = url.match("youtube.com");
	if( url == "Please enter your Youtube URL here"){
			$('#refererrmsg').html('<p style="color:red; margin:0; clear:both;">Please enter the Youtube url</p>');
			$('#youtubeurl').focus();
			return false;
	}
	if (matches != "youtube.com" )	 {
	  	$('#refererrmsg').html('<p style="color:red; margin:0; clear:both;">Please enter valid Youtube URL</p>');
		$('#youtubeurl').focus();
		return false;
	 }
	if(isValidSiteUrl(url)==false){
			 $('#refererrmsg').html('<p style="color:red;margin:0; clear:both;">Please enter valid Youtube URL <span style="color:green">eg. "http://www.youtube.com/user/example"</span></p>');
			$('#youtubeurl').focus();
			return false;
	}
	urlPat = /^(http:\/\/|https:\/\/){1}$/;
	if( url.match(urlPat) == null ) {
		$('#youtubeurl').val(url);
	}
	$('#refer').hide('slow');
	$('#refererrmsg').html('<p style="color:red;clear:both;">Please Wait...</p>');
	var param = 'pageurl='+escape(url)+'&rand='+Math.random();
	var url1 = g_site_path + 'ajax/check-vaild-yturl';
	
	$.ajax({
		type: "POST",
		url: url1,
		dataType: "json",
		data:param,
		success: function(json) {
			if(json.status == 1) { 
				earnSubescribeWidget();
				$('#refererrmsg').html('');
			} else {
				earnSubescribeWidget();
				$('#refererrmsg').html('');
				/*$('#refererrmsg').html('<p style="color:red;clear:both;">'+json.message+'</p>');
				$('#youtubeurl').focus();*/
				return false;
			}				
		}
	});
	
}

function earnSubescribeWidget() {	
	var pageurl	= $('#youtubeurl').val();
	
	var param = 'pageurl='+escape(pageurl)+'&rand='+Math.random();
	var url1 = g_site_path + 'ajax/earn-subscribers';
	
	$.ajax({
		type: "POST",
		url: url1,
		dataType: "json",
		data:param,
		success: function(json) {
			if(json.success == 1) { 
				
				if( json.pageId == 0 ) {
					$('#refererrmsg').html('<p style="color:red;clear:both;">Your youtube channel is not available in our system, please subscribe your channel first ! </p>');
				} else {
					window.location.reload();
				} 
			} else if( json.success == 0 ) { 
				$('#refererrmsg').html('<p style="color:red;clear:both;">Your youtube channel is not available in our system, please subscribe your channel first ! </p>');
			} 			
		}
	});	
			
	/*$('#dialog-modal').load(g_site_path+'ajax/refer-friend?pageurl='+escape(pageurl)+'&rand='+Math.random(), '', function() {
	   $("#dialog-modal").dialog({                        
				width:720,
				modal: true,
				draggable:false,
				resizable:false,
				closeOnEscape: false
		});
		$(".ui-dialog-titlebar").remove();
	});	*/
}
