statArray=['unpublished','apply for','unconfirmed','confirmed','cancelled'];

function dSub(fid,def){
	if($('#'+fid+' input[name=s]').val()==def){
		$('#'+fid+' input[name=s]').val('')
	}; 
	$('#searchForm').submit();
}

function removeComment(id){
	disable();
	$.post("removeComment.php",{id:id},
  	function(data){
	if(data.length<1)	{$('#com'+id).hide();	}else{$.prompt(data);}
	enable();
});}

function flash(){
	if(typeof(opa)=='undefined'){opa=100;}
	if(opa<20){dir='up';}else if(opa>90){dir='down';}
	opa=(dir=='down')?(opa-10):(opa+10);
	$('#flasher').css('opacity',(opa/100));
	$('#flasher').css('filter','alpha(opacity='+opa+')');
	setTimeout(flash,150);
}	
$(document).ready(function(){
//	if(typeof(agid)=='number'){setAGB(agid);}
	globtim=0;

	$.preloadCssImages();
	$(".cnr").corner('6px');
	if(sessMess.length>0){$.prompt(unescape(sessMess),{buttons:''});}
	
	$('.scst').click(function(){
		var scid=$(this).attr('id').replace('myr','').split('-');
		
		disable();
		
		$.post("ratingchange.php",{id:scid[1],rating:scid[0]},
  		function(data){
			if(data.length<1)	{
				for(var i=1; i<=5; i++){
					if(i<=scid[0]){var st='Act';}else{var st='Pas';} 
					$('#myr'+i+'-'+scid[1]+' img').attr('src','images/star'+st+'.gif');
				} 
			}else{$.prompt(data);}
		});
		enable();
		return false;	
	});
	
	$(".lnk").corner('6px');
	transy=new Array;
	var i=0;
	$('.transparentText').each(function(){transy[transy.length]=$(this).height()});
	$('.transparent').each(	function(){	$(this).height(transy[i]+'px');	i++;	});

	blob=new Array;
	var i=0;
	$('.blob').each(function(){blob[blob.length]=$(this).position()});
	$('.blobText').each(	function(){	$(this).css('top',(blob[i].top+13)+'px');	i++;	});

	blob=new Array;
	var i=0;
	$('.tagText').each(function(){blob[blob.length]=$(this).width()});
	$('.tag').each(	function(){	$(this).width(blob[i]+'px');	i++;	});
	
	$('ul').hover(function(){	$(this).addClass('hover')},function(){	$(this).removeClass('hover')});
	$('.gigTbl').hover(function(){	$(this).addClass('hover')},function(){	$(this).removeClass('hover')});

	/*$('.squ').hover(function() {
		if(globtim>0){return false; }
		globtim=1;
		$(".squ").css('z-index',1);
		$(this).css('z-index',100);
		$(this).animate({
    		width: '158',
			left:'2'
		}, 500, function() {});		
	});
	
	$('.squ').mouseout(function() {
			$(this).css('z-index',99);
			setTimeout("globtim=0; $(this).css('z-index',1); 	",500);
			var position=$(this).prev(".squ").position();
			if(position){
				var pos=(position.left-32);
			}else{var pos=130;}
			
			$(this).animate({
    		width: '30',
			left:pos
    	}, 500, function() {});
     });*/

	$('#commentBtn').click(function(){
		if($("#commentBox").height()>0){	
			$("#commentBox").animate({height:'0px'},300);
			return false;
		}
		$("#commentBox").animate({height:'136px'},300);
		return false;	
	});
	
	$("#commentClose").click(function(){
	  	$("#commentBox").animate({height:'0px'},300);
		return false;
	});
	
	$("#commentSubmitBtn").click(function(){ 
		var idt=$("#commentVars").val().split('-');	
		if($('#com').val()==''){$.prompt('you need to write something into the comment box'); return false;}
		disable();
		$.post("leave_comment_process.php",{id:idt[0],t:idt[1],comment:$('#com').val()},
		function(data){
			if(data.length<1)	{
				
				
					
				$("#commentList").prepend('<div class="col3 nomar com">'+aBox([activeuserid,decodeURIComponent(activeuser),activeimgid],'s','')+'<b>Just Now FROM:</b>'+decodeURIComponent(activeuser)+'<br />'+$('#com').val()+'</div>');
				
				//$("#commentList").prepend('banab');
				$("#commentBox").animate({height:'0px'},300);
				$("#com").val('');
			}else{$.prompt(data);}
		});
		enable();	
	});

	$('.Qmark').click(function(){
		$('#dynMsg').show();
		
		var pos=$(this).offset();
	//	alert(this.title+' '+pos.top+' '+pos.left);
		
		switch(this.title){
			case 'extension': var msg='This is used as a navigation aid to find your profile. For example, if you enter alfred, anyone looking for your page would type www.musicborn.com/alfred into their browser address bar. <br /><br />All extensions must be unique, you can not use the same for your band and member profiles.';break;	
			case 'postcode': var msg='Entering a postcode is optional, but if you don\'t enter one and people search our directories by location, your profile will not be shown in the results.<br/><br/> If you are worried about entering your full postcode, just tell us the first part.';break;	
			case 'catchphrase':var msg='Write a few words or a quote which will appear next to your entry in gig listings and in our directories.';
			case 'images':var msg='Minimum image width is 328px  and minimum height is 246px. JPG, GIF or PNG preferred<br /><br /> Free image resizing program is <a href="http://www.irfanview.com/" class="red" target="new">Irfan View</a> (PC)';
			case 'fbpgid':var msg='This will be necessary if you want to use our Facebook App to display the gigs you have listed with Musicborn on your Facebook page.<br /><br />If you would like to do this but don\'t know how, Go to Facebook and search for the musicborn gigs app. When you\'ve installed that, you will be given some setup instructions which will include information containing your Facebook page ID and how to use it.';
}
		$('#dynMsg').css({top:(pos.top-0)+'px',left:(pos.left-280)+'px'});
		var top='<a href="#" onclick="$(\'#dynMsg\').hide(); return false;"><img src="images/dynMsgClose.png" style="position:absolute; top:2px; right:2px;"/></a>'+
		'<b style="line-height:24px;">'+this.title.toUpperCase()+'</b><br/><br/>';
		$('#dynMsg').html(top+msg);
		
		return false;
	});
	
	$('.pBoxList').click(function(){
		$('#stdBox').show();		
		var pos=$(this).offset();
		//$('#stdBox').css({top:(pos.top-0)+'px',left:(pos.left-230)+'px'});
		return false;
	});
	
}); 





   function mktime() {  
        // Get UNIX timestamp for a date    
        //   
        // version: 901.2514  
       // discuss at: http://phpjs.org/functions/mktime  
        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
        // +   improved by: baris ozdil  
        // +      input by: gabriel paderni   
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
       // +   improved by: FGFEmperor  
       // +      input by: Yannoo  
       // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
       // +      input by: jakes  
       // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
       // +   bugfixed by: Marc Palau  
       // *     example 1: mktime(14, 10, 2, 2, 1, 2008);  
       // *     returns 1: 1201871402  
       // *     example 2: mktime(0, 0, 0, 0, 1, 2008);  
       // *     returns 2: 1196463600  
       // *     example 3: make = mktime();  
       // *     example 3: td = new Date();  
       // *     example 3: real = Math.floor(td.getTime()/1000);  
       // *     example 3: diff = (real - make);  
       // *     results 3: diff < 5  
       // *     example 4: mktime(0, 0, 0, 13, 1, 1997)  
       // *     returns 4: 883609200  
      // *     example 5: mktime(0, 0, 0, 1, 1, 1998)  
       // *     returns 5: 883609200  
       // *     example 6: mktime(0, 0, 0, 1, 1, 98)  
       // *     returns 6: 883609200  
         
       var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;  
     
       if (argc > 0){  
           d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);  
       }  
     
      var dateManip = {  
          0: function(tt){ return d.setHours(tt); },  
           1: function(tt){ return d.setMinutes(tt); },  
           2: function(tt){ var set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },  
           3: function(tt){ var set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },  
           4: function(tt){ return d.setDate(tt+mb); },  
           5: function(tt){ return d.setYear(tt+ma); }  
       };  
         
       for( i = 0; i < argc; i++ ){  
           no = parseInt(argv[i]*1);  
           if (isNaN(no)) {  
               return false;  
           } else {  
               // arg is number, let's manipulate date object  
               if(!dateManip[i](no)){  
                   // failed  
                   return false;  
               }  
           }  
       }  
     
       return Math.floor(d.getTime()/1000);  
   }  
