/**
	  *		Created for: File to hold some of predefined objects & commnly used functions.
	  *		Created by : Kathirvel.P
	  *		Objects :
	  *			browser : To get browser details(vesrion, co-ordinates, element size)
	  *			dialog  : To create a model / modeless popup layers.
	  *			drag    : To make a element draggable.
	  */
   
	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;
	}
	function detect() {
		var agent 	= navigator.userAgent.toLowerCase();
		// detect platform
		this.isMac		= (agent.indexOf('mac') != -1);
		this.isWin		= (agent.indexOf('win') != -1);
		this.isWin2k	= (this.isWin && (
				agent.indexOf('nt 5') != -1));
		this.isWinSP2	= (this.isWin && (
				agent.indexOf('xp') != -1 || 
				agent.indexOf('sv1') != -1));
		this.isOther	= (
				agent.indexOf('unix') != -1 || 
				agent.indexOf('sunos') != -1 || 
				agent.indexOf('bsd') != -1 ||
				agent.indexOf('x11') != -1 || 
				agent.indexOf('linux') != -1);
		
		// detect browser
		this.isSafari	= (agent.indexOf('safari') != -1);
		this.isSafari2 = (this.isSafari && (parseFloat(agent.substring(agent.indexOf("applewebkit/")+"applewebkit/".length,agent.length).substring(0,agent.substring(agent.indexOf("applewebkit/")+"applewebkit/".length,agent.length).indexOf(' '))) >=  300));
		this.isOpera	= (agent.indexOf('opera') != -1);
		this.isNN		= (agent.indexOf('netscape') != -1);
		this.isIE		= (agent.indexOf('msie') != -1);
		this.isFirefox	= (agent.indexOf('firefox') != -1);
		
		// itunes compabibility
		this.isiTunesOK	= this.isMac || this.isWin2k;
		
		this.getClientWidth = function() {
			return(window.innerWidth||
				  (document.documentElement && document.documentElement.clientWidth)||
				  (document.body && document.body.clientWidth)||
				  0);
		}
	}
	browser = new detect();	
	browser.getClientHeight = function() {
		return(window.innerHeight||
			  (document.documentElement && document.documentElement.clientHeight)||
			  (document.body && document.body.clientHeight)||
			  0);
	}
	browser.getPageScrollTop = function() {
		return(document.documentElement && document.documentElement.scrollTop)||
			  (document.body && document.body.scrollTop)||
			  0;
	}
	browser.getPageScrollLeft = function() {
		return(document.documentElement && document.documentElement.scrollLeft)||
			  (document.body && document.body.scrollLeft)||
			  0;
	}
	browser.getPageSize = function() {
		var xScroll,yScroll;
		if(window.innerHeight&&window.scrollMaxY){
			xScroll=window.innerWidth+window.scrollMaxX;
			yScroll=window.innerHeight+window.scrollMaxY;
		}else if(document.body.scrollHeight>document.body.offsetHeight){
			xScroll=document.body.scrollWidth;
			yScroll=document.body.scrollHeight;
		}else{
			xScroll=document.body.offsetWidth;
			yScroll=document.body.offsetHeight;
		}
		var windowWidth,windowHeight;
		if(self.innerHeight){
			if(document.documentElement.clientWidth){
				windowWidth=document.documentElement.clientWidth;
			}else{
				windowWidth=self.innerWidth;
			}
			windowHeight=self.innerHeight;
		}else if(document.documentElement&&document.documentElement.clientHeight){
			windowWidth=document.documentElement.clientWidth;
			windowHeight=document.documentElement.clientHeight;
		}else if(document.body){
			windowWidth=document.body.clientWidth;
			windowHeight=document.body.clientHeight;
		}
		if(yScroll<windowHeight){
			pageHeight=windowHeight;
		}else{
			pageHeight=yScroll;
		}
		if(xScroll<windowWidth){
			pageWidth=xScroll;
		}else{
			pageWidth=windowWidth;
		}

		scrollleft = browser.getPageScrollLeft();
		scrolltop = browser.getPageScrollTop();
		return { pageWidth:pageWidth, pageHeight:pageHeight, 
				 windowWidth:windowWidth, windowHeight:windowHeight, 
				 scrollLeft:scrollleft, scrollTop:scrolltop};
	}
	
	browser.getPosition = function( element ) 	{
		var l = t = 0;
		while( element != null ) {
			l += element.offsetLeft;
			t += element.offsetTop;
			element = element.offsetParent
		}
		return {left:l, top:t};
	};
	
	function ratestar(cid, type, callback, e, maxstar) {
		
		
		/*if( !eval(g_lin) ) { 
			//alert("sdfs")
			showLoginWarnning(e);
			return;
		}*/
		//alert(cid+'=='+type)
		if (e == null)  e = window.event;
		var target = e.target != null ? e.target : e.srcElement;		
		maxstar = (isdefined( maxstar )) ? maxstar : 10;
		ratebar = 'rate_star_bar';
		rateunselect = 'rate_star';
		rateselect = 'rate_star_select';
		barid = 'ratestar';
		
		if( ge(barid) != null ) document.body.removeChild( ge(barid) );
		
		pos = browser.getPosition(target);
		bar = ce('DIV');
		bar.id = barid;
		bar.className = ratebar;
		
		bar.style.top = pos.top - (browser.isIE ? 28 : 40) + 'px';
		bar.style.left = pos.left + 0 + 'px';
		
	/*	float = 'ratefloat';
		fl = ce('DIV');
		fl.className = 'rate_star_bar_float';
		fl.style.top = bar.style.top;
		fl.style.left = bar.style.left
		document.body.appendChild( fl );*/
		bar.onmouseout = function(e) { //	hide rate bar.
			if (e == null)  e = window.event;
			var t = e.relatedTarget != null ? e.relatedTarget : e.toElement != null ? e.toElement : '';
			for(var i = 0; i < 4; i++ ) {
				if( t != null && t.id && t.id == barid ) return;
				t = t.offsetParent != null ? t.offsetParent : '';
			}
			bar.parentNode.removeChild( bar );
		}
		document.body.appendChild( bar );
		
		slist = new Array();
		tbl = ce( 'TABLE' );
		bar.appendChild( tbl );
		tbdy = tbl.appendChild( ce( 'TBODY' ) );
		tr = ce( 'TR' );
		tbdy.appendChild( tr );
		
		txt = ce( 'TD' );
		txt.className = 'rate_text';
		txt.rowSpan = '2';
		txt.innerHTML = 'Rate';		
		tr.appendChild( txt );		
		for(tmp = 1; tmp <= maxstar; tmp++) {
			td = ce( 'TD' );
			star = ce('DIV');
			star.id = tmp;
			star.className = rateunselect;
			slist[tmp] = star;
			star.onmouseover = function() { 
				if( this.className == rateselect ) {
					for(ds = maxstar; ds >= this.id ; ds--) 
						slist[ds].className = rateunselect;		
				} else {
					for(s = 1; s <= this.id; s++) 
						slist[s].className = rateselect;
				}
			}
			star.onclick = function() { 
				bar.parentNode.removeChild( bar );				
				eval(callback+"(cid, type,  this.id)" );
				//RateAnswer(cid, this.id);
			}
			tr.appendChild( td );
			td.appendChild( star );
		}
		tr = ce( 'TR' );
		tbdy.appendChild( tr );
		for(n = 1; n <= maxstar; n++) {
			td = ce( 'TD' );
			td.className = 'rate_number';
			td.align = 'center';
			td.innerHTML = n;
			tr.appendChild( td );
		}
	}
	
	//	Drag
	function drag(o)	{		
		var src = o.src || '';
		var identy = o.identy || '';
		if( !src ) return;
		if( identy == '' ) return;
		var draggable = o.draggable || src;
		
		var draginit = function(e) {
			var htype = '-moz-grabbing';
			if (e == null) { e = window.event; htype = 'move';} 
			var target = e.target != null ? e.target : e.srcElement;
			 target = (target.nodeType == 1 || target.nodeType == 9) ? target : target.parentNode;
			//cursor = target.style.cursor;
			if ( target.className == identy || target.id == identy ) {
				//target.style.cursor = htype;
				target = draggable;
				dragging = true;
				dragXoffset = e.clientX - parseInt(draggable.style.left);
				dragYoffset = e.clientY - parseInt(draggable.style.top);
				src.onmousemove = function(e) {
					if (e == null) { e = window.event } 
					  if (e.button <=1 && dragging ) {
						 draggable.style.left = e.clientX - dragXoffset+'px';
						 draggable.style.top = e.clientY - dragYoffset+'px';
						 return false;
					  }
				}
				src.onmouseup = function() {
					src.onmousemove = null;
					src.onmouseup = null;
					//src.style.cursor = 'move';
					dragging = false;
				}
				return false;
			}
		}
		
		if(browser.isIE) src.attachEvent("onmousedown", draginit);
		else src.addEventListener("mousedown", draginit, false);
	}	
	/*
	 *	Captionier popup
	 */
	
	var popupwin  = null;
	var s = d = t = 0;
	var target,evt_type;
	function popup( o ) {
		o = o || {};	
		if ( o.event == null )  var e = window.event; else var e = o.event;		
		//var target = e.target != null ? e.target : e.srcElement;
		if ( o.sleep != true || !isdefined(o.sleep) ){
			if ( e == null || !isdefined(e) )
				target = o.target;
			else			
				target   = e.target != null ? e.target : e.srcElement;
			evt_type = e.type;
		}
	
		if( evt_type != "click" && (!isdefined( o.shownow ) || o.shownow == false) ) {
			if ( !s )	s = new Date();				
			var n  = new Date();
			d = n.getTime() - s.getTime();			
			if ( d <= 1000 ){				
				if( o.sleep != true || !isdefined(o.sleep) ) $(target).bind('mouseout',function() { if( t ) clearTimeout( t ); s = d = t = 0; } );
				o.sleep = true;
				t = setTimeout( function(){ popup(o) }, 1 );
			}
			else {
				o.shownow = true;
				popup( o );
				s = d = t = 0;
			}				
		}else{		
			var pos = browser.getPosition( target );		
			var left = pos.left;
			var top = pos.top;
			var width = o.width || 400;
			var url = o.url || '';
			var data = o.data || '';
			var onclose = ','+o.onclose || 'void(0)';
			var popupTitle = !isdefined(o.poptitle) ? 'LOGIN' : o.poptitle;
			var content = o.content || '<span class="loading" >Loading...</span>';
			if( target.offsetWidth ) left += Math.floor(target.offsetWidth / 2);
			if( target.offsetHeight ) top += Math.floor(target.offsetHeight / 2);
			if( isdefined( o.offsettop ) != undefined && parseInt( o.offsettop ) > 0 ) top += o.offsettop;
			if( isdefined( o.offsetleft ) != undefined && parseInt( o.offsetleft ) > 0 ) left += o.offsetleft;
			if( !isdefined( o.loginwindow ) ) o.loginwindow = false;
			 pop = ce('div');
			pop.forcedisplay = false;
			nopopup();
			//pop.onresize = function() { popupresize() };
			pop.className = 'popup';
			pop.style.width = width+'px';			
			if ( isdefined(o.height) && o.height > 0 ) customstyle = 'style="height:'+o.height+'px"';
			else	customstyle = '';
			//pop.style.left = left;
			//pop.style.top = top;			
			pop.postop = top;
			pop.posofftop = 25;
			pop.posoffleft = 43;
			pop.posleft = left;
			//pop.poshoriz = top - document.body.scrollTop > document.body.scrollTop + document.body.clientHeight - top ? 'd' : 'u';
			pop.poshoriz = top - browser.getPageScrollTop() > browser.getPageScrollTop() + browser.getClientHeight() - top ? 'd' : 'u';
			pop.posvert = left > width+50 ? 'r' : 'l';
			
			if( o.loginwindow ) {
		
				pop.posofftop = 13;
				pop.posoffleft = 44;
				arrow_style = "margin-top:0px";
				if( pop.poshoriz == 'u') arrow_style = "margin-top:0px";
					pop.innerHTML = '<div id="popuparrow" class=arrow >' + png( g_template_img + 'login_c_arrow_' + pop.poshoriz + pop.posvert + '.png', 24, 13, arrow_style )
								  + '</div><div class="back-login" id="popupbackground1" >'
								  +	'<div id="popupPanel">'
								  + '<div id="popup">'											
								  + '<div class="panel_top">'
								  + '<div class="deletebutton-login"><img id="popupclose" src="'+g_template_img+'img_close_popup.gif"  onclick="nopopup()'+ onclose +'" title="click to close" /></div>'
								  + '<div id="panelHeader" class="secondaryColor" >'+popupTitle+'</div>'								
								  + '</div>'
								  + '<div id="popupcanvas" class="panelbot" style="margin:0px"><span class="warning">Loading...</span>'
								 /* + '<div id="divlogin_err" class="warning" style="text-align:center;"></div>'
								  + '<div>'
								  + '<div class="popupHeaderText">User Name  &nbsp;&nbsp;<span class="">'
								  + '<input type="text" name="textfield" id="user_login" name="user_login" onkeydown="detectKey(event,1)" />'
								  + '</span></div>'
								  + '<div class="popupHeaderText">Password  &nbsp;&nbsp;&nbsp;&nbsp;<span class="">'
								  + '<input type="password" name="textfield" id="user_pass" name="user_pass" onkeydown="detectKey(event,1)" />'
								  + '</span></div>'
								  + '<div>'
								  + '<div style="padding-top:5px;"><span style="padding-left:113px; padding-top:10px;"> &nbsp;</span><span>'
								  + '<input type="checkbox" name="checkbox" value="checkbox" />'
								  + '</span><span class="popupcontent">Remember Me</span><span>'
								  +	'<input type="button" name="Submit" value="LOGIN" class="Button" onclick="login()" />'
								  + '</span></div>'
								  + '</div>'
								  + '<div>'
								  + '<div style="padding-top:5px;"><span style="padding-left:117px; padding-top:10px;"> &nbsp;</span><span class="lastPW"><a href="Javascript:void(0);" class="lastPW" onclick="getLostPasswordForm();">Lost your password?</a></span></div>'
								  + '</div>'*/												
								  + '</div>'									
								  + '</div>'
								  + '</div></div>';				
					
			} else { 
				arrow_style = "margin-top:-4px";
				if( pop.poshoriz == 'u') arrow_style = "margin-top:7px";
				pop.innerHTML = '<div id="popuparrow" class=arrow >' + png( g_template_img + 'c_arrow_' + pop.poshoriz + pop.posvert + '.png', 43, 25, arrow_style ) 
							  + '</div><div class="back" id="popupbackground" '+customstyle+'>'
							  + '<div id="popupclose" class="deletebutton" onclick="nopopup()'+ onclose +'" title="click to close">X</div>'
							  + '<div id=popupcanvas class="popupcanvas-login" >'+content+'</div></div>';
			}
			//alert(pop.innerHTML);
			popupwin = pop;			
			document.body.appendChild( pop );
			if ( document.all ){
				setTimeout(function(){									
										if ( $('#popupclose') ) $('#popupclose').attr('src',g_template_img+'img_close_popup.gif');										
										pngfix();
									},100);
			}
			//ge('popupcanvas').onchange = function() { popupresize(); }			
			if( url ) {
				$.ajax( {type : "POST",url : url, data : data, success: function( html ){
								$('#popupcanvas').html( html ); popupresize();
								if( isdefined( o.callback ) ) eval( o.callback );
								if( isdefined( o.autoclose ) && o.autoclose == true ) {
									var dely = ( isdefined( o.closedelay ) ) ? o.closedelay : 2000;
									setTimeout('nopopup()', dely);									
								}
							}
						});			
			}
			popupresize();
			return pop;
		}
	}
	function popupresize() {
		var pop = popupwin;
		var vtop;
		if( pop == null ) return;
		
		ge('popupbackground').style.height = pop.clientHeight + 'px'; 
		ge('popupbackground').style.width = pop.clientWidth + 'px';

		if( pop.poshoriz == 'd' )	{
			pop.style.top = vtop = pop.postop - (pop.clientHeight + pop.posofftop) + 'px';
			ge('popuparrow').style.top = browser.isIE ? pop.clientHeight -1 + 'px': pop.clientHeight + 1 + 'px';
		}
		else if( pop.poshoriz == 'u' ) {
			pop.style.top = vtop = pop.postop + (pop.posofftop) + 'px';
			ge('popuparrow').style.top = browser.isIE ? -pop.posofftop + 1 + 'px' : -pop.posofftop + 1 + 'px';
		}
		if( vtop < 0 && !pop.forcedisplay )	{
			pop.forcedisplay = true;
			pop.poshoriz = 'u';
			popupresize();
			ge('popuparrow').innerHTML = png( g_template_img + 'c_arrow_' + pop.poshoriz + pop.posvert + '.png', 43, 25 );
			return;
		}
		pop.style.left = pop.posvert == 'l' ? pop.posleft + 'px' : pop.posleft - pop.clientWidth + 'px';
		//alert(pop.style.left)
		ge('popuparrow').style.left = pop.posvert == 'l' ? 0 + 'px' : pop.clientWidth - pop.posoffleft + 'px';
		//ge('popupclose').style.left = pop.clientWidth - 28 + 'px';
	
		// scroll window to fit popup
		if( vtop < document.body.scrollTop )	{
			window.scrollBy( 0, vtop-(document.body.scrollTop+4) );
		}
		if( (vtop + pop.clientHeight) > (document.body.scrollTop + document.body.clientHeight) )	{
			window.scrollBy( 0, (vtop + pop.clientHeight)-(document.body.scrollTop + document.body.clientHeight - 4) );
		}
	}
	function reloadpopup(o){
		var url = o.url || '';
		var data = o.data || '';		
		var popupTitle = !isdefined(o.poptitle) ? 'LOGIN' : o.poptitle;
		var content = o.content || '<span class="loading" >Loading...</span>';
//		alert(o.height);
		$(popupwin).css('width',o.width);	
		if(o.height)	ge('popupbackground').style.height = o.height
	//	$('#$popupbackground').css('height',o.height);
		$('#panelHeader').html( popupTitle );
		$('#popupcanvas').html( content );popupresize();
		if( url ) {			
			$.ajax( {type : "POST",url : url, data : data, success: function( html ){
							$('#popupcanvas').html( html ); popupresize();
							if( isdefined( o.callback ) ) eval( o.callback );
							if( isdefined( o.autoclose ) && o.autoclose == true ) {
								var dely = ( isdefined( o.closedelay ) ) ? o.closedelay : 2000;
								setTimeout('nopopup()', dely);
								popupresize();
							}
						}
					});	
			popupresize();
		}
	}
	function nopopup() {
		if( popupwin != null ){ 
			document.body.removeChild( popupwin );
			if ( location.href.toString().match(/personalize-your-party/gi) != null ){			
				$('#uploadphoto').html(g_upload_photo_html);
				g_upload_photo_html = '';
			}
		}
		popupwin = null;
	}
	function png( src, w, h, s ) {
		//if( browser.isNN )
			return '<img src="' + src + '"  border=0 alt="" style="' + s + '">';
		//else
			return '<div style="' + s + ';width:' + w + ';height:' + h + ";filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')" + '"></div>';
	}
	//	Popup creater.
	function dialog(o) {
			
			o = o || {};
			var page = browser.getPageSize();
			var title = o.title || ''; 
			var width = o.width || 400;
			var height = o.height || 300;
			var ismodel = o.ismodel || false;
			var isdrag = o.isdrag || false;
			var isclose = o.isclose;
			var onclose = o.onclose || 'dialog.close()';
			var content = o.content || '<span class="warnning" >Loading...</span>';
			var left = o.left || ((page.windowWidth/2) - (width/2));
			var top = o.top || ((page.windowHeight/2) - (height/2));
			var popupBgClass = !isdefined( o.bgclass ) ? 'content-area' : o.bgclass;
			this.loaded = false;
			
			left = left + page.scrollLeft;
			top  = top + page.scrollTop;
			
			bgid = 'dialog_bg_'+Math.random();
			pop  = 'dialog_pop_'+Math.random();
			popcontainer  = 'dialog_container_'+Math.random();	
			
			if( ismodel == true ) {	//	Gray background
				this.bg = ce('div');		
				this.bg.id = bgid;					
				//alert(page.pageWidth+" "+page.pageHeight)
				this.bg.style.width = page.pageWidth+'px'; 
				this.bg.style.height = page.pageHeight+'px'; 
				this.bg.className = (browser.IsSafari) ? "popupBackgroundSafari" : "popupBackground";
				hideAllElement('select', this.bg, 1)
				document.body.appendChild(this.bg);
				//$('#'+bgid).fadeIn();
			//$('#'+bgid).css({backgroundColor:'#000',opacity:0.8,width:page.pageWidth+'px',height:page.pageHeight+'px'}).fadeIn();
			}
			//	window
			/*this.table = ce("TABLE");
			this.tbody = ce("TBODY");
			this.tr = ce("TR");
			this.td = ce("TD");*/
			
			this.win = ce('div');
			this.win.id = pop;
			this.win.className = 'dialog';
			this.win.style.width = width+'px';		
			//this.win.style.height = height+'px';
			this.win.style.left = left +'px';		
			this.win.style.top = top +'px';
			this.win.style.position = "absolute";		
			//	title bar
			this.tit = ce('div');
			this.tit.style.width = width+'px';
			this.tit.id = 'titlebar';	
			
			if(isclose == false) var header = '';
			else var header = '<div class="close"><a href="javascript:'+onclose+';" ><img id="popup_close_button" src="'+g_template_img+'img_popupclose.gif" border="0"></a></div>';	
			
			this.tit.innerHTML = header;
			this.win.appendChild(this.tit);
			
			//Inner Window	
			this.innerwin = ce('div');
			this.win.appendChild(this.innerwin);	
			//this.innerwin.className = 'content-area';
			this.innerwin.className = popupBgClass;
			
			//	title
			if( title != '' ) {
				this.titlediv = ce('div');
				this.titlediv.className = 'title';
				this.innerwin.appendChild(this.titlediv);	
				this.titlediv.innerHTML = title;
				this.br = ce('br');
				this.br.className = 'clear';
				this.innerwin.appendChild(this.br);	
			}
			//	Content area		
			this.con = ce('div');
			this.con.id = popcontainer;
			this.con.style.width = width+'px';
			this.con.style.height = height+'px';
			this.innerwin.appendChild(this.con);	
			//this.con.className = 'content-area';
				
			this.con.innerHTML = content;
			//this.con.onresize = function() {};
			this.show = function() {
			//	hideAllElement('select', this.win)				
				document.body.appendChild(this.win);
				/*if ( document.all ){
					setTimeout( function(){
										 	if ( $('#popup_close_button') ) $('#popup_close_button').attr('src', g_template_img+'img_popupclose.gif');
											if ( $('#titlebar') ){ $('#titlebar').attr('background', g_template_img+'img_popuplogo.gif');
											}
										 }, 100);
				}	*/			
				if( isdrag ) {
					this.tit.style.cursor = 'move';
					this.drag = new drag( {src:this.tit, draggable:this.win, identy:this.tit.id} )
				}
			}
			this.sethtml = function(html) {
				$(this.con).css('height','auto');
				$(this.con).html(html);
				this.loaded = true;
				this.resizeDialog();
				//this.resetHeight( parseInt($(this.con).offsetHeight) );
			}
			this.setHeight = function(height){
				if(!browser.isIE){
					height = this.con.offsetHeight + parseInt(height);					
					$(this.con).css('height', height + 'px'); 
				}
			}
			this.resizeDialog = function(){				
				$(this.con).css('height','auto');
				//alert($(this.con).attr('offsetHeight'));
				this.resetHeight( parseInt($(this.con).attr('offsetHeight')) );
			}
			this.resetHeight = function(height){
				height = parseInt(height);					
				$(this.con).css('height', height + 'px'); 
			}
			this.resize = function() {
				if(!browser.isIE){	
					if( this.con.clientHeight < this.win.clientHeight )
						$(this.con).css('height', this.win.clientHeight);
				}
			}
			this.gethtml = function() {
				return this.con.innerHTML;
			}		
			this.close = function() {
				if( this.loaded ) {
					showAllElement('select');
					if( this.bg ){
						var bgid = this.bg.id;
						$(this.bg).fadeOut( function(){$('#'+bgid).parent().remove();} );
					}
					if( this.win ) this.win.parentNode.removeChild(this.win);
				}
			}
		
	}	
	
	//	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
	//modified by ArulKumaran on to solve the problem in not remove the middle white space....
	function trim(nStr){
		return nStr.replace(/(^\s*)|(\s*$)/g, "");
	}
	
	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,3})$";
			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){
		/*var urlPattern= /^(http:\/\/|https:\/\/|www.){1}([\w]+)(.[\w]+){1,2}$/;
		//var urlPattern=  '/^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+(=\w+)?)(&\w+(=\w+)?)*)?/';
		var vRegExp = new RegExp(urlPattern);
		return (vRegExp.test(pmUrl));*/
		if (pmUrl.indexOf(" ")!=-1) return false;
		//var urlPat=/^(http:\/\/)|(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
	//	var urlPat=/^(http:\/\/){1}(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
		 urlPat= /^(http:\/\/|https:\/\/|www.){1}([\w]+)(.[\w]+){1,2}[A-Za-z0-9-_%&\?\/.=\-\*\$]+$/;
		if ( pmUrl.match(urlPat) == null ) return false;
		return true;
	}
	function isValidMySiteUrl(pmUrl){
		
		if (pmUrl.indexOf(" ")!=-1) return false;
		var vPattern = g_site_path+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
		var vLength  = pmUrl.length;
		for (var vLoop = 0; vLoop < vLength; vLoop++) 
			if (vPattern.indexOf(pmUrl.charAt(vLoop)) == -1) return false;
		return true;
		
	/*	var urlPat = /^(http:\/\/my.celebrations.com\/){1}([a-zA-Z0-9_]+)$/; 
		if ( pmUrl.match(urlPat) == null ) return false;
		return true;*/
	}
	
	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;

		/*var vRegExp = new RegExp("[ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÐÁÁÿÐ×Þðþÿ§ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÐÁÁÿÐ×Þðþÿ§]");		
		alert(vRegExp.test(pmStr));
		return (vRegExp.test(pmStr));*/
	}
	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) {
		/* Function will check whether the given zip code is valid or not */
		/*if(!trim(pmZipCode)) return false;		
		var vInValidChar = "!!*|,\":<>[]{}`\';()@&$#%";
		var vLength = pmZipCode.length;		
		for (var vLoop = 0; vLoop < vLength; vLoop++) 	{
			if (vInValidChar.indexOf(pmZipCode.charAt(vLoop)) != -1) return false;
		}
		return true;*/
		reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
		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;
		}
	}
	/*
     * hides give objects (for IE only)
     */
	function hideAllElement( elmID, overDiv , greypopup) {
		if( document.all )	{
			for( i = 0; i < document.all.tags( elmID ).length; i++ )	{
				thispopup = 0;
				obj = document.all.tags( elmID )[i];
				
				if( !obj || !obj.offsetParent ) continue;
				// Find the element's offsetTop and offsetLeft relative to the BODY tag.
				objLeft   = obj.offsetLeft;
				objTop    = obj.offsetTop;
				objParent = obj.offsetParent;
				while( objParent.tagName.toUpperCase() != "BODY" )	{
					objLeft  += objParent.offsetLeft;
					objTop   += objParent.offsetTop;
					objParent = objParent.offsetParent;
					//alert(objParent.className);
			
					if(objParent.id == overDiv.id){
						thispopup = 1;	
						break;
					}
				}
				
				if(thispopup == 1)	continue;
				if(greypopup){obj.style.visibility = "hidden";}
				else{
					objHeight = obj.offsetHeight;
					objWidth = obj.offsetWidth;
					if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
					else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
					else if( overDiv.offsetTop >= ( objTop + objHeight ));
					else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
					else	obj.style.visibility = "hidden";
				}
			}
		}
	}
     
    /*
     * unhides give objects (for IE only)
     */
	function showAllElement( elmID )	{
		if( document.all )	{
			for( i = 0; i < document.all.tags( elmID ).length; i++ ) {
				obj = document.all.tags( elmID )[i];				
				if( !obj || !obj.offsetParent )
					continue;
				obj.style.visibility = "";
			}
		}
	}
	
	function showHint( obj, text, pwdfield ) {
		var isPwd = !isdefined(pwdfield) ? 0 : pwdfield;
		if( !obj ) return;
		if( obj.value == '' ){
			if ( isPwd == 1 ){				
				togglePasswordField(obj, 0);
				//$(obj).attr('type','text');
				//obj.setAttribute('type','text');
			}
			obj.value = text;
		}
	}
	function removeHint( obj, text, pwdfield ) {
		//alert(pwdfield);
		var isPwd = !isdefined(pwdfield) ? 0 : pwdfield;
		if( !obj ) return;
		if( obj.value == text ){			
			obj.value = '';
			if ( isPwd == 1 ){
				togglePasswordField( obj, 1 );
				//$(obj).attr('type','password');
				//obj.setAttribute('type', 'password');				
			}
		}
	}
	function togglePasswordField( obj, want ){
		var isIE = document.all ? 1 : 0;
		if( isIE ){//for crappy IE work around.
		  var nextNode = obj.nextSibling;
		 /* if ( isdefined( obj.onblur ) ){
			  removeEvent(obj, 'keypress', function(e){var e = !e ? window.event : e; detectKey(e,1)} );
			  removeEvent(obj, 'blur', function(e){showHint(this,'Password',1)} );
			  removeEvent(obj, 'focus', function(e){removeHint(this,'Password',1)} );
		  }*/
		  obj.removeNode(true);
		  var newpwd = document.createElement("INPUT");
		  newpwd.setAttribute("type", want ? "password" : "text" );
		  newpwd.setAttribute("id", obj.id );		  
		  //alert(nextNode.id)		  
		  ge('LoginBox').insertBefore(newpwd, ge('RememberMe'));
		  //addEvent(obj, 'keypress', function(e){var e = !e ? window.event : e; detectKey(e,1)} );
		  //addEvent(obj, 'blur', function(e){showHint(this,'Password',1)} );
		  //addEvent(obj, 'focus', function(e){removeHint(this,'Password',1)} );
		  document.getElementById(obj.id).onkeypress = function(e){var e = !e ? window.event : e; detectKey(e,1)};
		  document.getElementById(obj.id).onblur = function(e){showHint(this,'Password',1)};
		  document.getElementById(obj.id).onfocus = function(e){removeHint(this,'Password',1)};
		  if ( !want ) setTimeout(function(){newpwd.setAttribute('value','Password')},200);
		  //$(newpwd).bind('keypress',function(e){detectKey(e,1)});
		  //$(newpwd).bind('blur',function(e){showHint($(this),'Password',1)});
		  //$(newpwd).bind('focus',function(e){removeHint($(this),'Password',1)});
		 // $(nextNode).append( newpwd );
		  //frm.insertBefore(obj, nextNode);
		}else{//for mozilla(NS) based browsers and all other standard compliant browsers.
		  obj.setAttribute("type",want ? "password" : "text" );
		  obj.setAttribute("id", obj.id );
		  //frm.innerHTML = frm.innerHTML;		 
		}
		ge( obj.id ).focus();
		//document.getElementById("passwordField").focus();
	}
	function showTinyHint( obj,  text ) {
		if( !obj ) return;
		var content = striptags(tinyMCE.activeEditor.getContent());
		if( content == '' || content == "&nbsp;" ) tinyMCE.activeEditor.setContent(text) ;
	}
	function removeTinyHint( obj, text ) {
		if( !obj ) return;		
		if( striptags(tinyMCE.activeEditor.getContent()) == text )  tinyMCE.activeEditor.setContent('');
	}

	/* Common Function for Checking for Given File is Valid */
	function ffCheckFileExtension( pmArrayFileExtension, pmFile ){
		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 clearAllErrorFields(pmArray){
		for(vIndex = 0; vIndex < pmArray.length; vIndex++)
			if(ge(pmArray[vIndex]))	ge(pmArray[vIndex]).innerHTML = '';
	}
	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;
	}
	//
	function globalSearchValidate( oFrm ) {
		vLen = oFrm.srchOption.length;
		for(vIndex = 0; vIndex < vLen; vIndex++){
			if(oFrm.srchOption[vIndex].checked){
				vOption = oFrm.srchOption[vIndex].value;
				break;
			}
		}
		obj = ge('txt-global-search');
		vKeyword =trim( obj.value ); 
		if( vKeyword == 'Search' || vKeyword.length == 0) {
			$('#err_global_search').html('Please enter search string');
			obj.focus();
			return false;
		}else if(!CheckSpecialChars(vKeyword)){
			$('#err_global_search').html('Special characters are not allowed.');
			obj.focus();
			return false;
		  } else if(vOption == 'Text'){
			arKeyword = vKeyword.split(" ");
			vKeywordCnt = arKeyword.length;
			for(vIndex = 0; vIndex < vKeywordCnt; vIndex++){
				if(arKeyword[vIndex].length < 4 && arKeyword[vIndex].length !=0)	{
					$('#err_global_search').html('Each word should be a minimum of 4 characters');
					obj.focus();
					return false;
				}
			}
		  }		
		return true;
	}
	function showLoginWarnning( e, message, offsettop, offsetleft, reloadpops ) {
		if( typeof offsettop == 'undefined' ) offsettop = 0;
		if( typeof offsetleft == 'undefined' ) offsetleft = 0;
		message = 'You need to <a class="warnning" href="javascript:void(0);" onclick="getLogin(event,1)">login</a> to use this feature.';
		/*if( typeof message == 'undefined' ) 
			message = 'You need to <a class="warnning" href="javascript:void(0);" onclick="getLogin(event,1)">login</a> to use this feature.';
		else
			message += '<div style="text-align:center"><a href="Javascript:void(0);" onclick="getLogin(event,1)" class="warnning">login</a>&nbsp;Or <a href="'+g_site_path+'register" class="warnning">register</a></div>';*/
		if ( isdefined(reloadpops) && reloadpops ) reloadpopup( {event:e, width:350, height:50, offsetleft:offsetleft, offsettop:offsettop, content:message } );
		else popup( {event:e, width:270, offsetleft:offsetleft, offsettop:offsettop, content: message} );
		//l = new dialog( {title:'Warning!', width:500, height:100, onclose:'l.close()', ismodel:true, isdrag:true} );
		//l.sethtml( 'you need to log in to use this feature.' ); 
		//l.show();
	}
	function showCustomWarnning( e, obj, message, offsettop, offsetleft, reloadpops ) {								
		if( typeof offsettop == 'undefined' ) offsettop = 0;
		if( typeof offsetleft == 'undefined' ) offsetleft = 0;
		if( typeof message == 'undefined' ) 
			message = 'You need to <a class="warnning" href="javascript:void(0);" onclick="getLogin(event,1,'+obj+')">login</a> to use this feature.';
		else
			message += '<div style="text-align:center"><a href="Javascript:void(0);" onclick="getLogin(event,1,'+obj+')" class="warnning">login</a>&nbsp;Or <a href="Javascript:void(0);" onclick="redirectToRegisterPage('+obj+')" class="warnning">register</a>&nbsp;<span><img src="'+g_template_img+'icon-spinner.gif" id="show-reg-loading" style="display:none;" /></span></div>';
		if ( isdefined(reloadpops) && reloadpops ) reloadpopup( {event:e, width:350, height:50, offsetleft:offsetleft, offsettop:offsettop, content: message } );
		else popup( {event:e, width:300, offsetleft:offsetleft, offsettop:offsettop, content: message } );
	}
	function redirectToRegisterPage( obj ){		
		obj.redURL = document.location.href;
		var serialObj = serialize( obj );
		$('#show-reg-loading').css('display','inline');
		$.ajax({
					type : "POST",
					url	 : g_site_path+"ajax/assign-values",
					data : 'sessvalues='+encodeURIComponent(serialObj),
					dataType : 'html',
					success: function(html){
						$('#show-reg-loading').css('display','none');
						window.location.href = g_site_path + 'register';
					}
			   });	
	}
	//	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)	{
		delCookie(cookieName); 
		nDays=11;
		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 '';
	
	}
	function hasValue(val, errdiv, fld, msg, isTiny){
		if ( val == "" ){			
			$('#'+errdiv).html(msg);
			if(isTiny)
				MoveFocusToEditor(fld);				
			else
				if(ge(fld)) ge(fld).focus();
			return 0;
		}
		return 1;
	}
	//	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 PromoteMemTopGirl(){
		var startDate = $('#txtStartDate').val();
		var endDate	  = $('#txtEndDate').val();
		var girlMemId = $('#hidMemId').val();
		/*if ( startDate == '' ){
			$('#showError').html('Please specify the start date');
			return;
		}		
		if ( !$('input[name="chkNoEndDate"]').is(':checked') ){
			if ( endDate == '' ){
				$('#showError').html('Please specify the end date');
				return;
			}
			if(!CompDate(startDate,endDate)){
				$('#showError').html('Please specify the end date should be greater than the start date');
				return;
			}
		}*/
		var status  = $('input[name="chkShowthisgirl"]').is(':checked') ? 1 : 0;		
		var linkPrf = $('input[name="chkShowMyProfileLink"]').is(':checked') ? 1 : 0;
		$.ajax({
			type : "POST",
			url	 : g_con+"con_profile_process.php",
			data : 'fname=PromoteMemTopGirl&startdate='+startDate+'&enddate='+endDate+'&status='+status+'&linkprf='+linkPrf+'&topgmemid='+girlMemId,			
			error: function(req, err, obj) {
				alert ("Error in Ajax call: " + err + " - " + req.status); 			 
			},
			success: function(xml){				
				$('#showError').html('Updated Successfully');
			}
		});
	}
	function viewProfileInfo( e, pmMemId ){
		popup( {event:e, width:400, url:g_com+"com_process.php", data:'fname=viewProfileInfo&userid='+pmMemId } );
	}
	//	Get My Saved Post Module //
	function getMySavedPost( pmShowAll, pmContType ){
		if ( !isdefined(pmShowAll) ) pmShowAll = 0;
		$('#divMySavedPost').html('<span class="warnning">Loading...</span>');
		$.ajax({
				type:"GET",
				url: g_com+"com_process.php",
				data: "fname=getMySavedPosts&showall="+pmShowAll+"&contributetype="+pmContType,
				success: function(rs){
					$('#divMySavedPost').html(rs);
				}
		});
	}
	// Showing the Media in Popup
	function showMedia( e, medid ){
		popup( {event:e, width:200, url:g_com+"com_process.php", data:'fname=viewMediaInfo&media_id='+medid } );
	}
	function showHelp( e,helpid){
		popup( {event:e, url:g_com+"com_process.php", data:'fname=showHelp&helpid=helpid'} );
	}

	/*function deleteContribute(Props){
		pmSort ='';
		vIsredirect = Props.isRedirect;
		vUrl = decodeURIComponent(Props.redirectUrl);
		if(ge('hidSort'))	pmSort = trim(ge('hidSort').value);
		if ( confirm("Are you sure want to delete this contribute?") ){
			var contid = Props.contid;
			var memid  = Props.memid;
			if(!vIsredirect)	
				$('#myprofile-content').html('<div class="warnning" align="center" style="margin-top:30px">loading...</div>');
			$.ajax({
				type : "POST",
				url	 : g_con+"con_profile_process.php",
				data : 'fname=DeleteContribute&cont_id='+contid,			
				success: function(xml){
					if(vIsredirect)	
						window.location.href = vUrl;
					else
						displayContribute(1, memid, pmSort);
				}
			});
		}
	}*/
	//	get new message template.
	//
	function getNewMessageTemplate( Props ) {
		var toId = isdefined(Props.toid) ? Props.toid :g_v_u;
		url	 = g_site_path + "ajax/profile-msg-template";
		data = 'touserid='+toId+'&rand='+Math.random();
		if ( isdefined(Props.reloadpopup) && Props.reloadpopup ) reloadpopup( {width:430, height:250, event:Props.e, url:url, data:data} );
		else	popup( {width:430,  height:250, event:Props.e, url:url, data:data} );
	}
	//	send new message to another user
	function SendMessageToFriend(){
		var msgBody = $('#txtAreaMessage').val();
		var toId	= $('#ToId').val();
		var subject = $('#txtSubject').val();
		if ( trim(subject) == "" ){
			$('#divResult').html('Please enter the subject');
			ge('txtSubject').focus();
			//popupresize();
			return;
		}
		if ( trim(msgBody) == "" ){
			$('#divResult').html('Please enter the message');
			ge('txtAreaMessage').focus();
			//popupresize();
			return;
		}
		//alert(g_site_path + "ajax/profile-sendmsg?" +'toid='+toId+'&msgbody='+encodeURIComponent(msgBody)+'&subject='+subject )
		$.ajax({
			type : "POST",
			url	 : g_site_path + "ajax/profile-sendmsg", 
			data : 'toid='+toId+'&msgbody='+encodeURIComponent(msgBody)+'&subject='+subject,
			dataType : 'xml',
			success: function(xml){
				$(xml).find('response').each( function(){
					var status  = $(this).find('success').attr('status');
					var message = $(this).find('success').attr('msg');
					$('#divResult').html(message);
					//popupresize();
					setTimeout( 'nopopup()', 1000 );
				});
			}
		});
	}
	//	send mygirl request
	function sendFriendInvite( Props ) {
		e = Props.e;
		var toUserId = isdefined( Props.touserid ) ? Props.touserid : g_v_u;
		url	 = g_site_path + "ajax/profile-friend-invite" ;
		data = 'touserid='+toUserId+'&rand='+Math.random();
		if ( isdefined(Props.reloadpopup) && Props.reloadpopup ) reloadpopup( {width:430, event:e, url:url, data:data, autoclose:true,closedelay:3000} );	
		else popup( {width:430, event:e, url:url, data:data, autoclose:true,closedelay:3000} );	
	}
	function subscribeContributes( params ){
		var toUserId = isdefined( params.to_user_id ) ? params.to_user_id : g_v_u;
		url	 = g_ppl + "usr_process.php";
		data = 'fname=subscribeContributes&userid='+g_u+'&mode='+params.mode+'&touserid='+toUserId+'&rand='+Math.random();
		popup( {width:230, event:params.e, url:url, data:data, autoclose:true,closedelay:3000} );
		setTimeout(function(){
							 	$('#subscribe-'+toUserId).toggle();
								$('#unsubscribe-'+toUserId).toggle();
							 },3000);
	}
	//	Load left/right panels
	function getGirlsLikeMe(pmUserId, pmUserOwner){	//	Load girl like me wondow.
		$.ajax({type:"POST", url:g_ppl+"usr_process.php", data:'fname=getGirlsLikeMe&userid='+pmUserId+'&user_owner='+pmUserOwner+'&frmAjax=1&rand='+Math.random(), success:function(html){$('#girls_like_me').html(html); } } );
	}
	function getTopgirl() {	//	Load top girl window.
		$.ajax({type : "POST",	url	 : g_com+"com_process.php",	data : 'fname=getTopGirl&fromjs=1&rand='+Math.random(),	success: function(html){ $('#div-top-girl').html(html);	} } );
	}
	function getTopdrops() {	//	Load top drops window.
		$.ajax({type : "POST",	url	 : g_com+"com_process.php",	data : 'fname=getTopDrops&fromjs=1&rand='+Math.random(), success: function(html){ $('#div-top-drops').html(html); } } );
	}	
	function getMostPopular( pmOpt ){	//	//	Load most popular post window.
		$('#div-top-popular').html('<span class="warnning">Loading...</span>');
		$.ajax({type:"POST", url:g_com+"com_process.php",data:"fname=getMostPopular&fromjs=1&filter="+pmOpt+"&rand="+Math.random(),success:function(rs){ $('#div-top-popular').html(rs); } } );
	}	
	function getTopContributorList( pmOpt ){ //	Load top contributer window - day, week, month, ever list changing.
		$('#div-top-contributer').html('<span class="warnning">Loading...</span>');
		$.ajax({type:"GET",	url: g_com+"com_process.php", data: "fname=getTopContributer&fromjs=1&filter="+pmOpt+"&rand="+Math.random(), success:function(rs){$('#div-top-contributer').html(rs); } } );
	}	
	function getRelatedpeople() {	//	Load related people window.
		$.ajax({type:"POST", url:g_com+"com_process.php", data:'fname=getRelatedPeople&fromjs=1&rand='+Math.random(), success: function(html){ $('#div-related-people').html(html); } } );
	}
	
	function getRelatedPost(pmIntCat, pmContCat, pmContId, pmIsTopGirl){	//	Load related post window.
		var intcat_ids = !isdefined(pmIntCat)?'':pmIntCat;
		var contcat_ids = !isdefined(pmContCat)?'':pmContCat;
		var cont_id = !isdefined(pmContId)?0:pmContId;
		var isTopgirl = !isdefined(pmIsTopGirl)?0:pmIsTopGirl;
		$('#related-post').html('<span class="warnning">Loading...</span>');
		$.ajax({
				type:"GET",	url: g_com+"com_process.php",
				data: "fname=getRelatedPost&int_cat="+escape(intcat_ids)+"&cont_cat="+escape(contcat_ids)+"&cont_id="+cont_id+'&istopgirl='+isTopgirl,
				success: function(rs){	$('#related-post').html(rs); }
		});
	}
	function getTags() {	//	Load tags window.
		$.ajax({type:"POST", url:g_com+"com_process.php", data:'fname=getTags&fromjs=1&rand='+Math.random(), 
	 		   success: function(html){ 
			   		$('#div-tags').html(html); 
					//Dynamically setting the cloud class name for tag based on the tag count passed in id attribute
					var pmRefClassName = 'tagcloud';
					var maxStyle = 5;
					var Max = $('#Max').val();
					var Min = $('#Min').val();
					$('.'+pmRefClassName).each(
						function(){
							var count = $(this).attr('id');
							sizeTag = Math.round((((maxStyle-1)/(Max-Min))*count) +(1*Max-maxStyle*Min)/(Max-Min));
							$(this).attr('className',"cloud"+sizeTag);
						}
					);
				} } );
	}
	var out, transaction;
	var sessTime = 30000;	//	30 secs
	function setSession()	{
		
		out = window.setTimeout(traceSessionOut, sessTime);
	}	
	function traceSessionOut()	{
		window.clearTimeout( out );
		traceAction();
		/*if(!g_lin) return;
		$.ajax( {type:"POST", url:g_site_path+'ajax/manage-session', data:'&rand='+Math.random(), 
	 		   success: function( html ){
				   	//	popup alert for session timeout.
						g_lin = 0;
						odialog = new dialog( {title:'Login', width:580, height:150, onclose:'window.location=\''+g_site_path+'\'', ismodel:true, isdrag:false} );	
						odialog.sethtml('<div class="warnning" style="margin-top:50px">Your session has been timed out. Please <a class="pro_contenttext" href="javascript:;" onclick="getLogin(event)">login</a> to continue...</div>');
						odialog.show();
				   } 
				} );*/
	}
	function traceAction()	{
		clearTimeout( out );
		$.ajax( {type:"POST", url:g_site_path+'ajax/manage-session', data:'action=1&rand='+Math.random(), 
	 		   success: function( html ) {
				   		resetTime();
			   		} 
				} );
	}
	function resetTime() {
		clearTimeout( out );
		out = setTimeout(traceSessionOut, sessTime);
	}

	//	Login
	function login(){
		var login_user_name = $("#user_login").val() == 'User Name' ? '' : trim( $("#user_login").val());
		var login_password  = $("#user_pass").val() == 'Password' ? '' : trim( $("#user_pass").val() );
		if ( login_user_name == "" ){
			$('#divlogin_err').html('Please enter Username');
			document.getElementById('user_login').focus();
			return false;
		}
		else if( login_password == "" ){
			$('#divlogin_err').html('Please enter Password');
			document.getElementById('user_pass').focus();
			return false;
		}
		else{
			vData = 'vuname='+trim($("#user_login").val())+'&vpass='+trim($("#user_pass").val())+"&rand="+Math.random(); 
			$.ajax({
						type : "POST",
						url	 : g_site_path+"ajax/login",
						data : vData,
						dataType : 'xml',
						success: function( xml ){
							$(xml).find('response').each(function(){
								var status = parseInt( $(this).find('status').text() );
								if ( status == 1 ){
									if ( ge('chkRememberMe').checked ){
										setCookie( g_cookie_prefix+"username", $("#user_login").val() );
									}else{
										delCookie( g_cookie_prefix+"username" );
									}
									var redurl = $(this).find('redurl').text();
									if ( redurl != '' )
										window.location = redurl;
									else
										self.location.reload();
										//window.location = g_site_path+"home";
								}else{
									var message = $(this).find('message').text();
									$('#divlogin_err').html( message );	
								}
							});
							/*var length = trim(html).length;			
							if(length==7){
								window.location = g_site_path+"home";
								return false;				
							}
							else{						
								$('#divlogin_err').html(html);	
								return false;				
							}		*/				
						}
				   });	
		}
	}
	function detectKey( event, type ){
		if ( event.keyCode == 13 ){ 
			if( type == 1 ){
				login();			
			}else if( type==2 ){
				forgotpassword();		
			}
			else if( type == 3 ){
				//
			}
		}
	}

	function login_old( param, obj ) {		
		var email 	 = trim($('#txt_login_email').val());
		var password = trim($('#txt_login_password').val());
		//alert(email);
		$('#err_login_email').html('');
		$('#err_login_password').html('');
		var error = false;
		if ( email == ""  ) {
			$('#err_login_email').html('Please enter a email address.');
			$('#txt_email').focus();
			popupresize();
			error = true;
		}
		
		if ( !isValidEmail(email) ){
			$('#err_login_email').html('Please enter a valid email address');
			$('#txt_email').focus();
			popupresize();
			error = true;
		}
		if ( password == "" ){
			$('#err_login_password').html('Please enter a password');
			$('#txt_password').focus();
			popupresize();
			error = true;
		} else if ( password.length < 6 ){
			$('#err_login_password').html('Password should be minimum of 6 chracters.');
			$('#txt_password').focus();
			popupresize();
			error = true;
		}	
		if( error  ) return;
		$('#btnLogin').disabled = true;
		
		var vData = '';
		
		if ( !isdefined(obj) )
			vData = 'email='+email+'&password='+password;
		else
			vData = 'email='+email+'&password='+password+'&sessvalues='+encodeURIComponent(serialize( obj ));				
		
		$('#content-area').css('display', 'none');
		$('#success-area').css('display', 'block');
		$('#success-area').html('Please wait... while we logging in!');
		$.ajax({
			type : "POST",
			url	 : g_site_path+"ajax/login",
			data : vData+'&rand='+Math.random(),
			dataType : 'xml',
			success: function(xml){
				$(xml).find('response').each( function(){
					var status  = parseInt($(this).find('status').text());
					if ( status == 0 ) {
						$('#content-area').css('display', 'block');
						$('#success-area').css('display', 'none');
						ge('btnLogin').disabled = false;
						ge('err_login_password').innerHTML = 'Invalid email or password!';
						//popupresize();
					} else if ( status == 1 ) {						
						setCookie( g_cookie_prefix+"email", email );
						redirectother =  $(this).find('redirectother').text();
						var loginsuccess_callback = $(this).find('callback').text();						
						vRedURL = $(this).find('redurl').text();
						$('#success-area').html('Login success...');
						if( redirectother == 1 ) window.location.href = vRedURL;
						else{
							if ( loginsuccess_callback != '' ){
								nopopup();
								g_lin = '1';
								setTimeout(loginsuccess_callback,1);								
							}
							else
								self.location.reload();
						}
						//window.location.href = self.location;						
					}
				});
			}
		});
	}
	
	function setCookInfoToLogin(){
		coo_email = trim(getCookie(g_cookie_prefix+"username"));
		if( coo_email != '' ) {
			ge('user_login').value = coo_email;
			ge('user_pass').value = "";
			ge('chkRememberMe').checked = true;
		
		}
	}
	
	function traceKey( code, obj ) {
		if( code == 13 ){
			if ( !isdefined(obj) ) login();
			else login(1, obj );
		}
	}
	
	function getLogin( e, reloadpops, obj ) {
		var redurl = '&redurl='+document.location.href;
		if( document.getElementById( 'user_login' ) ) {
			$('#user_login').select();
			nopopup();
		} else {
			if (  isdefined(reloadpops) && reloadpops  ){
				if ( !isdefined( obj ) )
					reloadpopup( {event:e, width:350, url:g_site_path+"ajax/get-login", data:redurl, callback:'setCookInfoToLogin()', loginwindow:true,height:'120px' } );
				else{
					obj.redURL = document.location.href;
					var encObj = serialize( obj );
					//alert(encObj)
					reloadpopup( {event:e, width:350, url:g_site_path+"ajax/get-login", data:'trackData='+encodeURIComponent(encObj), callback:'setCookInfoToLogin()', loginwindow:true } );
				}
			}
			else{
				if ( !isdefined( obj ) )
					popup( {event:e, width:350, url:g_site_path+"ajax/get-login", data:redurl, callback:'setCookInfoToLogin()', loginwindow:true } );
				else{
					obj.redURL = document.location.href;
					var encObj = serialize( obj );					
					popup( {event:e, width:350, url:g_site_path+"ajax/get-login", data:'trackData='+encodeURIComponent(encObj), callback:'setCookInfoToLogin()', loginwindow:true } );
				}
			}
		}
	}
	
	function getForgotpwd( e, ispopup ) {
		if( ispopup ) {
			reloadpopup( {event:e, width:350, url:g_site_path+"ajax/get-forgot-password", data:'','poptitle':'FORGOT PASSWORD'} )
		} else {
			popup( {event:e, width:350, height:150 ,url:g_site_path+"ajax/get-forgot-password", data:'', callback:'setCookInfoToLogin()','poptitle':'FORGOT PASSWORD' } );
		}
	}
	function MoveFocusToEditor(id)	{
		//return;
		if (tinyMCE.activeEditor.getContent() != null)		{
			//var vEditorId = tinyMCE.idCounter-1;	
			var oInstance = tinyMCE.get(id);
			oInstance.getWin().focus();
		} else 	{	ge(id).focus();	}
	}
	function getTinyMceContent( id ){
		var oInstance = tinyMCE.get(id);
		var content   = trim(oInstance.getWin().document.body.innerHTML);		
		var html	  = '';
		if ( content != '' ){			
			var temp = striptags(content)
			if ( temp == '&nbsp;' || temp == '' ) 
				html = temp;
			else 
				html = content;
		}
		return html;
	}
	var autosave_interval = '';
	function start_autosave(funcname){
		autosave_interval = window.setInterval(function(){if(!g_lin) return;eval(funcname);}, 60000)	
	}
	function stop_autosave(){
		if(autosave_interval!=""){
			window.clearInterval(autosave_interval)
			autosave_interval="";
		}
	}
    function striptags(a){
		return a.replace(/<\/?[^>]+>/gi,"")
	}
	function redirectToContribute(e){
		if(g_lin==1)	self.location= g_site_path +'contribute';
		else	getLogin(e)
	}
	function getContributeDetail( param ) {
		//alert(g_site_path+"ajax/show-contribute-detail/cateid/"+param.cate_id+"/contid/"+param.cont_id);	
		var target = ( (!isdefined(param.prefix) || param.prefix == '') ? 'contcat-details-'+param.cont_id : 'contcat-details-'+param.cont_id+param.prefix );
		preview = 0;
		if( isdefined( param.ispreview ) ) preview = param.ispreview ;
		//alert(preview);
		$( '#'+target ).html( '<span class="warnning">Loading...</span>' );
		//alert(g_site_path+"ajax/show-contribute-detail/articleid/"+param.article_id+"/cateid/"+param.cate_id+"/contid/"+param.cont_id);
		$.ajax({
				type : "POST",
				url	 :g_site_path+"ajax/show-contribute-detail/articleid/"+param.article_id+"/cateid/"+param.cate_id+"/contid/"+param.cont_id+"/preview/"+preview,
				
				data : 'rand='+Math.random(),
				dataType: "html",
				success: function(html){		
					
					$( '#'+target ).html( html );
				}
		   });
		
	}
	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 urlencode( str ) {
		// URL-encodes string  
		// 
		// version: 905.3122
		// discuss at: http://phpjs.org/functions/urlencode
		// +   original by: Philip Peterson
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: AJ
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Brett Zamir (http://brett-zamir.me)
		// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: travc
		// +      input by: Brett Zamir (http://brett-zamir.me)
		// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Lars Fischer
		// %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
		// *     example 1: urlencode('Kevin van Zonneveld!');
		// *     returns 1: 'Kevin+van+Zonneveld%21'
		// *     example 2: urlencode('http://kevin.vanzonneveld.net/');
		// *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
		// *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
		// *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
								 
		var histogram = {}, unicodeStr='', hexEscStr='';
		var ret = (str+'').toString();
		
		var replacer = function(search, replace, str) {
			var tmp_arr = [];
			tmp_arr = str.split(search);
			return tmp_arr.join(replace);
		};
		
		// The histogram is identical to the one in urldecode.
		histogram["'"]   = '%27';
		histogram['(']   = '%28';
		histogram[')']   = '%29';
		histogram['*']   = '%2A';
		histogram['~']   = '%7E';
		histogram['!']   = '%21';
		histogram['%20'] = '+';
		histogram['\u00DC'] = '%DC';
		histogram['\u00FC'] = '%FC';
		histogram['\u00C4'] = '%D4';
		histogram['\u00E4'] = '%E4';
		histogram['\u00D6'] = '%D6';
		histogram['\u00F6'] = '%F6';
		histogram['\u00DF'] = '%DF';
		histogram['\u20AC'] = '%80';
		histogram['\u0081'] = '%81';
		histogram['\u201A'] = '%82';
		histogram['\u0192'] = '%83';
		histogram['\u201E'] = '%84';
		histogram['\u2026'] = '%85';
		histogram['\u2020'] = '%86';
		histogram['\u2021'] = '%87';
		histogram['\u02C6'] = '%88';
		histogram['\u2030'] = '%89';
		histogram['\u0160'] = '%8A';
		histogram['\u2039'] = '%8B';
		histogram['\u0152'] = '%8C';
		histogram['\u008D'] = '%8D';
		histogram['\u017D'] = '%8E';
		histogram['\u008F'] = '%8F';
		histogram['\u0090'] = '%90';
		histogram['\u2018'] = '%91';
		histogram['\u2019'] = '%92';
		histogram['\u201C'] = '%93';
		histogram['\u201D'] = '%94';
		histogram['\u2022'] = '%95';
		histogram['\u2013'] = '%96';
		histogram['\u2014'] = '%97';
		histogram['\u02DC'] = '%98';
		histogram['\u2122'] = '%99';
		histogram['\u0161'] = '%9A';
		histogram['\u203A'] = '%9B';
		histogram['\u0153'] = '%9C';
		histogram['\u009D'] = '%9D';
		histogram['\u017E'] = '%9E';
		histogram['\u0178'] = '%9F';
		
		// Begin with encodeURIComponent, which most resembles PHP's encoding functions
		ret = encodeURIComponent(ret);
	
		for (unicodeStr in histogram) {
			hexEscStr = histogram[unicodeStr];
			ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
		}
		
		// Uppercase for full PHP compatibility
		return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
			return "%"+m2.toUpperCase();
		});
	}

	function validateExtendedChars(pmStr, pmDiv, pmErrDiv){
		if(isExtendedChars(pmStr)){
			ge(pmErrDiv).innerHTML = 'Extended characters are not allowed.';
			ge(pmDiv).focus();
			return 0;
		}
		return 1;
	}

	
	function getHomeIcons( page ) {
			$( '#home-icons' ).html('<span class="warnning" style="padding:20px;">Loading...</span>');
			$.ajax({
				type : "POST",
				url	 :g_site_path+"ajax/get-home-icons",				
				data : 'pageno='+page+'&rand='+Math.random(),
				dataType: "html",
				success: function(html){
					$( '#home-icons' ).html( html );
				}
		   });
	}
	
