
// function used to calculate maxlength of input fields */
function maxlength(field, size) {
	if (field.value.length > size) {
		field.value = field.value.substring(0, size);
	}
}

function isNum(o) {
try{
        if(isNaN(o.value)) {
                o.value='';
                o.focus();
                return false;
        }
    } catch(err){}
}

function checkYear(Fromid,Toid) {   
    try{
	if(document.getElementById(Fromid).value!="" && document.getElementById(Toid).value!=""){
		if(document.getElementById(Fromid).value > document.getElementById(Toid).value) {
		   	jQuery("#"+Toid+"Err").show();
			return false;	
		}
		else {
			jQuery("#"+Toid+"Err").hide();			
			return true;
		}
	}
	else {
		return true;
	}
    }catch(err){}	
}

function restorePix(cont)
{

if(cont.getAttribute('imgProc') == 1)
return;
lightVer = cont.innerHTML;
richVer = lightVer.replace(/img_/gi,"img");
cont.innerHTML = richVer;
cont.setAttribute('imgProc',1);
return ;
}

// function used to call omniture click events
function omnilog(l){
	if(typeof(s_gi)!='undefined'){
	 var s=s_gi(s_account);
	 s.pageName="ibibo:myibibo:event:"+l;
	 s.channel="myibibo";
	 s.prop3="s_prop3";
	 s.t()
	} //page view model
}