function dateSelect(datename, defaul, dir, inf){ 
	var dows=['sun','mon','tues','wed','thurs','fri','sat'];
	var mons=['jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec'];
	var e='';
	var t='<select name="'+datename+'" id="'+datename+'" class="sel">';
    if(defaul=='blank'){t+='<option value="inf" selected="selected" >select</option>';}

	var d = new Date();
	var e=new Date();
	for (var i = 0; i <= 365; i++) {

	   if(dir=='past'){e.setDate(d.getDate()-i);	}
		else if(dir=='future'){e.setDate(d.getDate()+i);}
		else{alert('no type in date'); }
	
		var option=dows[e.getDay()]+' '+mons[e.getMonth()]+' '+e.getDate()+', '+e.getFullYear();
		if(defaul=='now'){defaul=e.getFullYear()+'-'+(e.getMonth()+1)+'-'+e.getDate();}	
	
        var value=e.getFullYear()+'-'+leadZero((e.getMonth()+1),2)+'-'+leadZero(e.getDate(),2);

if (e.getDay()==0)        {    t+'<option disabled="disabled" >&nbsp;</option>';      }
		
        if ((value == defaul)&&(defaul!='blank')) {       var selected='selected="selected" ';} 
		else                    {      selected='';        }
		
     	t+='<option value="'+value+'" '+selected+' >'+option+'</option>';    
		

}	

if(inf=='on'){t+='<option value="inf"'; if(defaul=='inf'){t+='selected="selected"';} t+='>Forever</option>'; }
	t+='</select>';

return t;

}