//backup for immage scrolling in index page......

	/*function getHomePopularInvitations( dir ) {
		
			var index = parseInt( $('#hid_index').val() );			
			$("#tbl_popular_invites").css('position', 'relative');
			if( parseInt(index) == 1 ||  parseInt(index) == -1 ) {				
				$('#hid_baseleft').val( $('#tbl_popular_invites').position().left );
			}
			
			var baseleft = parseInt( $('#hid_baseleft').val() );
			var delta = $('#tbl_popular_invites').position().left - baseleft;
			
			if( dir == 'r' )	{
				delta -= 200;
				$('#hid_index').val(index+1);
				$('#move_left').css('display', 'block');
			} else if( dir == 'l' ) {
				delta += 200;
				$('#hid_index').val(index-1);
				$('#move_right').css('display', 'block');
			}
			
			$("#tbl_popular_invites").animate( {left:delta}, 500 );
			if( parseInt( $('#hid_index').val() ) == 1 ){
				$('#move_left').css('display', 'none');
			}
			if( parseInt( $('#hid_index').val() ) == parseInt( $('#hid_count').val() ) - 2 ){
				$('#move_right').css('display', 'none');
			}
			/*$( '#invitations' ).html('<span class="warnning" style="padding:20px;">Loading...</span>');
			$.ajax({
				type : "POST",
				url	 :g_site_path+"ajax/get-popular-invitations",				
				data : 'pageno='+page+'&rand='+Math.random(),
				dataType: "html",
				success: function(html){
					$( '#invitations' ).html( html );
				}
		   });*/