function stripTags(o)
{
var st =o.value;

st=st.replace("<!--","");
st=st.replace("-->","");
st=st.replace("<","");
st=st.replace(">","");

st=st.replace(/^\s*|\s*$/,"");
st=st.replace(/\"/g,"");
st=st.replace(/\'/g,"");

o.value=st.replace(/<.*>/g, '' );
o = o.value;
o= trim(o);
}


// function used to trim spaces input fields 
function trim(u) {
	return u.replace(/^\s+|\s+$|\<.*>/g, '' );
}


function pwdBoxFocus(element, txt, incHeight){
	jQuery('#dashPassword2').hide();
	jQuery('#p').show();
	jQuery('#p').get(0).value = '';	
	jQuery('#p').focus();
}

function pwdBoxBlur(){
	jQuery('#p').hide();
	jQuery('#dashPassword2').show();
	
}


function labelBoxFocus(element, txt, incHeight){
	txt = jQuery.trim( txt );
	if( element.value == txt ){
		element.style.color = '#000';
		element.value = '';
		if( incHeight ) {
           element.style.height = incHeight + 'px';
        }	
	}
}

function labelBoxBlur(element, txt, decHeight){
	var elementVal = jQuery.trim( element.value );
	if( elementVal == '' ){
		element.style.color = '#999';
		element.value = txt;
		if( decHeight && !jQuery.browser.msie) {
			element.style.height = decHeight + 'px';
		}
	}
	
}

var iShareUrl = 'http://iinvite.ibibo.com/ff.php';
function makeUrl() {
	var ele = document.getElementById('findfr_share');
	ele.href = iShareUrl + "?usn=" +document.getElementById('usn').value + "&p=" +document.getElementById('p').value + "&s=" +document.getElementById('s').value ;
}
 
function processFindFriend(e){
	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
	if( key == 13 ) {
		jQuery('#findfr_share').trigger('click');
	}
}


 /** Search Friend **/
function fr_search(frm){
	var searchStr = jQuery.trim( frm.searchStr.value );
	if( searchStr == '' || searchStr == 'Type name' ) {
		frm.searchStr.value = 'Type name';
		return false;
	}
}


function urlencode(str) {
return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

/* function to call new notification counts[[used by dashboard as well as blurbs page]] */
function DashboardNewLink(uid)
 {
 var urlsend = '<?=base64_encode("http://feeds.ibibo.com/nfo/notification_stats.py?userid=$this->selfUId")?>';

 var correctUrl= base_url+"dashboard/fetchNotificationsCount/"+uid;
 
 jQuery.get(correctUrl,{},function(data){
 	
 //	data = '<response> <status>success</status> <userid>617a42f5-6263-4ac1-9ee8-9150c715e5b7</userid> <num_notifications>224230</num_notifications></response>';
 	numNotif = -1;
 	startTag = "<num_notifications>";
 	endTag = "</num_notifications>";
 	index1 = data.indexOf(startTag)+startTag.length;
 	index2 = data.indexOf(endTag);
 	numNotif = data.substring(index1,index2);
 	
 	 /*if(numNotif!='0')
 	   {
 		jQuery('#notificatinsLink').addClass('myTextBold');
 	   }
 	   else
 	   {
 	   	 jQuery('#notificatinsLink').removeClass('myTextBold');
 	   }*/
 	   
 		document.getElementById('NewNotificationsMsg').innerHTML=numNotif;
 		
 		 });

 }
 
 /*
function to wrap a string
*/
function wordwrap(str,strlen)
{
	//alert(str.length);
	strlen = parseInt(strlen);
	var tmp_str,i;
	var wrap_str = '';
	if(str.len < strlen)
		return str;
	else
	{
		for(i=0;i<str.length;i++)
		{
			if(i%strlen == 0)
			{
				tmp_str = str.slice(i,i+strlen);
				
				wrap_str += tmp_str;
				wrap_str += "<br/>";
			}
			
		}
		
		return wrap_str;
	}
}

/* common function for calling ajax calls */ 
   function ajaxContentLoad(urlCall , htmlDiv)
   {	jQuery.ajax({
		type: "GET",
		cache:false,
		url: base_url+urlCall,
		data: "",
		success: function(msg)
		{ if(msg!="")
		  { //alert(msg);
			jQuery('#'+htmlDiv).show();
			jQuery('#'+htmlDiv).html(msg);
			
		  }
		  try {
		   	setTimeout("setContainerHeight()",500);
		  } catch(err){
		  	// this is added to avoid throwing error in dashboard and other areas
		  }
		}
	});
			
   }
   
  /* common function for calling ajax calls for displaying static contents*/ 
	 /* common function for calling ajax calls for displaying static contents*/ 
	function ajaxStaticContentLoad(urlCall , htmlDiv)
	{	
		var sug_url = base_url+urlCall;
		var prodSugPage ='';
		var tempDetails = '';
		var jq_combo_version = '';
		jQuery.getJSON( sug_url,function(data) {
  		  jQuery.each(data, function(key, val) {
		    if(jQuery.trim(key) == "prodSugPage") {
		    	prodSugPage = val;
		    }
		    if(key == 'fbInvite') {
		    	var fbInviteStr = val;
				fb_invite_param = fbInviteStr;
		    }
			if(key == 'version') {
				jq_combo_version = val;
			}
		  });
		  switch(prodSugPage) {
			case 'fbconnect':
				var tmpStyle='style=\"height: 37px;width: 75px;\"';
				if(userType=='WU'){
					//tmpStyle='style=\"margin:5px 0 0 2px;height: 37px;width: 75px;\"';
					//tmpStyle='margin:5px 0 0 2px;"';
				}
				tempDetails +='<div class="myDashFBConCont"><div class="myFlLt" style="width:380px;padding:5px 10px;border:0px solid red;"><span style="font-size:14px; font-weight:bold;">Find your Facebook friends playing on ibibo.com</span><div class="myClearAll"></div>Link your account now</div><div class="myFlLt myPadT5px"><iframe id="kk" scrolling="no" frameborder="0" src="http://link.ibibo.com/fbfriends.php?button_img=http://static.myibibo.com/images/icons/fbfriends_btn_small.gif"></iframe></div><div class="myFlRt"><a class="gric closeFrnd" onclick="getDashboardRotation(1);" href="javascript:void(0);"></a></div><div class="myClearAll"></div></div><div class="myClearAll mySpacer15 myWBg"></div><script>function ShowFBFriends(name) {ShowFBFriendsOnMyibibo(0,"dash");}</script>';
				jQuery('#'+htmlDiv).show();
				jQuery('#'+htmlDiv).html(tempDetails);
				break;
			case 'google':
				tempDetails+='<div class="myDashFBConCont"><div class="myFlLt" style="width:380px;padding:5px 10px;border:0px solid red;"><span style="font-size:14px; font-weight:bold;">Find your Google contacts playing on ibibo.com</span><div class="myClearAll"></div>Link your account now</div><div class="myFlLt myPadT5px"><a class="myMarR5px" style="" id="openWin" href="javascript:void(0);" onclick="clearTimertime();"><img alt="Gmail Import" src="http://static.myibibo.com/images/icons/g_btn_small.gif" onclick="getDashboardGoogleFriends('+jq_combo_version+');"></a><a></div><div class="myFlRt"><a class="gric closeFrnd" href="javascript:void(0);"  onclick="getDashboardRotation(2);"></a></div><div class="myClearAll"></div></div><div class="myClearAll mySpacer15 myWBg"></div>';
				jQuery('#'+htmlDiv).html(tempDetails);
				jQuery('#'+htmlDiv).show();
				break;
			case 'education':
				tempDetails+='<div class="myProdCampusCont" ><div class="myFlLt" style="width:60px;" ><img src="http://static.myibibo.com/images/icons/campus_icon.gif"  /></div><div class="myFlLt myPadT5px myPadT5px" style="width:384px" ><h1>Find your classmates playing on ibibo.com	</h1><div class="myClearAll mySpacer5"></div><strong style="float:left">We can find them for you. Tell us your school/college name. <a href="'+base_url+'editprofile/education">Click here</a></strong></div><div class="myFlLt"><a class="gric closeFrnd" onclick="getDashboardRotation(4);" href="javascript:void(0);"></a></div><div class="myClearAll"></div></div><div class="myClearAll mySpacer15 myWBg"></div>';
				jQuery('#'+htmlDiv).html(tempDetails);
				break;
			case 'mobile':
				tempDetails+='<div class="myDashFBConCont"><div class="myFlLt" style="width:470px;padding:5px 10px;border:0px solid red;"><span style="font-size:14px; font-weight:bold;">Link your mobile &amp; start sending FREE SMS to your friends </span><div class="myClearAll"></div><a href="http://isms.ibibo.com/contact">Click here</a> to get started</div><div class="myFlLt myPadT5px"><a></div><div class="myFlLt"><a class="gric closeFrnd"  onclick="getDashboardRotation(3);" href="javascript:void(0);"></a></div><div class="myClearAll"></div></div><div class="myClearAll mySpacer15 myWBg"></div>';
				jQuery('#'+htmlDiv).html(tempDetails);
				jQuery('#'+htmlDiv).show();
				break;
			case 'photo':
				tempDetails+='<div class="myDashFBConCont"><div class="myFlLt" style="width:470px;padding:5px 10px;border:0px solid red;"><span style="font-size:14px; font-weight:bold;">Upload your real photo to your profile. It makes it easier for your friends to find you! </span><div class="myClearAll"></div><a href="http://www.ibibo.com/editprofile">Click here</a> to upload your photo</div><div class="myFlLt myPadT5px"><a></div><div class="myFlLt"><a onclick="getDashboardRotation(5);"  class="gric closeFrnd" href="javascript:void(0);"></a></div><div class="myClearAll"></div></div><div class="myClearAll mySpacer15 myWBg"></div>';
				jQuery('#'+htmlDiv).html(tempDetails);
				jQuery('#'+htmlDiv).show();
				break;
			case 'close':
				jQuery('#'+htmlDiv).hide();
				break;
			}
	});
	
	}

	function ShowFBFriendsOnMyibibo(start,pagefrom,giud){
		    jQuery.ajax({
			  type: 'POST',
			  url: base_url+'invite/getfbfriendsdetails/'+pagefrom+'/'+start+'',
			  timeout: 15000,
			  data: {"format" : 'html', 'inviteApp' :"FACEBOOK", 'nuser' : 1,'pagefrom':pagefrom,'giud':giud},
			  success: function(data){
			  	if(parseInt(data) == 2) {
			  		//changePUWidth(630);
			  		var dataMsg = '<div class="myPad10px" id="myWelHeadTxt"  ><strong>Hi '+displayName+'! </strong><br/><div class="mySpacer10 myClearAll" ></div><strong>ibibo is more fun with more friends. Invite your Facebook friends now!</strong></div><div class="mySpacer15 myClearAll"></div><div class="myPad10px"><strong>Click here -> </strong><a href="javascript:void(0);" onclick="javascript:showInviteFBFriends();"><img src="http://static.myibibo.com/images/fbconnect/fb-invite-btn.gif"></a></div>';
            		setPUBody( dataMsg );
                	setPUTitle( 'Find your friends');
                	showPU();
			/*		location.href='<?=$base_url?>welcome/show/fb/<?=$fromInvite?>/<?=$inviterUId?><?=$surlParam?>';	
			*/
			
					/*if(fbtry >= 5) {
						location.href='<?=$base_url?>welcome/show/fb/<?=$fromInvite?>/<?=$inviterUId?><?=$surlParam?>';	
					}
					else {
						fbtry++;
						FBtimeout = setTimeout("ShowFBFriendsOnMyibibo()",1000);
						//(sname);						
					}*/
				} else {
			  		//changePUWidth(630);
			  		data+='<div class="mySpacer15 myClearAll"></div><div class="myTextCenter"><a href="javascript:void(0);" onclick="showInviteFBFriends()"><img src="http://static.myibibo.com/images/fbconnect/fb-invite-btn.gif"></a></div><div class="mySpacer15 myClearAll"></div>';
			  		setPUBody( data );
            		setPUTitle( 'Facebook friends on ibibo.');
                	showPU();
                	//jQuery('#emailList').html('');
				}
				
			},
			  error: function(err){
			  }
			});
	}
	
	function showInviteFBFriends(){
		if(typeof(fb_invite_param)=='undefined')
		fb_invite_params=0;
		else
		fb_invite_params=encodeURI(fb_invite_param);
		var fbFrnds = '<iframe src="http://link.ibibo.com/fb_invite_friends.php?params='+fb_invite_params+'" scrolling="no"  frameborder="0"  height="580" width="630" ></iframe>';			
			changePUWidth(700);
			setPUTitle('');
			//setPUBody();
			setPUBody(fbFrnds);
			showPU();
	}
	
	function GetFBWall(uname,uid,next,pagefrom) {

	jQuery.ajax({
			  type: 'GET',
			  url: base_url+'welcome/getFbWall/',
			  timeout: 15000,
			  data:{"guid":uid, "uname":uname, "next":next, "pagefrom":pagefrom},
			  success: function(data){
				setPUTitle('Gift your friend a brand new Beetle!');
			  	changePUWidth(600);
			    setPUBody(data);
			    autoWidthPU();
			    showPU();
			    showPUClose();
				
			},
			  error: function(err){
			  }
			});

}

function PostFBWall(uid, uname,next,pagefrom) {
	//var songname = jQuery("#fbGiftLeft input[type='radio']:checked").val();
	var msg = jQuery('#fbmsg').val();
	/*if(songname == undefined) {
		jQuery('#fberr').text('Please choose a song to gift');
		jQuery('#fberr').removeClass('myDispNone');
		jQuery('#fberr').addClass('myDispBlock');
		return;
	}*/
	jQuery.ajax({
			  type: 'POST',
			  url: base_url+'welcome/postFbWall/dash',
			  timeout: 15000,
			  data:{"guid":uid, "uname":uname, "msg": encodeURI(msg),"next":next,"pagefrom":pagefrom},
			  beforeSend: function() {
			    jQuery('#fberr').addClass('myDispNone');
				jQuery('#fberr').removeClass('myDispBlock');
			  	jQuery('#fbldr').removeClass('myDispNone');
				jQuery('#fbldr').addClass('myDispBlock');
			  },
			  success: function(data){
				setPUTitle('Gift your friend a brand new Beetle!');
				if(parseInt(data) == -1) {
					var resp = 'Failed to send gift.Try again';
                    jQuery('#fberr').text(resp);
                    jQuery('#fberr').removeClass('myDispNone');
                    jQuery('#fberr').addClass('myDispBlock');
                    jQuery('#fbldr').addClass('myDispNone');
					jQuery('#fbldr').removeClass('myDispBlock');
					
				} else {
					setPUBody(data);
				    autoWidthPU();
					showPU();
					showPUClose();
					//hidePUDelay(3000);

				}
		},
			  error: function(err){
			       var resp = 'Failed to send gift.Try again';
				    jQuery('#fberr').text(resp);
					jQuery('#fberr').removeClass('myDispNone');
					jQuery('#fberr').addClass('myDispBlock');
					jQuery('#fbldr').addClass('myDispNone');
					jQuery('#fbldr').removeClass('myDispBlock');
			  }
			});

}
var feedsJson;
  
var feedCurrIndex =0;
var feedlastIndex = 0;
var notifyapps = new Array();
   /* common function for calling ajax calls using json obj*/ 
  function ajaxJsonLoad(urlCall)
   {	   		
   		
   		
		var templateDetails = new Array(); 
		   		
		templateDetails['vp'] = new Array();
		templateDetails['vp']['divid']='verifiedProfileContainer';
		
		var vpHeaderArray = new Array();
		vpHeaderArray[0] ='<div><div class="myRtMod"><div class="myModTitle" ><div class="myFlLt myModuleHeading myTextBold" >Celebrities on ibibo</div>';
		vpHeaderArray[1] = '';
		vpHeaderArray[2] ='<div class="myClearAll"></div></div><div >';
		
   		templateDetails['vp']['header']=vpHeaderArray.join('');
   		
   		var vpContentArray = new Array();	
   		
   		vpContentArray[0] ='<div > <div class="myFlLt myPadTB10px" id="frndBlk_#uId#" style="width:48px;padding:0px 12px 0px 5px;" ><div >';
		vpContentArray[1] ='<a href="#base_url#/#userName#" class="myTextBold" >';
		vpContentArray[2] ='<img src="#avatar_48#" alt="#displayName#" title="View profile - #displayName#" onerror="setDefAvatar(this);" width="48" height="48" border="0" /></a></div>';			
	    vpContentArray[3] ='<div ><div ><span style="color:#0066bb;">#shortName#</span></div><div >'; 
		vpContentArray[4] ='<a style="color:#333;" href="#base_url#/verifiedprofile/popular/#seocategory#" title="Verified Profiles :: #categoryName#">#shortCategory#</a></div>	';
		vpContentArray[5] ='<div class="myPadT5px"><a href="#base_url#/#userName#">Follow me</a></div></div><div class="myClearAll"></div></div>';
		//vpContentArray[6] ='<div class="myPadLR10px"><div class="myClearAll mySpacer5 myModuleBtmBrdr"></div></div></div>';   		
   		templateDetails['vp']['content']=vpContentArray.join('');
		templateDetails['vp']['footer']='</div></div></div><div class="myClearAll mySpacer15"></div><div class="myTextRight myPadR5px"><a title="View all Verified Profiles" href="#base_url#/verifiedprofile">View All</a></div>';   		
   		
   		templateDetails['wn'] = new Array();
		templateDetails['wn']['divid']='PlayandNet';
   		templateDetails['wn']['header']='';
   		templateDetails['wn']['content']='<a  href="#url#" class="myDispBlock myFlLt myWhatNewContWidth #class#" style="-margin-right:-3px;" title="#title#" >#count#&nbsp;#text#</a>';
   		
   		//templateDetails['wn']['content']='<a href="#url#" class="myDispBlock myFlLt myWhatNewContWidth" style="-margin-right:-3px; background:transparent url(#icon#) no-repeat scroll 0 3px;"  title="View all #text#" >#count#&nbsp;#text#</a>';
		templateDetails['wn']['footer']='';   	
		jQuery.ajax({
		type: "GET",
		cache:false,
		url: base_url+urlCall,
		data: "",
		success: function(msg)
		{ if(msg!="")
		  { 
			if(msg.length <=2) return;
		  	jsonData = jQuery.evalJSON(jQuery.trim(msg));
			 var finalResp='';
			 var finalCont='';
				for(var key1 in jsonData){
					if(key1 == undefined) {
						continue;
					}
					/*if(key1 == 'gn' || key1 =='nn' ) {
						break;
					}*/
					if(key1 == 'gn') {
					var wnval = jsonData['gn'];
					
					var mykey1;
					for(var mykey1 in wnval ) {
						var wnapp = wnval[mykey1].app_name;
							var wncount = wnval[mykey1].count;
							if(wnapp != undefined && wncount != undefined ) {
								notifyapps[wnapp] = wnval[mykey1];	
								jQuery('#notify_'+wnapp).text(wncount);
								jQuery('#notify_'+wnapp).removeClass('myDispNone');
							}
						}
						continue;
					}
					if(key1 == 'nn') {
						var nnval =  jsonData['nn'];
						if(parseInt(nnval) >0)
							jQuery('#notificatinsLink').html(nnval+' New notifications');
						continue;
					}
					
					if(key1 == 'feeds') {
						//feedsJson
						var showCnt =0;
						var dataToShow = "";
						if(jsonData[key1].length >0) {
							feedsJson = jsonData[key1];
							feedlastIndex = jsonData[key1].length;
							for(ii=0; ii < feedlastIndex ; ii++){
								dataToShow = dataToShow + jsonData[key1][ii] + "<div class=\"myClearAll mySpacer5\"></div>";
								showCnt = showCnt + 1;
								if(showCnt>=3){break;}
							}

							/*jQuery('#latestfeed').html(jsonData[key1][ii]);*/
							jQuery('#latestfeed').html(dataToShow);
							if(jsonData[key1].length >1) jQuery('#latestfeednav').show();
							jQuery('#midNotifCont').fadeIn(600);
						}
						continue;
					}
					if(key1 =='ib') {
						var ibval = jsonData['ib'];						
						jQuery('#ibalance').append(' : '+ibval);
						continue;
					}
					
					var respHeader = templateDetails[key1]['header'];
					var respFooter = templateDetails[key1]['footer'];
					
					for(var i = 0; i < jsonData[key1].length; i++){
						
						var value = jsonData[key1][i];
						
						var resp2;
						var replaceStr;
						var respContent =templateDetails[key1]['content'];;
						
						for(var key2 in value){			
							replaceStr = '#'+key2+'#';
							respContent =respContent.replace(eval("/"+replaceStr+"/gi"),value[key2]);
							respHeader =respHeader.replace(eval("/"+replaceStr+"/gi"),value[key2]);
							respFooter =respFooter.replace(eval("/"+replaceStr+"/gi"),value[key2]);
						}
						finalCont += respContent;							
					 }
					 	
					    var  finalResp = respHeader;
					    finalResp += finalCont;
						//finalResp += templateDetails[key1]['footer'];						
						finalResp += respFooter;						
						jQuery('#'+trim(templateDetails[key1]['divid'])).show();
						jQuery('#'+trim(templateDetails[key1]['divid'])).html(trim(finalResp));
				}
			
			
		  }
		}
	});
			
   }


/** Word wrap applicable only for plain text. It might not be accurate, if the text contains html tags **/
function _wordwrap(str,width,brkChar){

	if(!width) width = 72;
	if(!brkChar) brkChar = ' ';

        var strlen = str.length;
        if( strlen <= width ) {
                return str;
        }

        var retString = '';
        var strParts = str.split(' ');
	var totalStrParts = strParts.length;
	for(var i = 0; i < totalStrParts; i++){
                var partLen = strParts[i].length;
                if( partLen > width && strParts[i].indexOf(' ') == -1 ){
                        var currentPos = 0;
                        var temp_strParts = '';
                        while( currentPos < partLen ){
                                temp_strParts+= strParts[i].substr(currentPos,width) + brkChar;
                                currentPos+= width;
                        }
                        retString+= temp_strParts+' ';
                }
                else{
                        retString+= strParts[i]+' ';
                }
        }

        return retString;
}

/*  ends here */



// function to truncate a string.
function truncateMe(str,start,len){
if(str && str.length > len)
return str.substr(start,(len-3))+'...';

return str;
}



	// Set up my regular expressions that will match the HTML tags and attributes that I want to allow
var reAllowedAttributes = /^(face|size|style|dir|color|id|class|alignment|align|valign|rowspan|colspan|width|height|background|cellpadding|border|href|src|target|alt|title)$/i;
var reAllowedHTMLTags = /^(h1|h2|a|b|em|li|ol|p|pre|strong|ul|font|span|div|u|sub|sup|table|tbody|blockquote|tr|td)$/i;

function ParseHTML(theHTML){
// Start of with a test to match all HTML tags and a group for the tag name which we pass in as an extra parameter
theHTML = theHTML.replace(/<[/]?([^> ]+)[^>]*>/g, function(match,HTMLTag)
{
// if the HTML tag does not match our list of allowed tags return empty string which will be used as a
// a replacement for the pattern in our inital test.
if(!reAllowedHTMLTags.test(HTMLTag)){
return "";
}else{
// The HTML tag is allowed so check attributes with the tag

// Certain attributes are allowed so we do another replace statement looking for attributes and using another
// function for the replacement value.
match = match.replace(/([^=]+)="[^"]*"/g, function(match2, attributeName)
{
// If the attribute matches our list of allowed attributes we return the whole match string
// so we replace our match with itself basically allowing the attribute.
if(reAllowedAttributes.test(attributeName)){
return match2;
}else{
return match2;  // not allowed so return blank string to wipe out the attribute value pair
}
});

}
return match;

}); //end of the first replace

//return our cleaned HTML
return theHTML;
}

function addSelClass(el){
        jQuery(el).addClass('myThemeSelBg');
}

function removeSelClass(el){
        jQuery(el).removeClass('myThemeSelBg');
}


 function onChangeEmailClick( caller ) {
try { 
var prepend = '';

if( caller != "D" ) {
    prepend = 'O';
}


    var new_email = jQuery(  "#" + prepend + "strNewEMailId" ).val();

jQuery( "#"+ prepend + "errMsg" ).hide();


    var uId       = jQuery( "#" + prepend + "uId" ).val();
    var old_email = jQuery( "#" + prepend + "email" ).val();
    var prev_html = jQuery( "#" + prepend + "msgBlock" ).html();

    var pubNo = jQuery( "#" + prepend + "pubNo" ).val();
    var sec_code = jQuery( "#" + prepend + "security_code" ).val();

sec_code = trim( sec_code );
new_email = trim( new_email );

    







if( new_email == '' ) {
        // jQuery( "#msgBlock" ).html( prev_html );
        jQuery( "#" + prepend + "errMsg" ).text( "Please enter your new Email Id" );
        jQuery( "#" + prepend + "errMsg" ).show();
        jQuery( "#" + prepend + "strNewEMailId" ).focus();
        jQuery( "#"+ prepend + "strNewEMailId" ).val( ''); //select();
        return false;
    }

    // case: entered email is not a valid one
   /* var email_pattern = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
    if( !email_pattern.test( new_email ) ) {
        jQuery( "#" + prepend + "errMsg" ).show();
        jQuery( "#" + prepend + "errMsg" ).text( "Please enter an valid Email Id" );
        jQuery ( "#" + prepend + "strNewEMailId").focus();
        jQuery( "#" + prepend + "strNewEMailId" ).select();
        return false;
    }*/
    
    
	var eExp =/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	m = eExp.test(new_email);
	if(!m)
	{
		 jQuery( "#" + prepend + "errMsg" ).show();
        jQuery( "#" + prepend + "errMsg" ).text( "Please enter an valid Email Id" );
        jQuery ( "#" + prepend + "strNewEMailId").focus();
        jQuery( "#" + prepend + "strNewEMailId" ).select();
        return false;
	}
	
	
	
 // case: old email is entered
   if( new_email == old_email ) {
        jQuery( "#" + prepend + "errMsg" ).show();
        jQuery( "#" + prepend + "errMsg" ).text( "Please enter a new email Id" );
        jQuery ( "#" + prepend + "strNewEMailId").focus();
        jQuery( "#" + prepend + "strNewEMailId" ).select();
        return false;
   }

   // case: ibibo mail id is entered
   if( new_email.indexOf( "ibibo.com" ) > 1 ) {
        jQuery( "#" + prepend + "errMsg" ).show();
        jQuery( "#" + prepend + "errMsg" ).text( "You can not use your ibibo mail id. Please give some other email Id" );
        jQuery ( "#" + prepend + "strNewEMailId").focus();
        jQuery( "#" + prepend + "strNewEMailId" ).select();
        return false;

   }

  /*if( captcha_ret == 0 ) {
      jQuery( "#errMsg" ).show();
      jQuery( "#errMsg" ).text( "Please enter the correct text in the adjacent given box" );
      jQuery( "#security_code" ).focus();
      return false;
  } */

 if( sec_code == '' ) {
  jQuery( "#" + prepend + "errMsg" ).text( "Please enter the text in the adjacent box" );
        jQuery( "#" + prepend + "errMsg" ).show();
        jQuery( "#"+prepend +"security_code" ).focus();
jQuery( "#"+prepend  + "security_code" ).val( "" );
        return false;

    }


    jQuery( "#" + prepend + "errMsg" ).hide();
 // after successful validation
    jQuery( "#" + prepend + "msgBlock" ).html( '<div class="myTextCenter myPULoader" id = "divLoader" name = "divLoader"><img src="'+base_url+'images/load.gif" alt="Loader" /><br /><br /><span>Please wait - We are sending you the confirmation mail</span></div>' );

    // case: valid data, then post the data to the respective server side script
    jQuery.ajax({
        type: "POST",
        url: base_url+"emailverification/changeEmail/",
        data: "uId="+selfUId+"&email="+new_email+"&check_captcha=1&pubNo="+pubNo+"&secCode="+sec_code,
        success: function( msg ) {

            if( msg != "" && msg == 1  ) {
                msg = msg.replace( /^\s+|\s+$/g,"");
                jQuery( "#" + prepend + "msgBlock" ).html(prev_html);
                jQuery( "#" + prepend + "updateMsg" ).html ( "Please find this mail in your mailbox and click on the link in the email to verify your email id and update the same with us." );
                jQuery( "#" + prepend + "emailTBConfd" ).html ( new_email );
                  jQuery( "#" + prepend + "errMsg" ).hide();
jQuery( "#" + prepend + "strNewEMailId" ).val( '');
jQuery( "#" + prepend + "security_code" ).val( '' );
onGetDiffOne();

            }
 else {
                if( msg == 0  ) {
                jQuery( "#" + prepend + "msgBlock" ).html( prev_html );
                 jQuery( "#" + prepend + "errMsg" ).show();
                  jQuery( '#' + prepend + 'errMsg' ).text( "Sorry! Try to change your email later" );
                  return false;
}
                if( msg == -2 )  {
                 jQuery( "#" + prepend + "msgBlock" ).html( prev_html );
jQuery( "#" + prepend + "captchaImg" ).attr( "src", '' );

                 jQuery( "#"+ prepend + "errMsg" ).show();
                 jQuery( "#" + prepend + "errMsg" ).text( "Please enter the correct characters in the adjacent box" ); jQuery( "#" + prepend + "security_code" ).focus();jQuery( "#" + prepend + "security_code" ).select();
                 jQuery( "#" + prepend + "captchaImg" ).attr( "src", base_url+ "emailverification/getCaptcha/"+ Math.floor(Math.random()*1001)+  "/" + pubNo   );
                 jQuery( "#"+ prepend + "strNewEMailId" ).val( new_email );
                 return false;
                }
                if( msg == -3 ) {
                // jQuery( "#msgBlock" ).html( prev_html );
                 jQuery(  "#"+ prepend + "errMsg" ).show();
                 var err_msg  = "Please enter a valid Email Id";
                 jQuery( "#"+ prepend + "errMsg" ).html( err_msg );
                 return false;

            }
                if( msg == -1 ) {
                 jQuery( "#" + prepend + "msgBlock" ).html( prev_html );
                 jQuery( "#" + prepend + "errMsg" ).show();
                 var err_msg  = new_email + " is associated with an existing account. Please use the different one";
                 jQuery( "#" + prepend + "errMsg" ).html( err_msg );
                 return false;

            }
}
        }
    });
}
catch( err ) {

}
}

// function used to verify the captcha
function checkCaptcha( caller ) {

 var prepend = '';
if( caller != "D" ) {
    prepend = 'O';
}

  var pubNo = jQuery( "#" + prepend + "pubNo" ).val();
  var sec_code = jQuery( "#" + prepend + "security_code" ).val();
    var prev_html = jQuery( "#" + prepend + "msgBlock" ).html();

 if( sec_code == '' ) {
     var err_msg = "Please enter the correct text in the adjacent box";
    jQuery( "#"+ prepend + "msgBlock" ).html( prev_html );
    jQuery( "#" + prepend + "errMsg" ).show();
    jQuery( "#" + prepend + "errMsg" ).html( err_msg );
    jQuery( "#" + prepend + "secutiry_code" ).focus();
    return false;
 }

 else {
     // case: valid data, then post the data to the respective server side script
    jQuery.ajax({
        type: "POST",
        url: base_url+"emailverification/checkCaptcha/",
        data: "pubNo="+pubNo+"&secCode="+sec_code,
        success: function( msg ) {

            if( msg != "" && msg == 1  ) {
                return 1;
            }
            else {
               return 0;
            }
        }
    });

 }
}

function onResendConfEmailClick( caller ) {

   try { 

var prepend = "";
if( caller != "D" ) {
    prepend = 'O';
}
    var uId =  jQuery( "#" + prepend + "uId" ).val();
    var email = jQuery( "#" + prepend + "emailTBConfd" ).text( );

//jQuery ( "#email" ).val();
    var prev_html = jQuery( "#" + prepend + "msgBlock" ).html();
 jQuery( "#" + prepend + "msgBlock").html( '<div class="myTextCenter myPULoader" id = "divLoader" name = "divLoader"><img src="'+base_url+'images/load.gif" alt="Loader" /><br /><br /><span>Please wait - We are sending you the confirmation mail</span></div>' );

jQuery.ajax({
        type: "POST",
        url: base_url+"emailverification/sendEmailConfirmation/",
        data: "uId="+uId+"&email="+email,
        success: function( msg ) {
            if( msg!= "" && msg != 0 ) {
                jQuery( "#" + prepend + "msgBlock" ).html( prev_html );
                jQuery( "#" + prepend + "errMsg" ).hide();

            }
            else {
                // getPUMsg( "Sorry! Try to resend your confirmation email later", "myPUError" );
            }
        }
    });
}catch( err ) {
}
}



function onGetDiffOne( caller ) {
    try { 

        if( caller == "D" ) { 
            var pubNo = jQuery( "#pubNo" ).val();
            var img_src = base_url + "emailverification/getCaptcha/" +  Math.floor(Math.random()*1001)+  "/" + pubNo + "/1" ;
            jQuery( "#captchaImg" ).attr( "src", img_src );
        }
        else {
            var pubNo = jQuery( "#OpubNo" ).val();
            var img_src = base_url + "emailverification/getCaptcha/" +  Math.floor(Math.random()*1001)+  "/" + pubNo + "/1" ;
            jQuery( "#OcaptchaImg" ).attr( "src", img_src );

           
        }
    }catch( err ) {
    }

}

function  onVerifyClick( caller  ) {

 var prepend = '';
 
  if( caller != "D" ) {
      prepend = "O";
  }

     
  var uId =  jQuery ( "#" + prepend + "uId" ).val();
  var email = jQuery( "#" + prepend + "email" ).val();

if( caller == "D"  )  jQuery( "#verifyLnk" ).removeAttr( "onClick" );
else  jQuery( "#OverifyLnk" ).removeAttr( "onClick" );

jQuery.ajax({
        type: "POST",
        url: base_url+"emailverification/sendEmailConfirmation/",
        data: "uId="+uId+"&email="+email,
        success: function( msg ) {
            if( msg!= "" && msg != 0 ) {
                         if( jQuery( "#"+prepend + "emailTBConfd" ).text() != email ) {
                             jQuery( "#" + prepend + "emailTBConfd" ).text( email );
                         }
                        jQuery("#"+prepend + "verifyEmailBlock").slideToggle("slow");

            }
            else {
         if( jQuery( "#" + prepend + "emailTBConfd" ).text() != email ) {
                             jQuery( "#" + prepend + "emailTBConfd" ).text( email );
                         }
                jQuery( "#" + prepend + "verifyEmailBlock" ).slideToggle( "slow" );
                jQuery( "#" + prepend + "msgBlock" ).text( "Sorry! Try to resend your verification email later" );
            }
        }
    });
}

function hideVerifyEmailBlock( caller ) {
    if( caller == "D" )   { 
        jQuery( '#verifyLnk' ).bind( 'click', { call: caller }, bindVerifyClick );
        jQuery( "#verifyEmailBlock").hide("fast");
    }

    else {
       jQuery( '#OverifyLnk' ).bind( 'click', {call: caller }, bindVerifyClick );
        jQuery( "#OverifyEmailBlock").hide("fast");

    } 
}


function bindVerifyClick( event  ) {
    onVerifyClick( event.data.call );
}

var email_target_url;

// function used to render the emailverification block
function renderEmailVerificationBlock( obj, url ) {

    try{ 
var curr_url = window.location.href;
var encoded_url = encodeURIComponent( curr_url );
if( selfUId == '' ) {
  window.location.href = 'http://myaccount.ibibo.com/auth/RegistrationStart.aspx?x=&surl='+ encoded_url;
 return false;

}
	email_target_url = (url) ? url : obj.href;

        jQuery.ajax({
            type: "POST",
            url: base_url+"dashboard/renderEmailVerificationMod", 
            data: "others=1", 
            success: function( msg ) {
            if( msg != "" && msg != 0 ) {
                changePUWidth(630);
            	setPUBody( msg );
                setPUTitle( 'Verify Your Email Id');
                hidePUClose();
                showPU();
            }
            else {
                window.location.href = email_target_url;
            }
        }
    });
    
    var getCaptch = setTimeout('onGetDiffOne()', 500);
	setTimeout('clearCaptchTO()', 550);	
    
    return false;
  } catch( err ) { }
}
function sendFrRequestAutoFollow(profilename,selfUId,fruid ) {

    try{ 

if( selfUId == '' ) {
  window.location.href = 'http://myaccount.ibibo.com/auth/RegistrationStart.aspx?x=&surl='+ encoded_url;
 return false;

}
        jQuery.ajax({
            type: "POST",
            url: base_url+"friends/sendFrndRequestWithAutoFollow", 
            data: "frndUId="+fruid+"", 
            success: function( msg ) {
           	if( msg == 1 ) {
                setPUTitle( 'Friendship request');
                content='<div>Friendship request sent successfully</div>';
                content+= '<div style="float:left;padding:10px 0px 0px 0px;"><input id="statusFirstForward" class="myTextCenter myPUSubmit myTextBold myCursor" style="padding:3px 6px;float:right;margin-right:10px" type="button" onclick="hideFrndBlock(\''+profilename+'\')" value = "OK" /></div>';
            	showPU();
                getPUMsg( escape(content), 'myPUFriend');
            }
            else {
                setPUTitle( 'Friendship request');
                content='Friendship request not sent';
                showPU();
                getPUMsg( escape(content), 'myPUFriend');
                hidePUDelay(4000);
             
            }
        }
    });
    
  } catch( err ) { }
}
function hideFrndBlock(profilename){
	try{
	location.href = base_url+profilename;
	}catch(err){}

}

function clearCaptchTO(){ clearTimeout(getCaptch); }

function onSkipNow() {
   hidePU();
   window.location.href = email_target_url; 
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


/// Declare variable required for phone validation
// 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 checkPhoneNumber(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 setDefAvatar(elm){ elm.src="http://static.myibibo.com/images/default_avatar_48.gif"; }

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)+ ";expires=''";
                 
// alert(document.cookie);;
}

/* common function for calling ajax calls */ 
function delinkGmail()
   {	jQuery.ajax({
		type: "POST",
		url: base_url+"settings/delinkGmail",
		data: "",
		success: function(msg)
		{ 
			jQuery('#openGmail').show();
			jQuery('#successGmail').hide();
			
		}
	});
			
   }
  //function used to add carnival redFM code 
   function addCarnivalFMCode()
   {	
   	var fmcode =  jQuery ( "#fmCode" ).val();
   	
   	if(fmcode==''){
   		return false;
   	}
   	jQuery.ajax({
		type: "POST",
		url: base_url+"carnival/addCarnivalFMCode",
		 data: "fmcode="+fmcode,
		success: function(msg)
		{ 
			
			jQuery('#fmdiv').html('Successfully updated!');
			
		}
	});
			
   }
   
   function showGameInviteBlock(ids,shareid){

   	document.getElementById("ginvite_"+shareid).style.display = "";
   	jQuery('#onemore_'+shareid).remove();
   }
   function gameInviteAccept(userId,shareid,target_url){
   		jQuery.ajax({
		type: "POST",
		url: base_url+"invite/accept",
		 data: "shareid="+shareid+"&userId="+userId,
		success: function(msg)
		{ 
			window.location.href =target_url;
		
		}
	});
   }
   function gameInviteIgnore(userId,shareid,id,gameTotalCount){
   		jQuery.ajax({
		type: "POST",
		url: base_url+"invite/ignore",
		 data: "shareid="+shareid+"&userId="+userId+"&id="+id,
		success: function(msg)
		{ 
			jQuery('#ginvite_'+shareid+'_'+id+'').remove();
			jQuery('#ginvite_'+shareid+'').show();
			gameTotalCount=jQuery( '#totCount_'+shareid+'' ).val();
			
			var x = parseInt(gameTotalCount-1);
			jQuery('#totInv_'+shareid+'').html(''+x+'');
			jQuery( '#totCount_'+shareid+'' ).val(x);
			if(x == 1 || x==0){
			jQuery('#onemore_'+shareid).remove();
			if(x==0){
			jQuery('#gametitle_'+shareid).remove();
			jQuery('#hrruler_'+shareid).removeClass('myModuleBtmBrdr');
			}
			
			}
	
		}
	});
   }
   
   
// stats to show how many clicks on aircelmusic connect link
function getAircelSiteClicks()
{
	jQuery.ajax({
		type: "POST",
		url: base_url + "dashboard/getSiteClicks",
		data: {},
		success:function( msg ) {

		}});

}

// stats to show how many clicks on aircelmusic facebook share link
function getAircelfbshareClicks()
{
	jQuery.ajax({
		type: "POST",
		url: base_url + "dashboard/getfbShareClicks",
		data: {},
		success:function( msg ) {

		}});

}

function sendFrndRequest(profilename,selfUId,fruid,respCont) {

    try{ 

if( selfUId == '' ) {
  window.location.href = 'http://myaccount.ibibo.com/auth/RegistrationStart.aspx?x=&surl='+ encoded_url;
 return false;

}
        jQuery.ajax({
            type: "POST",
            url: base_url+"friends/sendFrndRequestWithAutoFollow", 
            data: "frndUId="+fruid+"", 
            success: function( msg ) {
           	if( msg == 1 ) {
           		
           		jQuery('#'+respCont).html('Friendship request sent');
           	
                
            }
           
        }
    });
    
  } catch( err ) { }
}

function skipFbFriendsBlock(){
	hidePU();
}

function getSuggestedByNames(u1Uid,u2Uid){
	
	getPULoader( "Please wait ..." );
	

	jQuery.ajax({
			type: "GET",			
			url: base_url+"friends/getSuggestedByUserPopUp/"+u1Uid+"/"+u2Uid,
			success: function(msg)
			{ 
				if(msg!='0'){				
			
				setPUBody(msg);					
				setPUTitle('');				
				showPU();
			   }			
			
			}
	  });
}

function getDashboardGoogleFriends(ver){
	if(ver == undefined || ver == '') {
		var dt = new Date();
		var ver = dt.getTime();
	}
	jQuery.getScript('http://static1.ibcdn.com/my/js/jquery_combo.'+ver+'.js', function () {
		jQuery.getScript(base_url+'dashboard/getRotator', function () {
			jQuery('#openWin').click();
		});
		
	});
}

function getDashboardRotation(nextid){
	if(nextid == undefined) nextid = 0;
	if(navigator.appName=='Microsoft Internet Explorer'){
		setTimeout(function(){ajaxStaticContentLoad('dashboard/getDashboardMinifiedProdSugg/'+nextid , 'prodSuggestions');},1000);
	} else {
		ajaxStaticContentLoad('dashboard/getDashboardMinifiedProdSugg/'+nextid , 'prodSuggestions');
	}

}
function moveLatestFeed(pos) {
        try {
			feedCurrIndex = feedCurrIndex + pos;
	        if (feedCurrIndex > feedlastIndex) {
	          feedCurrIndex = 0;
	        } else if (feedCurrIndex < 0) {
	          feedCurrIndex = feedlastIndex;
	        }
	        if(feedsJson.length > 0) {
				jQuery('#latestfeed').html(feedsJson[feedCurrIndex]);
	        }
        } catch(e) {
        	
        }
        return false;
      }
function notifyLayer(myurl, myapp) {
	
	if(myurl == undefined) return false;
	if(myapp == undefined) myapp = '';
	var mynotify = notifyapps[myapp];
	if(mynotify == undefined) {
		window.location.href = myurl;
		return false;
	}
	if(mynotify == '') {
		window.location.href = myurl;
		return false;
	}	
	var myNoitfyContent = '<div><div class="myPadB10px"><img height="20" width="20" src="'+ mynotify.icon+'" />&nbsp;'+mynotify.count+ '&nbsp;'+mynotify.text+'</div><div class="myTextRight"><a href=\''+mynotify.url+'\'" >Go to Application &gt;&gt;</a></div></div>';
	jQuery('#myNotifLayer').html(myNoitfyContent);
	var myTipTop = jQuery('#notify_'+myapp).offset().top;
	//var myTipLeft = jQuery('#notify_'+myapp).offset().left;
	var myTipLeft =  document.getElementById('notify_'+myapp).offsetLeft;
	//alert(myTipTop+'     '+myTipLeft);
	jQuery('#myNotifCont').css({'left':myTipLeft-11+'px', 'top':myTipTop-167+'px'});	
	jQuery('#myNotifCont').show();		
}