function leadZero(n, totalDigits) { 
        n = n.toString(); 
        var pd='';;
        if (totalDigits > n.length) 
        { 
            for (var i=0; i < (totalDigits-n.length); i++) 
            { 
                pd += '0'; 
            } 
        } 
        return pd + n.toString(); 
    } 
	
function dirCheck(tyid,checked,lk){
	ty=proty[tyid].replace('_',' ');
	if(checked){var tr=false;}else{var tr=true;}
	if(!checked){
		var response = window.confirm("Are you sure you want to remove yourself from this directory? Doing so will erase all of your "+ty+" ratings, and your "+ty+" information");
		if (!response) { $('.dir'+tyid).attr('checked', tr); return false;}
	}
	disable();
	$.post("directoryCheck.php",{tyid:tyid,checked:checked,lk:lk},
	function(data){
		if(data.length<1)	{
			var sPath = window.location.pathname;
			var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
			if(sPage=='profileEdit.php'){
				window.location.reload();
			}else{
				$('.dir'+tyid).attr('checked', checked);
				if(checked){$.prompt('Action sucessful. You will now appear in the '+ty+' directory, and there is a new area on your member profile where you can leave some info about your role as a '+ty+'. To enter the information, go to "<a href="diraded.php?id='+activeuserid+'#'+proty[tyid]+'">Edit Details</a>" of your member profile which is available via dashboard.');
				}else{$.prompt('You have been removed from the '+ty+' directory',{timeout:2000});}
			}
		}else{$('.dir'+tyid).attr('checked', tr); $.prompt(data);}
		enable();
});}