//	}*/
	
	
	function getHomePopularInvitations( dir ) {		
		var index = parseInt( $('#hid_index').val() );			
		$("#tbl_popular_invites").css('position', 'relative');
		if( parseInt(index) == 1 ||  parseInt(index) == -1 ) {				
			$('#hid_baseleft').val( $('#tbl_popular_invites').position().left );
		}
		
		var baseleft = parseInt( $('#hid_baseleft').val() );
		var delta = $('#tbl_popular_invites').position().left - baseleft;
		
		if( dir == 'r' )	{
			delta -= 201;
			$('#hid_index').val(index+1);
			$('#move_left').css('display', 'block');
		} else if( dir == 'l' ) {
			delta += 201;
			$('#hid_index').val(index-1);
			$('#move_right').css('display', 'block');
		}
		
		$("#tbl_popular_invites").animate( {left:delta}, 500 );
		
		if( parseInt( $('#hid_index').val() ) == 1 ){
			$('#move_left').css('display', 'none');
		}
		if( parseInt( $('#hid_index').val() ) == parseInt( $('#hid_count').val() ) - 2 ){
			$('#move_right').css('display', 'none');
		}			
	}
	
	var inviation_page=1;
	function getNextInvitationPage(){
		if ( inviation_page == parseInt($('#hid_tot_page').val()) ) return;
		inviation_page++;
		$.ajax({
				type : "POST",
				url	 :g_site_path+"ajax/get-popular-invitations",				
				data : 'frmAjax=1&page='+inviation_page+'&rand='+Math.random(),
				dataType: "html",
				success: function(html){
					$( '#tbl_popular_invites' ).append( html );
				}
		   });
	}
	
	function getPopularInvitations1( dir ) {
		var index = parseInt( $('#hid_o_index').val() );			
		$("#tbl_popular_occastion").css('position', 'relative');
		
		if( parseInt(index) == 1 ||  parseInt(index) == -1 ) {				
			$('#hid_o_baseleft').val( $('#tbl_popular_occastion').position().left );
		}
		
		var baseleft = parseInt( $('#hid_o_baseleft').val() );
		var delta = $('#tbl_popular_occastion').position().left - baseleft;
		
		if( dir == 'r' )	{
			delta -= 125;
			if( ( $('#tbl_popular_occastion').width() + delta ) < 472 )
				delta =  - $('#tbl_popular_occastion').width() + 472;
			$('#hid_o_index').val(index+1);
			$('#move_o_left').css('display', 'block');
		} else if( dir == 'l' ) {
			delta += 119;
			if( delta > 0 ) delta = 0;
			$('#hid_o_index').val(index-1);
			$('#move_o_right').css('display', 'block');
		}		
		$("#tbl_popular_occastion").animate( {left:delta}, 600 );
		
		if( parseInt( $('#hid_o_index').val() ) == 1 ){
			$('#move_o_left').css('display', 'none');
		}
		if( parseInt( $('#hid_o_index').val() ) == parseInt( $('#hid_o_count').val() ) - 3 ){
			$('#move_o_right').css('display', 'none');
		}
	}
	
	function getPopularInvitations( dir ) {
		var index = parseInt( $('#hid_o_index').val() );			
		$("#tbl_popular_occastion").css('position', 'relative');
		
		if( parseInt(index) == 1 ||  parseInt(index) == -1 ) {				
			$('#hid_o_baseleft').val( $('#tbl_popular_occastion').position().left );
		}
		
		var baseleft = parseInt( $('#hid_o_baseleft').val() );
		var delta = $('#tbl_popular_occastion').position().left - baseleft;
		
		if( dir == 'r' )	{
			delta -= 190;
			if( ( $('#tbl_popular_occastion').width() + delta ) < 570 )
				delta =  - $('#tbl_popular_occastion').width() + 570;
			$('#hid_o_index').val(index+1);
			$('#move_o_left').css('display', 'block');
		} else if( dir == 'l' ) {
			delta += 190;
			if( delta > 0 ) delta = 0;
			$('#hid_o_index').val(index-1);
			$('#move_o_right').css('display', 'block');
		}		
		$("#tbl_popular_occastion").animate( {left:delta}, 600 );
		
		if( parseInt( $('#hid_o_index').val() ) == 1 ){
			$('#move_o_left').css('display', 'none');
		}
		if( parseInt( $('#hid_o_index').val() ) == parseInt( $('#hid_o_count').val() ) - 2 ){
			$('#move_o_right').css('display', 'none');
		}		
	}
	
	function doPagingContMediaImage( cur, opt, refid , totalcount ){		
		var display = 'none';		
		for ( var t=0; t<totalcount; t++ ){			
			if ( cur == t ) display = 'block';
			else	display = 'none';
			$('#cont-image-'+refid+'-'+t).css('display',display);
		}
	}
	
	function DeleteContributeItem( obj ){
		var redirect = obj.redirect;
		var refid 	 = obj.refid;
		var type	 = obj.type;
		var callback = obj.callback;
		if ( confirm("Do you want to delete this story?") ){
			$.ajax({
				type : "GET",
				url	 : g_site_path+"ajax/profile-delete-contribution",
				data : 'cont_type='+type+'&contid='+refid+'&pagefrom=nonprofile&rand='+Math.random(),
				dataType : 'html',
				error: function(req, err, obj) {
					alert ("Error in Ajax call: " + err + " - " + req.status); 			 
				},
				success: function(html){
					if ( redirect == 1 )
						window.location.href = callback;
					else
						setTimeout(callback,1);
						//eval(callback);
				}
		   });
		}		
	}
	/*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;
	}
	/*Converting 24Hour Format to 12 Hour and vice-versa*/
	function twodigits( input ) {
		input = input + "";	
		if (input.length == 1) return "0" + input;
		return input;
	}
	function conv24to12clock(hours, ampm24) {	
		if ( ampm24 == "24" ) {
			if (hours < 12)	a_p = "AM";
			else			a_p = "PM";
	
			if (hours == 0)	hours = 12;
			if (hours > 12)	hours = hours - 12;
			
			hours = twodigits ( hours );
			hours = hours + a_p;
		} else {
			if (hours == 12) hours = 0;
			if (ampm24 == "pm")	hours = parseInt(hours) + 12;
			
			hours = twodigits ( hours );
		}
		return hours;
	}
	
	function convert24to12( srctype, inputs ) {
		if ( srctype == "24" ) {
			var hours12 = conv24to12clock( inputs.t24hrValue, inputs.ampmValue );	
			return hours12;			
		} else { 
			var hours24 = conv24to12clock( inputs.t12hrValue, inputs.ampmValue );			
			return hours24;
		}
	}
	/**/
	/*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 doContributeSearch( code ){
		if ( code == 13 ){			
			validatecontsearch();
		}
	}
	
	function validatecontsearch(){
		var text = $('#q').val();		
		if ( trim(text) == '' ){
			$('#err_search_string').html('Please enter search string');
			ge('q').focus();
			return false;
		}
		if ( trim(text).length < 4 ){
			$('#err_search_string').html('search string should contain atleast 4 characters');
			ge('q').select();
			return false;
		}
		ge('frm_contribute_search').submit();
	}
	
	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 GoToURL( url, params, formname ){
		for( key in params ){
			$('#'+key).attr('value', params[key] );			
		}
		url = url.replace('[##DOUBLEQUOTES##]','"');
		url = url.replace('[##QUOTES##]',"'");
		ge(formname).action = url;
		ge(formname).submit();
	}
	
	function NavigatePartyLink( e, obj ){
		var frmStep = obj.from;
		var toStep  = obj.to;
		var eventid = obj.eventid;
		//var skip	= !isdefined(obj.skip) ? 0 : obj.skip;
		//if ( frmStep == 2 && toStep > 2 && skip == 0 ){
		if ( frmStep == 2 && toStep > 2 ){
			//doProcessCreateParty( e, 1, {callback:'NavigatePartyLink("'+e+'",{from:"'+frmStep+'",to:"'+toStep+'",skip:1,eventid:'+eventid+'})',warnning:0,skiplogincheck:0,frmBreadcrumb:1} );			
			doProcessCreateParty( e, 1, {from:frmStep,to:toStep,url:obj.url,frmBreadcrumb:1,warnning:0,skiplogincheck:0} );
			return;
		}else if ( frmStep == 2 && toStep < 2 ){
			window.location.href = obj.url;
		}else if ( frmStep == 1 && toStep > 1 ){
			window.location.href = obj.url;
		}else if ( frmStep == 3 && toStep > 3 ){
			Preview(e, 0, 2, {frmBreadcrumb:1,from:frmStep,to:toStep});
			return;
		}else if ( frmStep == 3 && toStep < 3 ){
			window.location.href = obj.url;
		}else if ( frmStep == 4 && toStep < 4 ){
			window.location.href = obj.url;
		}		
		/*$('#show-loading').css('display','block');
		$.ajax({
				type : "GET",
				url	 : g_site_path+"ajax/get-party-navigate-link",
				data : 'fromStep='+frmStep+'&toStep='+toStep+'&eventid='+eventid+'&rand='+Math.random(),
				dataType : 'xml',
				success: function( xml ){
					$(xml).find('response').each(function(){
						var errors = parseInt( $(this).find('errors').text() );
						$('#show-loading').css('display','none');
						if ( errors == 1 ){
							var content = $(this).find('msgDescription').text();
							popup( {event:e, width:300, content:content } );
						}else{
							var url = $(this).find('url').text();
							window.location.href = url;
						}
					});
				}
		});*/
	}
	
	function assignPageBgLink(){
		var obj  = ge('mainbody');
		var left = 0;
		if ( obj.offsetParent ){
			do{
				left += obj.offsetLeft;
			}while(obj = obj.offsetParent)
		}				
		var leftWidth  = left;
		var height     = browser.getPageSize().pageHeight;
		//alert(height);
		$('#magic_link_left').css({'display':'block','position':'absolute','height':height+'px','width':leftWidth+'px','top':'0px','left':'0px'});
		$('#magic_link_right').css({'display':'block','position':'absolute','height':height+'px','width':leftWidth+'px','top':'0px','left':(leftWidth+ge('mainbody').offsetWidth)+'px'});
	}
	
	function getPageEspot( p ){
		$('#espot_container').html ('<div class="warnning"><img src="'+g_template_img+'icon-spinner.gif"> Loading...</div>');
		$.ajax({
			type : "POST",
			url	 : g_site_path+"ajax/parse-espots",
			data : 'param='+p+'&rand='+Math.random(),
			dataType : 'html',
			success: function( html ) {
				$('#espot_container').html (html);
			}
		});
	}
	
	function validateDecimalNumber( value, maxLength, maxPrecision ){
		var maxLength 	 = !isdefined(maxLength) ? 10 : maxLength;
		var maxPrecision = !isdefined(maxPrecision) ? 2 : maxPrecision;	
		var aNumber  = value.split('.');
		var digitCnt = maxLength - maxPrecision; /* for MySql Mode */
		if ( aNumber[0].toString().length > digitCnt ) return false;
		return true;
	}
	
	function stopBubbling( e ){
		if (!e) var e = window.event;
		if ( e == null ) return false;		
		e.cancelBubble = true;
		e.returnValue = false;
		if ( e.preventDefault ) e.preventDefault();
		if ( e.stopPropagation ) e.stopPropagation();		
	}
	
	function MM_swapImage() { //v3.0
		var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	   	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}
	
	function MM_findObj(n, d) { //v4.01
		var p,i,x;  
		if(!d) 
			d=document; 
		if((p=n.indexOf("?"))>0&&parent.frames.length) {
			d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
		}
	  	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  	if(!x && d.getElementById) x=d.getElementById(n); return x;
	}
	
	function MM_swapImgRestore() { //v3.0
		var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}

	function parseQuery ( query ) {
	   var Params = new Object ();
	   if ( ! query ) return Params; // return empty object
	   var Pairs = query.split(/[;&]/);
	   for ( var i = 0; i < Pairs.length; i++ ) {
		  var KeyVal = Pairs[i].split('=');
		  if ( ! KeyVal || KeyVal.length != 2 ) continue;
		  var key = unescape( KeyVal[0] );
		  var val = unescape( KeyVal[1] );
		  val = val.replace(/\+/g, ' ');
		  Params[key] = val;
	   }
	   return Params;
	}
	
	function listenandSearch( e ){
		var keyCode = e.keyCode;
		if ( keyCode == 13 ) doSearchText();
	}
	
	function doSearchText() {
		var searcid =ge('id').value;
		if( searcid == 1 ){
			var text = ge('s').value == 'search Monavie Tv' ? '' : trim(ge('s').value);
			var searchon = 1;
		}else if( searcid == 2 ){	
			var text = ge('s').value == 'search Photo Gallery' ? '' : trim(ge('s').value);
			var searchon = 2;
		}else{
			var text = ge('s').value == 'search On The Move' ? '' : trim(ge('s').value);
			var searchon = 3;
		}
		//alert(ge('s').value)
		//alert(g_site_path+'search?s='+encodeURIComponent( text ))
		if( searcid == 1 ){
		window.location.href = 'monavietv-channels?s='+encodeURIComponent( text )+'&mode='+searchon;
		}
		else if( searcid == 2 ){
			window.location.href = 'photogallery-categories?s='+encodeURIComponent( text )+'&mode='+searchon;
			
		}
		//ge('frmSearch').action = g_site_path+'search?s='+text;
		//ge('frmSearch').submit();
	}
	
	function showMap( e, zip ) {
		htm  = '<div id="loading" style="margin-left:5px;" class="warnning">Loading....</div><div style="text-align:center;width:440px;height:380px;clear:both;">';
		htm += '<iframe id="ifrmMap" name="ifrmMap" src="'+g_site_path+'ajax/get-direction?zip='+zip+'&width=440&height=380" frameborder="0" height="380px" width="440px" scrolling="no"></iframe>';
		htm += '</div>';		
		popup( {event:e, width:460, height:350 } );
		ge('popupcanvas').innerHTML = htm;		
		popupresize();
	}
	
	function funtoggle() {
		var togg = $('#hiddtoggle').val();
		if (togg == '0'){
			$('#hiddtoggle').val('1');
			$('#rightpanel').hide();
			$('#displayadmin').css({ width:"960px"});
			$('#leftpanelHolder').css({ width:"960px"});
			$('#toggle').html('<span style="color:#0000FF;font-weight:bold;"><<</span>');
		}
		if(togg == '1'){
			$('#hiddtoggle').val('0');
			$('#rightpanel').show();
			$('#displayadmin').css({ width:"683px"});
			$('#leftpanelHolder').css({ width:"683px"});
			$('#toggle').html('<span style="color:#0000FF;font-weight:bold;">>></span>');
		}
	}
	
	function addEvent(obj,type,fn) {
		if(obj.addEventListener) 
			obj.addEventListener(type,fn,false);
		else if(obj.attachEvent){
			obj["e"+type+fn]=fn;
			obj[type+fn]=function(){obj["e"+type+fn](window.event);}
			obj.attachEvent("on"+type,obj[type+fn]);
		}
	}
	
	function removeEvent(obj,type,fn) {
	  	if(obj.removeEventListener) 
	  		obj.removeEventListener(type,fn,false);
	  	else if(obj.detachEvent) {
			obj.detachEvent("on"+type,obj[type+fn]);
			obj[type+fn]=null;
			obj["e"+type+fn]=null;
	  	}
	}
	