function aSk(type,e){
	if(typeof(e)=="string"){ e=unescape(e);	 if(e.substring(0,1)=='{'){e=$.evalJSON(e);}else{e=getFields(e);}}		
//alert('aSk '+type+'-'+$.toJSON(e));
	$.post(type+".php",e,
	function(data){
	
	if(!isNumeric(data) && data.substring(0,1)!="{"){
		$.prompt(data,{buttons:{}});
		return false;
	}
	
	if(data.length>0){data=$.evalJSON(data);}
	if(data['error']){
		$.prompt(html_entity_decode(data['error'])+'<br>'+type); 
		return false;
	}
	jQuery.prompt.close();
	
	
	
	switch(type){
case "rq_newspublish": 			$.prompt("The news has been published to your news feed",{timeout:1000});	
								$('#boxrequest'+e['id']).css('display','none'); 		break;
case "admin/addBirthdayPro"		:
case "admin/ideasWritePro": 	$.prompt("Idea Submitted, refresh page an it will be displayed",{timeout:1500});									break;	//WORKS		
case "admin/recommendaband":	runRecommendations(); break;
case "admin/hpArtistBannerPro": setTimeout('window.location.reload();',800); $.prompt("Banner Added",{timeout:1000});	break;
case "memberRolePro"				: window.location.reload();break;
case "checkCur"				: 	
case "admin/addAdPro"				: 	break;
case "evperm" :$.prompt("Permission Requested",{timeout:1000});	break;
/*case "sound_engineerConfirm":	$.prompt("Sound Engineer Confirmed.",{timeout:1000});	
								$('#req'+e['rqId']).css('display','none'); 										break;*/
case "rq_gig2_2": 				$('#boxrequest'+e['id']).css('display','none');
								$.prompt("Request Sent.",{timeout:1000});									break;
case "rq_gig3":  				$('#boxrequest'+e['id']).css('display','none');
								$.prompt("An unconfirmed gig has been posted pending approval by the organiser.",{timeout:1000});							break;	//WORKS	
case "rq_gig1_2":  				$.prompt("A request has been sent to the relevant profiles.",{timeout:1200});	break;	//WORKS
//case "notifyAttendeesPro":		$.prompt('Notification Sent',{timeout:1000});									break;	//WORKS
case "requestReplyProcess": 	$.prompt("Action Successful",{timeout:1000});	checkCuteyRem();	break;	//checkstockonly for request decline page		
//case "gigsWallWritePro": 		$.prompt("Action Successful",{timeout:1000});									break;	//WORKS		
case "reportClosure":			$.prompt("Thanks, we'll look into the status of this company and remove the profile if it appears that they are no longer in business",{timeout:3000});break;	
case "sendLoginPro"	:			$.prompt('You Have Email',{timeout:1000});										break;
case"VPinvite":					setTimeout('window.location.reload();',800);$.prompt('A request has been sent'); break;
case"VPdel": 					$("#r"+e['id']).css('display','none'); $.prompt('Promoter to venue assosiation has been removed',{timeout:1000}); break;
case"rq_vpinvite":
case"eventInvitePro":
case"applyToPlay":		 aSk("requestReply",data); break;	//WORKS
case"rq_applyconfirm":	
case "rq_gig2_3":
case"rq_meminvite":
case"rq_joingroup":	
case"rq_contact":
case"rq_gig4_p":
case"rq_gig4_o":
case"rq_evperm":
case"claimGigApprove":		$('#boxrequest'+e['id']).css('display','none'); 
							if(!isNaN(data['rqid']) || !isNaN(data['rid'])){aSk("requestReply",data);}else{$.prompt('action successful.')} break;	//WORKS
case"hidInvite": $.prompt(data['name']+' has been added to the conversation.',{timeout:2000}); $('#between').append(', '+data['name']);break;

case "rq_addtocal": 			$.prompt("The Event has been added to your calendar",{timeout:800});	
								$('#boxrequest'+e['id']).css('display','none'); 
//								alert($.toJSON(data));
								setTimeout("aSk('eventInvite',"+$.toJSON(data)+");",1000);		break;
								//aSk('eventInvite',data);													break;
case "eventInvite":			aSk('eventInvitePro',data);													break;
case "cloneDate":				$.prompt("Event Cloned",{timeout:500});		break;

case "myCalCreate":  			alert('function del');aSk('eventInvite',data);													break;
case "contactAdd":				$("#incontacts").html("<a class=\"lnk\">Contact Requested</a>");	
								aSk("requestReply",data);													break;	//WORKS
case "contactRemove":			$("#incontacts").html("<a class=\"lnk\">Contact Removed</a>"); $.prompt('Contact has been removed',{timeout:1000});
								$("#r"+e['id']).css('display','none'); 
								enable();																	break;	//WORKS
case "claimGigRequest":			$('#cl'+e['gid']).css('display','none'); 
								aSk("requestReply",data); 													break;	//WORKS
case "newslistAdd": 			$("#innewslist").html('<a href=\'#\'onclick=\'aSk("newslistRemove",'+$.toJSON(e)+');  return false;\' class=\'lnk\'>Remove from News</a>');	
								enable();																	break;//WORKS	
case "newslistRemove": 			$("#innewslist").html('<a href=\'#\' onclick=\'aSk("newslistAdd",'+$.toJSON(e)+');  return false;\'  class=\'lnk\'>Add to News List</a>');	
								enable();																	break;//WORKS	
case "gigs_PofV":				//alert(type+''+e+'PofV'+$.toJSON(data));
//aSk(data['tyid']); var tyo=(data.tyid==3)?organiser 
aSk("gigs_post_listFromName",{"name":"","type":"organiser","epid":0});								enable();								 									break;//very clever function, if retrows <1 dont disaply page, just send var back
case "gigs_VofP":				//alert(type+''+e+'VofP'+$.toJSON(data));aSk(data['tyid']);  
aSk("gigs_post_listFromName",{"name":"","type":"eventhost","epid":0});								enable();								 									break;//very clever function, if retrows <1 dont disaply page, just send var back

								enable();								 									break;
case "gigsMyGroups" :			 setPoster(data);													break;
case "gigsMakeVenuePro"	:		set(data['id'],data['name'],data['tyid']); 									break;
case "cancelHid" :				if(typeof(e['date[]'])=='string'){$('#ev'+e['date[]']).hide();}else{for(var i=0; i<e['date[]'].length; i++){$('#ev'+e['date[]'][i]).hide();}}
								$.prompt("Event Cancelled",{timeout:1000}); break;

default:   					alert('default shouldnt see this make the function inside erMsg to handle this TYPE - '+type);

//very clever function, if retrows <1 dont disaply page, just send var back
//CHECK STOICK AND CUTEYREM STOP ERMSG AS PAGE RELOADS. HOW STOP THIS
//}
return true;
	}});
}	