/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

	// Declaring required variables
	var digits = "0123456789";
	// non-digit characters which are allowed in phone numbers
	var phoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;
	
	function isInteger(s) {   
		var i;
		for (i = 0; i < s.length; i++) {   
			// Check that current character is number.
			var c = s.charAt(i);
			if (((c < "0") || (c > "9"))) return false;
		}
		// All characters are numbers.
		return true;
	}
	
	function stripCharsInBag(s, bag) {   
		var i;
		var returnString = "";
		// Search through string's characters one by one.
		// If character is not in bag, append to returnString.
		for (i = 0; i < s.length; i++) {   
			// Check that current character isn't whitespace.
			var c = s.charAt(i);
			if (bag.indexOf(c) == -1) returnString += c;
		}
		return returnString;
	}
	
	function checkInternationalPhone(strPhone){
		var bracket=3
		strPhone=trim(strPhone)
		if(strPhone.indexOf("+")>1) return false
		if(strPhone.indexOf("-")!=-1)bracket=bracket+1
		if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
		var brchr=strPhone.indexOf("(")
		if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
		if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
		s=stripCharsInBag(strPhone,validWorldPhoneChars);
		return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
	}
	
	function loadAdminContent(pmstr) {
		//$('#popupcanvas').html( html )	
		$.ajax({
			type : "POST",
			url	 :g_site_path+"ajax/"+pmstr+"",
			dataType: "html",
			success: function(html){	
				$('#divcontentarea').html(html);
			}
	   });
	}
	
	function embedPlayer( options ) {
		var so = new SWFObject(g_tool_path+'MPlayer.swf','mpl','738','388','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('autostart','true');
		so.addParam('flashvars','&videoPath='+options.video+'&videoTitle='+options.name+'&autostart=true&image='+options.thumb);
		so.write('app-player');				
		return;	

		var flashvars = {};
		flashvars.VideoPath = options.video;
		flashvars.VideoName = options.name;
		flashvars.autostart = true;
		flashvars.image = options.thumb;
		
		var params = {};
		params.play = "true";
		params.menu = "false";
		params.quality = "high";
		params.scale = "noscale";
		params.wmode = "opaque";
		params.bgcolor = "#869ca7";
		params.allowscriptaccess = "always";
		var attributes = {};
		attributes.align = "middle";
		alert( g_tool_path+"MPlayer.swf" )
		swfobject.embedSWF(g_tool_path+"MPlayer.swf", "app-player", "738", "388", "9.0.0", false, flashvars, params, attributes);
		//swfobject.createCSS("#app-pyp","outline:none"); 
	}
	
	function toggleCategory(obj, id){
		//alert($(obj).children().attr('src'))
		if ( $(obj).children().attr('src') == g_template_img+'icon_cat_minus.gif' ){
			$('.sub_cat_'+id).fadeOut('slow', function(){ 
													   	$(obj).children().attr('src', g_template_img+'icon_cat_plus.gif'); 
														} 
									);
		}else{
			$('.sub_cat_'+id).fadeIn('slow', function(){ 
													  	$(obj).children().attr('src', g_template_img+'icon_cat_minus.gif'); 
														} 
									);			
		}
	}
	function toggleCategory1(obj, id){
		//alert($(obj).children().attr('src'))
		if ( $(obj).children().attr('src') == g_template_img+'icon_cat_minus_1.gif' ){
			$('.sub_cat_'+id).fadeOut('slow', function(){ 
													   	$(obj).children().attr('src', g_template_img+'icon_cat_plus_1.gif'); 
														} 
									);
		}else{
			$('.sub_cat_'+id).fadeIn('slow', function(){ 
													  	$(obj).children().attr('src', g_template_img+'icon_cat_minus_1.gif'); 
														} 
									);			
		}
	}
	
	function showurl(uid,path){		
		var mediaid=$('#hdnDownloadMedia').val();
			
		if(uid==1)
			window.open('http://twitter.com/home/?status='+path+mediaid ,'_blank');
		else if(uid==2)
			window.open('http://www.facebook.com/sharer.php?u='+path+mediaid ,'_blank');
		else if(uid==3)
			window.open('http://www.stumbleupon.com/submit?url='+path+mediaid ,'_blank');
		else if(uid==4)
			window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+path+mediaid ,'_blank');
		else if(uid==5)
			window.open('http://digg.com/submit?phase=2&amp;url='+path+mediaid ,'_blank');	
	}
		
	function DownloadMedia( path ){
		if ( parseInt($('#hdnDownloadMedia').val()) > 0 ){
			window.location.href = path+'?media_id='+$('#hdnDownloadMedia').val();
		}
	}