function parse_date(
	timestamp) {  
	if(timestamp.length==10){timestamp+=' 00:00:00'}
    var date = new Date();  
    var parts = String(timestamp).split(/[- :]/);  
    date.setFullYear(parts[0]);  
    date.setMonth(parts[1] - 1);  
    date.setDate(parts[2]);  
    date.setHours(parts[3]);  
    date.setMinutes(parts[4]);  
	date.setSeconds(parts[5]);  
    date.setMilliseconds(0);  
   	return date;  
}  


function mysqlJsDate(timestamp) {
	if(timestamp.length==10){timestamp+=' 00:00:00'}
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
  

function clearUp(tagId) {var f=$('#'+tagId).html($('#'+tagId).html());} 

  
function stripHTML(oldString) {
	var newString = "";
	var inTag = false;
	for(var i = 0; i < oldString.length; i++) {
		if(oldString.charAt(i) == '<') inTag = true;
		if(oldString.charAt(i) == '>') {
           	if(oldString.charAt(i+1)=="<"){
           		//dont do anything
			}else{
				inTag = false;
				i++;
			}
        }
 		if(!inTag) newString += oldString.charAt(i);
   	}
   return newString;
}


function delProfile(id){
	var response = window.confirm("Are you sure you want to remove this profile?");
	if (response) {
	disable();
	$.post("admin/manageDelProfile.php",{id:id},
  	function(data){
	if(data.length<1){
		window.location=document.referrer;
		/*
		var sPath = window.location.pathname;
		//var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
		var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
		
		if(sPage=='profileEdit.php'){	window.location="admin/accountmanager.php";}
		else{$('#d'+id).css('display','none');}*/
	}else{$.prompt(data);}
	enable();
});}}
	




//function checkFunctions(){}


function runAds(){
	//ads=$.evalJSON(theAds);
//alert('kkk');
var b=new Array();

	$(".cleverAdBox").each(		
	function(i){
		b[i]=new Array();
		
		var parentId = $(this).parent().get(0).id;
		var h=$("#"+parentId).height();
		var pos = $(this).position();
		//alert($("#"+parentId).nextAll('.clear').id());
		var clear=$("#"+parentId).nextAll('.clear').position();
		
		b[i][0]=$(this).width();
		b[i][1]=(clear.top-pos.top-15);
	});

	$(".hidAd").each(		
	function(){
		if(typeof(c)=='undefined'){var c=b.length;}
		b[c]=new Array();
		b[c][0]=$(this).width();
		b[c][1]=$(this).height();
		c++;
	});

	//alert(b[1][0])
	$.post("adsRetrieve.php",{'theAds':theAds,'dim':$.toJSON(b)},
	function(data){
		//alert(data);
		//if(!isNumeric(data) && data.substring(0,1)!="{"){





if(data.substring(0,1)!="[" && data.substring(0,1)!="{"){
		//$.prompt('pre inside runads'+data,{buttons:{}});
		return false;
		}else{
		//alert(data);
		data=$.evalJSON(data);
		
		c=0;
$(".cleverAdBox").each(		
	function(i){
		$(this).html(data[i]+'<br/><br/>');
	c++;
	});
$(".hidAd").each(		
	function(i){
		$(this).html(data[c]+'<br/><br/>');
	c++;
	});
		//alert(data[i]);
		}
		
	});

/*	
	
	if(typeof(ads)!='object'){return false;}
	
	var adColumn=new Array();
	var box=new Array();
	
$(".cleverAdBox").each(		
	function(i){
		adColumn[(i+1)]=new Array();
		var parentId = $(this).parent().get(0).id;
		var h=$("#"+parentId).height();
		var pos = $(this).position();
		var clear=$("#"+parentId).nextAll('.clear').position();
		adColumn[(i+1)]['adW']=$(this).width();
		adColumn[(i+1)]['adH']=(clear.top-pos.top-15);
		$(this).css("height",adColumn[(i+1)]['adH']);
		adColumn[(i+1)]['this']=this;
		$(adColumn[(i+1)]['this']).html(adColumn[(i+1)]['adH']+'<br/>');
	});

	var col=1;	
	var i=0;
	var strikeNo=1;
	var end=0;

	while(end<1){
		bw=adColumn[col]['adW'];
		bh=adColumn[col]['adH'];
		aw=ads[i][0];
		ah=ads[i][1];
		//alert(ads[i][3]+' '+aw+'x'+ah+' st-'+strikeNo)
		if(bh>ah && (aw<=bw && aw> (bw-100) )){
			$(adColumn[col]['this']).html($(adColumn[col]['this']).html()+decodeURIComponent(ads[i][2])+'<br /><br />');
			adColumn[col]['adH']=(bh-ah-20);			
			strikeNo=1;
			i++;
		}else{
			//$(adColumn[col]['this']).html($(adColumn[col]['this']).html()+'<br />'+ads[i][3]+' ad-'+aw+'x'+ah+' i='+i+'<br />box'+bw+'x'+bh+' i='+i+'<br />');
			strikeNo++;
		}
		if(strikeNo>=adColumn.length){i++;strikeNo=1;}
		col++;
	if(i==ads.length){end++;}
	if(col==adColumn.length){ col=1;}	}	
*/
}



profileTypes=proty;

function checkCuteyRem(){if(typeof(cuteyRem)=='number'){cuteyRem--;	checkstock();}}
function checkstock(){	if(cuteyRem<2){ jQuery.prompt.close(); window.location.reload();}else{enable();}}
function addslashes(str) {str=str.replace(/\'/g,'\\\'');str=str.replace(/\"/g,'\\"');str=str.replace(/\\/g,'\\\\');str=str.replace(/\0/g,'\\0');return str;}
function stripslashes(str) {str=str.replace(/\\'/g,'\'');str=str.replace(/\\"/g,'"');str=str.replace(/\\\\/g,'\\');str=str.replace(/\\0/g,'\0');return str;}
function ucwords(str){return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );}
function highlight(str,key) {var words=str.split(' ');var out='';for (var b=0; b<words.length; b++){if(words[b].replace (/[\.\,\?!\s]/g, "").toLowerCase() ==key.toLowerCase() ){out+="<b  class='red'>"+words[b]+'</b> ';}else{out+=words[b]+' ';}}return out;}
function page(){if(document.forms['searchForm'] && document.forms['searchForm'].elements['pagenum']){document.forms['searchForm'].elements['pagenum'].value=1;}}
function ret(i,ret){if ((i % ret == 0) && (i>0)) {return'<div class="clear"></div>';}else{return "";}}


function addTableRow(jQtable,e){
	var table = document.getElementById(jQtable);
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	for(var i in e){
    	var cell1 = row.insertCell(i);
		cell1.innerHTML=e[i];
    }
}

function nl2br (str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}


	
function aBox(array,size,nomar){
	var id=array[0];
	var name=array[1];
	var imgid=array[2];

	if(id>0 ){var pg='<a href="profile.php?id='+id+'" target="_parent">'; var pg2='</a>';}	else{var pg=''; var pg2='';}
	var l='<div class="aBox '+size+' '+nomar+'"><div class="img">'+pg+'<img src="ups/'+size+'/'+imgid+'.jpg"  alt="'+escape(name)+'" />'+pg2+'</div>'+pg+'<b>'+name+'</b>'+pg2+'</div>';
	return l;
}


function subGenre(){
	var genSel=document.getElementById("genre");
	var subSel=document.getElementById("sub_genre");
	var genre=genSel.value;
	var sub_genre=subSel.value;
	subSel.options.length=0;
	if(genSel.value!=''){
		$(".genTd").css("visibility","visible");
		$.post("sub_genres.php",{o:genSel.value},
  		function(data){
		var a=$.evalJSON(data); 
		if(a.length>0)	{
			subSel.options[0] = new Option('select',"0",false,true);
			for (r=0; r<a.length;r++){
				
				if(sub_genre==a[r]["id"]){		var b=true	}else{var b=false} 
				subSel.options[(r+1)] = new Option(a[r]["sub_genre"],a[r]["id"],false,b); 
			}		
			enable();
		}else{subSel.options[0] = new Option('No Options',0,false,true);  }			
		});
	}else{
		$(".genTd").css("visibility","hidden");
		subSel.value=''; 
	}
}

function in_array(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;
}



function getFields(form){
	o= new Object;
	var f=document.forms[form];
	//if(!f){	var f=$("jqi").document.forms[form];}
	if(!f){alert("no f"); return false;}
	var backup=new Array();
	for (var i=0; i<f.elements.length; i++){
		var name=f.elements[i].name;
		var type=f.elements[i].type;
		//alert(name+' - '+type);
		if(type=='radio'){
			if(f.elements[i].checked){	o[name]=f.elements[i].value; }
		}else if(type=='checkbox'){
			backup[backup.length]=name;
			if(f.elements[i].checked){
				if(!o[name]){o[name]=new Array();  	}
				o[name][o[name].length]=f.elements[i].value;
			}
		}else if(type.substring(-2)){	
			if(!o[name]){o[name]=new Array();  }			
			o[name][o[name].length]=f.elements[i].value;
		}else{			o[name]=f.elements[i].value; }
	}
	for(var e in backup){if(!o[backup[e]]){o[backup[e]]=0;}}
	return o;
}







function removeByVal(item,array) {
var i = 0;
while (i < array.length) {
if (array[i] == item) {
array.splice(i, 1);
} else {
i++;
}
}
return array;
}


function resize(id){
	window.top.$('#'+id).css("height",0+'px');
	window.top.$('#'+id).css("display",'block');
	var h=window.top.document.getElementById(id).contentWindow.document.body.scrollHeight;
	window.top.$('#'+id).css("height",window.top.document.getElementById(id).contentWindow.document.body.scrollHeight+'px');
}
function enable(){
	$('#errorMessage').css('display','none'); $('#blanket').css("display",'none'); 
//	if(parent.document.forms[0]){parent.document.forms[0].elements[0].focus();}
}
function disable(){window.top.$("#blanket").css("display",'block');}






/*function changeRating(id,rating){
	disable();
	$.post("ratingchange.php",{id:id,rating:rating},
  	function(data){
	if(data.length<1)	{$.prompt("Rating ammended",{timeout:1000}); 	}else{$.prompt(data);  //$(this).val($.data(this, 'current'));
}
	enable();	
});}
*/





	



function htmlentities(texto){
    var i,carac,letra,novo='';
    for(i=0;i<texto.length;i++){
        carac = texto[i].charCodeAt(0);
        if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
          //se for numero ou letra normal
            novo += texto[i];
        }else{
            novo += "&#" + carac + ";";
        }
    }
    return novo;
}

function html_entity_decode(str) {
  var ta = document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  toReturn = ta.value;
  ta = null;
  return toReturn
} 



function isNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
	   Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1){
        	IsNumber = false;
        }
   }
   return IsNumber;
}





// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};



/* from here unique to pm_send*/
function toggle(name,id,imgid,c){
	if(c){
		addRecipient(name,id,imgid);
	}else{
		for(var i in recipients){if(recipients[i][1]==id){var id=i;}}
		removeRecipient(id);
	}
}

function loadNames(type){
	if($("#contactName").val().length<2){$('#matches').html('');return false;}	
	//disable();
	var exclude='';for(var i in recipients){exclude+=','+recipients[i][1];}
	if(type=='*'){var ext='All';}else{var ext='Members';}
	$.post("search"+ext+".php",{'contactName':$("#contactName").val(),'exclude':exclude.substr(1)},
	function(data){
		//alert(data);
var matchy=$.evalJSON(data);
		
		if(matchy==null){v='No similar names on MusicBorn';}
		else{
			var v='';
			for(var i in matchy){
				v+='<a href="#" id="href'+matchy[i]['id']+'" onclick="addRecipient(\''+escape(matchy[i]['name'])+'\','+matchy[i]['id']+','+matchy[i]['imgid']+'); return false;">'+matchy[i]['name']+'</a>';
			}
		
		}	
		$('#matches').html(v);
	});
}

function removeRecipient(i){
 $("input[name^='checkBox"+recipients[i][1]+"']").each(function() {      $(this).attr('checked',false) });
	recipients.splice(i,1);
	loadRecipients();
}
function addRecipient(name,id,imgid){
	$("input[name^='checkBox"+id+"']").each(function() {      $(this).attr('checked',true) });
	$('#href'+id).hide();
	recipients[recipients.length]=[unescape(name),id,imgid];
	loadRecipients();
}