function renderTooltip( obj, params ){
		var corners = [
					   'bottomLeft', 'bottomRight', 'bottomMiddle',
					   'topRight', 'topLeft', 'topMiddle',
					   'leftMiddle', 'leftTop', 'leftBottom',
					   'rightMiddle', 'rightBottom', 'rightTop'
					];
		var opposites = [
						   'topRight', 'topLeft', 'topMiddle',
						   'bottomLeft', 'bottomRight', 'bottomMiddle',
						   'rightMiddle', 'rightBottom', 'rightTop',
						   'leftMiddle', 'leftTop', 'leftBottom'
						];
		var i = 6;
		
		 // If counter reaches maximum, reset
        if(i === corners.length) i = 0;
         
         // Destroy currrent tooltip if present
        if($(obj).data("qtip")) $(obj).qtip("destroy");
         
        $(obj).qtip({
               content: params.text, // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: corners[i], // Use the corner...
                     target: opposites[i] // ...and opposite corner
                  }
               },
               show: {
                  when: true, // Don't specify a show event
                  ready: true // Show the tooltip when ready
               },
               hide: false, // Don't specify a hide event
               style: {
                  border: {
                     width: 1,
                     radius: 1
                  },
				  height:params.height,
				  width:params.width,
                  padding: 3, 
                  textAlign: 'left',
                  tip: true, // Give it a speech bubble tip with automatic corner detection
                  name: 'light' // Style it according to the preset 'cream' style
               }
            });
         
         //i++; // Increase the counter      
	}
	
	function hideToolTip( obj ){
		 // Destroy currrent tooltip if present
      	if($(obj).data("qtip")) $(obj).qtip("destroy");
	}