function rBox(array,boxid){
	var id=array[0];
	var name=array[1];
	var imgid=array[2];

	var pg='<a href="profile.php?id='+id+'" target="_parent">'; var pg2='</a>';
	var l=' <div class="rBox nomar">'
				+'<div class="img">'+pg+'<img src="ups/s/'+imgid+'.jpg"  alt="'+escape(name)+'" />'+pg2+'</div>'
				+'<div class="text">'+pg+'<b>'+name+'</b>'+pg2
				+'<div class="editBtn">'
					
					+'<a href="#" onclick="removeRecipient('+boxid+'); return false;" class="rem">Remove</a>'
				+'</div>'
			+'</div></div>';
	return l;
}
function loadRecipients(){
	$("#recipients").html('');
	if(recipients.length>0){
		for (i=0; i < recipients.length; i++){
			$("#recipients").prepend(rBox([recipients[i][1],recipients[i][0],recipients[i][2]],i));
		}
	}else{$("#recipients").html('No Recipients Added');}
}

function sendMessage(bh){
	//alert('pmsend pro');
	//gen - subject msg did
	//pmsend - subject msg
	//pmview - hid behalf msg
	disable();
	var include='';	
	if(typeof(recipients)=='object'){
		var i=0;
		for(var i in recipients){include+=','+recipients[i][1];}
	}
	if($('#did').val()){var did=$("#did").val();}else{var did='';}
	if($('#hid').val()){var hid=$("#hid").val();}else{var hid='';}
	if($('#subject').val()){var subject=$("#subject").val();}else{var subject='';}
	$.post("pm_send_process.php",{recipients:include.substr(1),did:did,hid:hid,subject:subject,msg:$("#msg").val(),bh:bh},
  	function(data){
		if(data.length<1)	{
			var refA=document.referrer.split('/');
			var ref=refA[(refA.length-1)];
			window.location=ref;
		}else{$.prompt(data);}
		enable();
	});
}
/*to here unique to pm_send*/
