var breaker = 1;
function ajax_start()
{
		var XMLHttpRequestObject = false; 
		if (window.XMLHttpRequest)
		{
			XMLHttpRequestObject = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			XMLHttpRequestObject = new ActiveXObject('Microsoft.XMLHTTP');
		}	
		return XMLHttpRequestObject;
}
function display_ajax_html(page, args, div_id, XMLHttpRequestObject, callback, callback_args, args2)
{
	if(XMLHttpRequestObject)
	{
		var params = args;

		XMLHttpRequestObject.open('POST', '/ajax.php?do='+page, true); 
		XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		XMLHttpRequestObject.onreadystatechange = function() 
			{ 
				if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
				{ 						
						if(callback)
						{
							callback(XMLHttpRequestObject.responseText, callback_args, args2);
						}
						else
							document.getElementById(div_id).innerHTML = XMLHttpRequestObject.responseText;

				} 
			} 
		XMLHttpRequestObject.send(params); 
	}
}
function urlEncode(str)
{
	return str.replace("&", "%26");
}
function forgot_pass()
{
	//Ajax to send
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('forgot_pass', '&username='+document.getElementById('forgot_passbox').value, 'forgot_pass', XMLHttpRequestObject);	
}
function change_pass()
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('change_pass', '&id='+document.getElementById('id_form').value+'&code='+document.getElementById('code_form').value+'&new_password='+document.getElementById('new_password').value, 'pass_content', XMLHttpRequestObject);
}
function switch_psst(cur, prev, username, tweeted, click)
{
	var psst_action_arr = new Array();
	var psst_text_arr = new Array();
	//Rotation
	if(!tweeted)
	{
		psst_action_arr[1] = "share('"+username+"', true);";
		psst_text_arr[1] = "<img src='/images/twitter_small.gif' style='border:0px;position:absolute;margin-top:-6px;'/> <span style='margin-left:37px;'>Click here to tweet about us and get 5 free credits!</span>";
	}

	//Social sites
	psst_action_arr[2] = "window.location = '/profile#tabs-2';";
	psst_text_arr[2] = "Get your name out there! Click this box to add your Facebook, Twitter, Blog and more for surfers to see.";		
	//Gallery
	psst_action_arr[3] = "window.location = '/gallery';";
	psst_text_arr[3] = "Check out the gallery where top sites and users are showcased!";
	//Blog
	psst_action_arr[4] = "window.location = '/blog';";
	psst_text_arr[4] = "Check out our blog for updates!";
	//Surf tips
	psst_action_arr[5] = "window.location = '/surftips';";
	psst_text_arr[5] = "Need help understanding the surf bar? Here's a few tips!";
	//Mobilesurf tips
	psst_action_arr[6] = "window.location = '/mobilesurf';";
	psst_text_arr[6] = "Want to surf on your iphone? Click here to find out more!";
	
	//if cur is too big
	if(cur > 6 && !tweeted)
		cur = 1;
	else if(cur > 5 && tweeted)
		cur = 2;
	if(!tweeted)
	{
		$('#psst').animate({color:"#48647A"}, 300, function()
		{
		document.getElementById('psst').innerHTML = psst_text_arr[cur];
		document.getElementById('psst').href = "javascript:"+psst_action_arr[cur];
		$('#psst').animate({color:"#ffffff"}, 300);
		});
	}
	else
	{
		$('#psst').animate({color:"#48647A"}, 300, function()
		{
		document.getElementById('psst').innerHTML = psst_text_arr[cur+1];
		document.getElementById('psst').href = "javascript:"+psst_action_arr[cur+1];
		$('#psst').animate({color:"#ffffff"}, 300);
		});	
	}
	document.getElementById('rotate_'+cur).style.color = '#ffffff';
	document.getElementById('rotate_'+prev).style.color = '#777777';
	cur_psst = cur;
	if(click)
	{
		clearTimeout(this_timeout);
		if(tweeted)
			tweeted = 'true';
		else
			tweeted = 'false';
		this_timeout = setInterval("switch_psst(cur_psst+1, cur_psst, '"+username+"', "+tweeted+");", 5000);
	}
}
function distribute_creds()
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('distribute_creds', '', 'distribute_creds', XMLHttpRequestObject);
}
function big_thumb(id, span_id)
{
	if(!span_id)
		span_id = id;
	//Hidden, show
	if(document.getElementById('big_thumb_'+span_id).style.display == 'none')
	{
		document.getElementById('big_thumb_'+span_id).style.display = 'block';
		document.getElementById('big_thumb_'+span_id).innerHTML = "<img src='thumbnail.php?id="+id+"' />";
	}
	else
	{
		//Shown, hide
		document.getElementById('big_thumb_'+span_id).style.display = 'none';
	}	
}

function validate(form, check_email)
{
	var form_el = document.getElementById(form);
	if(form == 'username')
	{
		if(form_el.value.length < 3)
			validate_output(form, false, 'Username must be 3 or more characters');
		else if(form_el.value.match(/[^a-zA-Z0-9]/))
			validate_output(form, false, 'Username can only contain letters and numbers');			
		else
		{
			//Ajax to check availability
			XMLHttpRequestObject = ajax_start();
			display_ajax_html('check_avail', '&username='+form_el.value, '', XMLHttpRequestObject, is_available, 'user');
		}	
	}
	else if(form == 'email')
	{
		if(!form_el.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/))
			validate_output(form, false, 'Please enter a valid email address');	
		else if(!check_email)
		{
			//Ajax to check availability
			XMLHttpRequestObject = ajax_start();
			display_ajax_html('check_avail', '&email='+form_el.value, '', XMLHttpRequestObject, is_available, 'email');
		}
		else
			validate_output(form, true);		
	}
	else if(form == 'password')
	{
		if(form_el.value.length < 6)
			validate_output(form, false, 'Password must be 6 or more characters');
		else
			validate_output(form, true);
	}
	else if(form == 'password2')
	{
		if(form_el.value.length < 6)
			validate_output(form, false, 'Password must be 6 or more characters');
		else if(document.getElementById('password').value != form_el.value)
			validate_output(form, false, 'Your passwords did not match');		
		else
			validate_output(form, true);
	}
	else if(form == 'blog')
	{
		//Std varchar
		if(form_el.value.length > 0 && form_el.value.substring(0, 7) != 'http://')
			validate_output(form, false, 'Blog must be a url');		
		else			
			validate_output(form, true);
	}
	else if(form == 'facebook')
	{
		//Std varchar
		if(form_el.value.match(/[^a-zA-Z0-9+@._\?&= \/-]/))
			validate_output(form, false, 'Invalid Character');		
		else			
			validate_output(form, true);	
	}	
	else if(form == 'linkedin')
	{
		//Std varchar
		if(form_el.value.match(/[^a-zA-Z0-9+@._\?&= \/-]/))
			validate_output(form, false, 'Invalid Character');		
		else			
			validate_output(form, true);	
	}
	else
	{
		//Std varchar
		if(form_el.value.match(/[^a-zA-Z0-9+@._ -]/))
			validate_output(form, false, 'Username can only contain letters, spaces, numbers + @ _ . and -');		
		else			
			validate_output(form, true);
	}
		
}
function toggle_mobile()
{
	//Change mobile stuff
	document.getElementById('mobile_info').innerHTML = '<img src="/images/small_load.gif" alt="loading..."/>';
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('toggle_mobile', '', 'mobile_info', XMLHttpRequestObject);
}
function is_available(json, type)
{
	var json_array = eval('(' + json + ')');	
	if(type == 'user')
	{
		if(json_array['error'] == 'true')
			validate_output('username', false, 'That usename is taken');
		else
			validate_output('username', true);
	}
	else
	{
		if(json_array['error'] == 'true')
			validate_output('email', false, 'That email is taken');
		else
			validate_output('email', true);	
	}
} 
function validate_output(form, success, message)
{
	document.getElementById(form+'_message').style.display = 'block';
	if(success)
	{
		document.getElementById(form+'_message').innerHTML = '<font color="#008C00">Success</font>';
		document.getElementById(form).style.backgroundColor = '#A6FFA9';
		document.getElementById(form).style.border = '1px solid #008C00';		
	}
	else
	{
		document.getElementById(form+'_message').innerHTML = message;
		document.getElementById(form).style.backgroundColor = '#FF9C9C';
		document.getElementById(form).style.border = '1px solid #CC0000';		
	}
	
}
function request_com()
{
	var paypal = document.getElementById('paypal_email').value;
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('request_com', '&paypal='+paypal, 'commission', XMLHttpRequestObject);	

}
function update_thumb(site_id, times)
{
	/*if(days > 0)
		alert('Unfortunately we can only refresh your thumbnail once per 15 days. You have '+days+' before you can refresh this site');
	else
	{*/
	if(times<1)
		alert("Unfortunately you've maxed out on the number of refreshes per week");
	else
	{
		var answer = confirm('Are you sure you want to refresh this thumbnail? You have '+times+' thumbnail refreshes left this week. It will take a few minutes for your thumbnail to update.');
		if(answer)
		{
			XMLHttpRequestObject = ajax_start();
			display_ajax_html('refresh_thumb', '&site_id='+site_id, '', XMLHttpRequestObject, updated_thumb, site_id);	
		}
	}
}
function updated_thumb(json, id)
{
	alert('This thumbnail has been queued for update. It can take up to 1 hour');
}
function update_thumb_preview(assign)
{
	if(document.getElementById('add_border'))
		var color = document.getElementById('add_border').value;
	else
		var color = '#111111';
	//If not from sites page
	if(!assign)
	{
		document.getElementById('thumb_preview_main').style.display = 'block';
		document.getElementById('thumb_preview').innerHTML = "<img src='thumbnail.php?id="+document.getElementById('add_csite').value+"' style='border:4px solid #"+color+";'/>";
	}
	else
	{
		document.getElementById('thumb_preview_img').style.border = "border:4px solid #"+color;	
	}
}
function submit_feedback()
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('submit_feedback', '&feedback='+urlEncode(document.getElementById('feedback').value)+'&email='+document.getElementById('f_email').value, '', XMLHttpRequestObject, slim);
}
function slim(response)
{
	document.getElementById('login_box').innerHTML = response;
	$("#login_bar").animate({height: 30}, 300);	
}
function edit_site(site_id, action)
{
	if(action != 'delete')
	{
		//Loading img
		document.getElementById(site_id+'_edit').innerHTML = "<img src='images/small_load.gif' alt='loading' />";
	}
	XMLHttpRequestObject = ajax_start();
	if(action == 'edit')
		display_ajax_html('site_info', '&site_id='+site_id, '', XMLHttpRequestObject, update_site);
	else if(action == 'cancel')
		display_ajax_html('site_info', '&cancel=T&site_id='+site_id, '', XMLHttpRequestObject, update_site);	
	else if(action == 'save')
	{
		//Pass values
		var name = urlEncode(document.getElementById('name_'+site_id).value);
		var url = urlEncode(document.getElementById('url_'+site_id).value);
		var auto = urlEncode(document.getElementById('auto_'+site_id).value);
		var args = '&name='+name+'&url='+url+'&auto='+auto;
		display_ajax_html('site_info', '&save=T&site_id='+site_id+args, '', XMLHttpRequestObject, update_site, true);
	}
	else if(action == 'delete')
	{
		var answer = confirm('Are you sure you want to delete this site? Any associated campaigns will be deleted as well.');
		if(answer)
			display_ajax_html('site_info', '&delete=T&site_id='+site_id, '', XMLHttpRequestObject, delete_row);			
	}
}
function edit_campaign(campaign_id, action)
{
	if(action != 'delete')
	{
		//Loading img
		document.getElementById(campaign_id+'_edit').innerHTML = "<img src='images/small_load.gif' alt='loading' />";
	}
	XMLHttpRequestObject = ajax_start();
	if(action == 'edit')
		display_ajax_html('campaign_info', '&campaign_id='+campaign_id, '', XMLHttpRequestObject, update_campaign, 'S');
	else if(action == 'cancel')
		display_ajax_html('campaign_info', '&cancel=T&campaign_id='+campaign_id, '', XMLHttpRequestObject, update_campaign);	
	else if(action == 'save')
	{
		//Pass values
		var name = urlEncode(document.getElementById('name_'+campaign_id).value);
		var site = urlEncode(document.getElementById('site_'+campaign_id).value);
		var txtkeyword = urlEncode(document.getElementById('txtkeyword_'+campaign_id).value);
		var credits = urlEncode(document.getElementById('credits_'+campaign_id).value);
		var args = '&name='+name+'&site='+site+'&credits='+credits+'&txtkeyword='+txtkeyword;
		display_ajax_html('campaign_info', '&save=T&campaign_id='+campaign_id+args, '', XMLHttpRequestObject, update_campaign, 'T');
	}
	else if(action == 'delete')
	{
		var answer = confirm('Are you sure you want to delete this campaign? Your credits will be restored.');
		if(answer)
			display_ajax_html('campaign_info', '&delete=T&campaign_id='+campaign_id, '', XMLHttpRequestObject, delete_row, 'T');
	}
	else if(action == 'refresh')
	{
		display_ajax_html('campaign_info', '&refresh=T&campaign_id='+campaign_id, '', XMLHttpRequestObject, refresh);	
	}
		
}
function delete_all(type)
{
	var answer = confirm('Are you sure you want to delete all your campaigns? Your credits will be returned');
	if(answer)
	{
		XMLHttpRequestObject = ajax_start();
		display_ajax_html('delete_all', '&type='+type, '', XMLHttpRequestObject, delete_all_rows);		
	}
}
function delete_all_rows(table)
{
	//Delete all the rows
	var Parent = document.getElementById(table);
	while(Parent.hasChildNodes())
	{
		Parent.removeChild(Parent.firstChild);
	}
	insert_filler(table, "Campaigns successfully deleted");
}
function insert_filler(table, text)
{
	//Insert a no campaigns row
	var Parent = document.getElementById(table);
    var row = document.createElement("tr");

	//Create tds
	var td = document.createElement("td");
	if(table == 'tbody')
		var id = 'filler';
	else if(table == 'auto_body')
		var id = 'filler_auto';
	else
		var id = 'filler_completed';
	td.id = id;
	td.colSpan = 5;
	row.appendChild(td);
    
    Parent.appendChild(row);
    document.getElementById(id).innerHTML = text;
   	//$("#"+id).effect('highlight', {}, 2000);
}
function show_tut(vid, height)
{
	var margin = height+45;
	document.getElementById('tut_vid').innerHTML = "<a href='javascript:void(0);' onclick=\"hide_tut('"+vid+"')\"><b>Close</b></a><br /><div id='container' style='position:absolute;margin-left:-487px;margin-top:-"+margin+"px;background-color:#fa9300;z-index:100;border:6px solid #111111;'><a href='/guide#"+vid+"'>Click here for a text version</a><br /><a  href='/media/"+vid+".flv' style='display:block;width:520px;height:"+height+"px' id='player'></a></div>";
	flowplayer("player", "/flowplayer/flowplayer-3.1.5.swf");
}
function hide_tut(vid)
{
	document.getElementById('tut_vid').innerHTML = "<img src='/images/television.png' style='border:0px;' /><a href='javascript:void(0);' onclick=\"show_tut('"+vid+"');\"><b>Click here to watch our tutorial video for this page</b></a>";
}
function refresh(json)
{
	//See if error or not
	if(json.indexOf("{") == -1)
	{
		var arr = json.split('_');
		var id = arr[0];
		var error = arr[1];
		alert(error);
		edit_campaign(id, 'cancel');
	}
	else
	{
		//Remove old row
		removeRow(json, true);
		$("#tabs").tabs('select', 0);
		insert_row(json, true);
	}
}
/*
function sort(type)
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('sort', '&sort='+type, '', XMLHttpRequestObject, refresh_rows);
}
*/
function add_site()
{
	//Give a loading message
	document.getElementById('site_submit').innerHTML = '<img src="images/small_load.gif" alt="loading" />';
	
	XMLHttpRequestObject = ajax_start();
	//Pass values
	var name = urlEncode(document.getElementById('add_name').value);
	var url = urlEncode(document.getElementById('add_url').value);
	var args = '&name='+name+'&url='+url;
	display_ajax_html('add_site', args, '', XMLHttpRequestObject, insert_row);
}
function add_campaign(no_callback)
{

	var keywords = urlEncode(document.getElementById('add_keywords').value);

	if ( keywords.length>100 )
	{
		alert("The No of Characters must be less than 100.");
		return false;	
	}	

	//Give a loading message
	document.getElementById('campaign_submit').innerHTML = '<img src="images/small_load.gif" alt="loading" />';

	//Switch to active tab
	$("#tabs").tabs('select', 0);
		
	XMLHttpRequestObject = ajax_start();
	//Pass values
	var name = urlEncode(document.getElementById('add_cname').value);
	var site = urlEncode(document.getElementById('add_csite').value);
	var credits = urlEncode(document.getElementById('add_credits').value);

	//If admin and there's a border
	if(document.getElementById('add_border'))
		var border = document.getElementById('add_border').value;
	else
		var border = '';
	//Insert row
	if(!no_callback)
	{
		var args = '&name='+name+'&site='+site+'&credits='+credits+'&border='+border+'&keywords='+Encode_Special_Chars(keywords);
		display_ajax_html('add_campaign', args, '', XMLHttpRequestObject, insert_row, true);
	}
	else
	//show message
	{
		var args = '&name='+name+'&site='+site+'&credits='+credits+'&border='+border+'&update=true&keywords='+Encode_Special_Chars(keywords);	
		display_ajax_html('add_campaign', args, 'contactArea', XMLHttpRequestObject);	
	}	
}
function delete_row(json, campaign)
{
	removeRow(json, campaign);
}
function insert_row(json, campaign)
{	
	//If there aren't campaigns or sites, delele the filler row
	if(document.getElementById('no_rows').innerHTML == 't')
		removeRow('filler', false, true);
	//See if error or not
	if(json.indexOf("{") == -1)
		alert(json);
	else
	{
		var table = document.getElementById('tbody');
	    var row = document.createElement("tr");
	
		var json_array = eval('(' + json + ')');	
		for(var i in json_array)
		{
			if(i != 'credits' && i != 'id')
			{
				//Create tds
				var td = document.createElement("td");
				td.id = i;
		     	row.appendChild(td);
		     	var index = i;
	     	}
		}
		var row_id = index.split('_');
		row_id = row_id[0];
		if(campaign)
	    	row.id = 'campaign_'+row_id;
	    else
	    	row.id = 'site_'+row_id;
	    
	    table.insertBefore(row, table.firstChild);
	    //Update tds
		for(var i in json_array)
		{
			if(i != 'credits' && i != 'id')
	    		document.getElementById(i).innerHTML = json_array[i];
	    }
	    	
	    if(campaign)
	    {
	    	//Update credit count if pos
	    	if(json_array['credits'] > 0)
	   		{
				var credits = json_array['credits'];		
				//Update credit count on page
				document.getElementById('cur_credits').innerHTML = credits;
			}
	    	//Update progress bar
			$("#"+row_id+"_progress_bar").progressbar({
					value: 0
			});
		}
		else
		{
			//validate for sites
			update_counter(10, row_id);
			//Prevent any framebreaks, redirect to fail page
 			breaker = 1;
 			var skip = 0;
			setInterval(function() 
			{ 
				if (skip>0 && breaker>0) 
				{ 
					skip = skip-2; 
					window.location = 'http://www.thumbvu.com/sites?fail='+row_id; 
				}
			}, 130); 
			window.onbeforeunload = function() 
			{
				skip++;
			}
		}
		//Highlight
		$("#"+row.id).effect('highlight', {}, 2000);
		//Remove load msg
	}
	if(campaign)
	{
		//Hide add campaign box
		$('#add_camp').hide();
		document.getElementById('add_camp_button').value = "Add another campaign";
		$('#add_camp_message').show();
		document.getElementById('campaign_submit').innerHTML = "<input type='submit' value='Add campaign' onclick=\'add_campaign();\' /> <a href='javascript:void(0);' onclick=\"$('#add_camp').hide();$('#add_camp_message').show();\">Cancel</a>";
	}
	else
	{
		//Hide add site box
		$('#add_site').hide();
		document.getElementById('add_site_button').value = "Add another site";
		$('#add_site_message').show();
		document.getElementById('site_submit').innerHTML = "<input type='submit' value='Add site' onclick=\'add_site();\' /> <a href='javascript:void(0);' onclick=\"$('#add_site').hide();$('#add_site_message').show();\">Cancel</a>";    
	}
}
function insert_article(json, campaign)
{	
	//If there aren't campaigns or sites, delele the filler row
	if(document.getElementById('no_rows').innerHTML == 't')
		removeRow('filler', false, true);
	//See if error or not
	if(json.indexOf("{") == -1)
		alert(json);
	else
	{
		var table = document.getElementById('tbody');
	    var row = document.createElement("tr");
	
		var json_array = eval('(' + json + ')');	
		for(var i in json_array)
		{
			
			//Create tds
			var td = document.createElement("td");
			td.id = i;
			row.appendChild(td);
			var index = i;
	     	
		}
		var row_id = index.split('_');
		row_id = row_id[0];
		

	    row.id = 'article_'+row_id;
	    
	    table.insertBefore(row, table.firstChild);
	    //Update tds
		for(var i in json_array)
		{
	    	document.getElementById(i).innerHTML = json_array[i];
	    }	    	

		//Update progress bar
		$("#"+row_id+"_progress_bar").progressbar({
				value: 0
		});

		//Highlight
		$("#"+row.id).effect('highlight', {}, 2000);
		//Remove load msg
	}
		
	//Hide add article box
	$('#add_article').hide();
	document.getElementById('add_article_button').value = "Add another article";
	$('#add_article_message').show();
	document.getElementById('article_submit').innerHTML = "<input value='Save' type='submit'  onclick='add_article();' ><a href='javascript:void(0);' onclick=\"$('#add_article').hide();$('#add_article_message').show();\">Cancel</a>";
		
}
function try_again(site_id, url)
{
	document.getElementById(site_id+'_assign').innerHTML = "<img src='images/small_load.gif' alt=''/> Validating <span id='counter_"+site_id+"'>10</span><img src='http://thumbvu.websnapr.com/?size=S&url="+urlEncode(url)+"' style='width:1px;height:1px;'/><iframe style='height:1px; width: 1px; border: 0px;' src='"+url+"'></iframe>";
	//validate for sites
	update_counter(10, site_id);
	//Prevent any framebreaks, redirect to fail page
	breaker = 1;
	var skip = 0;
	setInterval(function() 
	{ 
		if (skip>0 && breaker>0) 
		{ 
			skip = skip-2; 
			window.location = 'http://www.thumbvu.com/sites?fail='+site_id; 
		}
	}, 130); 
	window.onbeforeunload = function() 
	{
		skip++;
	}
}
function update_counter(count, site_id)
{
	var new_count = count-1;
	if(new_count == 0)
	{
		//Validation page, passed
		XMLHttpRequestObject = ajax_start();
		display_ajax_html('approve_site', '&site='+site_id, site_id+'_assign', XMLHttpRequestObject);
		breaker=0;
	}
	else
	{
		document.getElementById('counter_'+site_id).innerHTML = new_count;
		var delay = function() { update_counter(new_count, site_id); };
		setTimeout(delay, 1000);
	}
}
function update_site(json, highlight)
{
	//See if error or not
	if(json.indexOf("{") == -1)
	{
		var arr = json.split('_');
		var id = arr[0];
		var error = arr[1];
		alert(error);
		edit_site(id, 'cancel');
	}
	else
	{
		var json_array = eval('(' + json + ')');
		for(var i in json_array)
		{
			if(i != 'new_url')
			{
				document.getElementById(i).innerHTML = json_array[i];
				//Get row name
				row_id = document.getElementById(i).parentNode;
			}
		}
		if(highlight)
		{
			//Highlight
			$("#"+row_id.id).effect('highlight', {}, 2000);
			//Validate stuff
			if(json_array['new_url'])
			{
				var row_id = row_id.id.split('_');
				row_id = row_id[1];
				document.getElementById(row_id+'_assign').innerHTML = "<img src='images/small_load.gif' alt=''/> Validating <span id='counter_"+row_id+"'>10</span><img src='http://thumbvu.websnapr.com/?size=S&url="+urlEncode(json_array['new_url'])+"' style='width:1px;height:1px;'/><iframe style='height:1px; width: 1px; border: 0px;' src='"+json_array['new_url']+"'></iframe>";
				//validate for sites
				update_counter(10, row_id);
				//Prevent any framebreaks, redirect to fail page
	 			breaker = 1;
	 			var skip = 0;
				setInterval(function() 
				{ 
					if (skip>0 && breaker>0) 
					{ 
						skip = skip-2; 
						window.location = 'http://www.thumbvu.com/sites?fail='+row_id; 
					}
				}, 130); 
				window.onbeforeunload = function() 
				{
					skip++;
				}
			}
		}
	}
}
function update_campaign(json, highlight)
{
	//See if error or not
	if(json.indexOf("{") == -1)
	{
		var arr = json.split('_');
		var id = arr[0];
		var error = arr[1];
		alert(error);
		edit_campaign(id, 'cancel');
	}
	else
	{
		var json_array = eval('(' + json + ')');
		for(var i in json_array)
		{
			if(i != 'perc' && i != 'credits')
			{
				document.getElementById(i).innerHTML = json_array[i];
				//Get row name
				row_id = document.getElementById(i).parentNode;
			}
		}
		if(highlight == 'T')
		{
			//Update credit count on page
			//highlight = credits
			document.getElementById('cur_credits').innerHTML = json_array['credits'];
			var new_row = row_id.id.split('_');
			new_row = new_row[1];
			//Update progress bar
			$("#"+new_row+"_progress_bar").progressbar('option', 'value', json_array['perc']);
			//Highlight value: json_array['perc']
			$("#"+row_id.id).effect('highlight', {}, 2000);
		}
		//Select box
		else if(highlight == 'S')
		{
			//get id
			var new_row = row_id.id.split('_');
			new_row = new_row[1];
			//select box fancy
			$("#site_"+new_row).msDropDown();
		}
	}
}
function assign_credits(site_id)
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('assign_credits', '&site_id='+site_id, '', XMLHttpRequestObject, update_assign);
	
	centerPopup(site_id);
	var title = "Add a campaign";
	var content = '<img src="images/small_load.gif" alt="" /> Loading';
	loadPopup(title, content);	
}
function add_suggest()
{
	//load img
	document.getElementById('submit_load').innerHTML = "<img src='/images/small_load.gif' alt='loading...'/>";
	XMLHttpRequestObject = ajax_start();
	if(document.getElementById('suggestion').value.length > 0)
	{
		display_ajax_html('add_suggestion', '&suggestion='+urlEncode(document.getElementById('suggestion').value), '', XMLHttpRequestObject, add_suggestion);
		document.getElementById('suggestion').value = '';
	}
	else
	{
		alert('You must enter a suggestion!');
		document.getElementById('submit_load').innerHTML = "<input type='submit' value='Suggest' onclick='add_suggest();'/>";
	}
}
function add_suggestion(json)
{
	document.getElementById('submit_load').innerHTML = "<input type='submit' value='Suggest' onclick='add_suggest();'/>";
	var json_array = eval('(' + json + ')');
	document.getElementById('suggestion_added').innerHTML = json_array['msg'];
	if(json_array['add'].length > 0)
	{
		document.getElementById('suggestions').innerHTML = json_array['add'] + document.getElementById('suggestions').innerHTML;
		$("#sugg_new").effect("highlight", {color:"#444444"}, 3000);
		document.getElementById('sugg_new').id = 'sugg_old';
		if(document.getElementById('none_yet'))
			document.getElementById('none_yet').style.display = 'none';
	}
	else
		document.getElementById('suggestion').value = json_array['sug'];
}
function max_chars(textarea, counter_id) 
{
	counter_id.value = 256 - textarea.value.length;
}
function suggest(id)
{
	if(document.getElementById('suggest_text'+id).innerHTML != 'Liked')
	{
		var likes = document.getElementById('likes'+id).innerHTML;
		document.getElementById('likes'+id).innerHTML = parseInt(likes)+1;
		document.getElementById('suggest_text'+id).innerHTML = 'Liked';
		XMLHttpRequestObject = ajax_start();
		display_ajax_html('inc_suggestion', '&id='+id, '', XMLHttpRequestObject);
	}
}
function update_assign(json)
{
	document.getElementById('contactArea').innerHTML = json;
	new jscolor.color(document.getElementById('add_border'), {});
}
function dupe_campaign(campaign_id)
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('add_campaign', '&dupe=T&id='+campaign_id, '', XMLHttpRequestObject, insert_row, true);
}
function share(refname, give_creds)
{
	if(!give_creds)
		centerPopup(false, 'tweetthis');
	else
		centerPopup(false);
	var title = "Tweet this!";
	if(give_creds)
		var content = "<p style='margin-bottom:0px;'>Type in your twitter username and twitter password (we don't store any of this data) -- we'll post it to Twitter for you and add 5 credits to your account!</p><br /><span class='label'><span style='font-weight:500;'>Tweet:</span></span><br />Explode your social network following and promote YOU: http://www.thumbvu.com/ref/"+refname+" #thumbvu<p><span class='label'><span style='font-weight:500;'>Twitter Username:</span></span> <input type='text' id='username'/></p><p><span class='label'><span style='font-weight:500;'>Twitter Password:</span></span> <input type='password' id='password' onkeydown='if (event.keyCode == 13) retweet_send(true);'/></p><p><input type='submit' value='Tweet this' onclick='retweet_send(true)'/> <a href='javascript:void(0);' onclick='disablePopup();'>Cancel</a></p><img src='/images/twitter_logo.png'/>";
	else
		var content = "<p style='margin-bottom:0px;'>Type in what you want to tweet, your twitter username and twitter password (we don't store any of this data) -- we'll post it to Twitter for you!</p><br /><span class='label'><span style='font-weight:500;'>Tweet:</span></span><br /><textarea id='tweet_content' onKeyDown=\"max_chars(document.getElementById('tweet_content'), document.getElementById('tweet_counter'))\" onKeyUp=\"max_chars(document.getElementById('tweet_content'), document.getElementById('tweet_counter'))\">Explode your social network following and promote YOU: http://www.thumbvu.com/ref/"+refname+" #thumbvu</textarea><br /><input readonly type='text' id='tweet_counter' size='3' maxlength='3' value='140' />characters left.<br /><p><span class='label'><span style='font-weight:500;'>Twitter Username:</span></span> <input type='text' id='username'/></p><p><span class='label'><span style='font-weight:500;'>Twitter Password:</span></span> <input type='password' id='password' onkeydown='if (event.keyCode == 13) retweet_send();'/></p><p><input type='submit' value='Tweet this' onclick='retweet_send()'/> <a href='javascript:void(0);' onclick='disablePopup();'>Cancel</a></p><img src='/images/twitter_logo.png'/>";
	loadPopup(title, content);	
}
function retweet_send(give_creds)
{
	if(document.getElementById('tweet_content') && document.getElementById('tweet_content').value.length > 140)
		alert('Your tweet must be 140 characters or less!');
	else
	{
		XMLHttpRequestObject = ajax_start();
		if(give_creds)
			display_ajax_html('post_to_twitter', '&give_creds=true&username='+document.getElementById('username').value+'&password='+document.getElementById('password').value, '', XMLHttpRequestObject, retweet_send_update);	
		else
			display_ajax_html('post_to_twitter', '&tweet_content='+document.getElementById('tweet_content').value+'&username='+document.getElementById('username').value+'&password='+document.getElementById('password').value, '', XMLHttpRequestObject, retweet_send_update);	
	}
}
function retweet_send_update(response)
{
	if(response.substring(0,5) == '<span')
	{
		document.getElementById('contactArea').innerHTML = response+document.getElementById('contactArea').innerHTML;
	}
	else
		document.getElementById('contactArea').innerHTML = response;
}
function show_listad(username, id)
{
	var html = "";
	//If they have a pic show it
	if(id > 0)
		html += "<img src='/pics/pic_"+id+".gif' align='left' style='width:100px;margin-right:5px;margin-bottom:3px;'/>";
	var box_array = new Array();
	//Array with all the sites
	var sites_array = new Array("facebook", "twitter", "blog", "youtube", "imloop", "imfaceplate","apsense", "digg", "linkedin", "blogger", "flickr", "tumblr", "email", "yahoobuzz", "myspace", "vimeo", "orkut", "stumbleupon", "picasa", "friendfeed", "lastfm", "skype", "aim", "google", "peoplestring");
	var url_array = new Array("http://www.facebook.com/<<u>>", "http://www.twitter.com/<<u>>", "<<u>>", "http://www.youtube.com/user/<<u>>", "http://imloop.com/#!/<<u>>","http://www.imfaceplate.com/<<u>>","http://www.apsense.com/user/<<u>>", 'http://www.digg.com/users/<<u>>', 'http://www.linkedin.com/<<u>>', 'http://www.<<u>>.blogspot.com', 'http://www.flickr.com/photos/<<u>>', 'http://www.<<u>>.tumblr.com', 'mailto:<<u>>', 'http://www.buzz.yahoo.com/publisher/<<u>>', 'http://www.myspace.com/<<u>>', 'http://www.vimeo.com/<<u>>', 'http://www.<<u>>.orkut.com/', 'http://www.stumbleupon.com/stumbler/<<u>>', 'http://www.picasaweb.google.com/<<u>>', 'http://www.friendfeed.com/<<u>>', 'http://www.lastfm.com/user/<<u>>', 'skype:<<u>>?chat', 'aim:goim?screenname=<<u>>', 'http://www.google.com/profiles/<<u>>', 'http://www.social.peoplestring.com/<<u>>');
	//Grab all the forms with info
	var boxes = document.getElementById('social').getElementsByTagName("INPUT");
	for(var i = 0; i < boxes.length; i++)
	{
		if(boxes[i].type == 'text' && boxes[i].value.length > 0)
			box_array[boxes[i].id] = boxes[i].value;
	}
	var textareas = document.getElementById('social').getElementsByTagName("TEXTAREA");
	for(var i = 0; i < textareas.length; i++)
	{
		if(textareas[i].type == 'text' && textareas[i].value.length > 0)
			box_array[boxes[i].id] = textareas[i].value;
	}
	//Email
	if( document.getElementById('show_email')!=null && document.getElementById('show_email').checked == 1)
		box_array['email'] = document.getElementById('email').value;
		
	html += "<span style='float:left;'>";
	for(var site in sites_array)	
	{
		if(box_array[sites_array[site]] != '' && box_array[sites_array[site]] != null)
		{
			if(sites_array[site] == 'blog')
				var icon = 'rss';
			else
				var icon = sites_array[site];
			var url = url_array[site].replace(/<<u>>/, box_array[sites_array[site]]);
			html += "<a href='"+url+"' target='_BLANK' title='"+url+"' ><img src='/images/icons/"+icon+"_32.png' style='border:0px;' /></a> ";	
		}
	}
	html += "</span></span>";
	document.getElementById('listad_container').style.display = 'block';
	//Listad header
	if(document.getElementById('header'))
	{
		html += "<p style='clear:both;'>"+document.getElementById('header').value+"</p>";
		XMLHttpRequestObject = ajax_start();
		display_ajax_html('get_preview', '&listad='+urlEncode(document.getElementById('listad_t').value), '', XMLHttpRequestObject, update_preview, html);		
	}
	else
		update_preview('', html);
		
}
function update_preview(json, html)
{
	document.getElementById('listad_preview').innerHTML = html + json + "</div></div></div>";
}
function tweet_this()
{
	document.getElementById('tweet_submit').innerHTML = '<img src="images/small_load.gif" alt="loading" />';
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('thanks_tweet', '&username='+document.getElementById('username').value+'&password='+document.getElementById('password').value, '', XMLHttpRequestObject, tweet_this_update);		
}
function tweet_this_update(response)
{
	if(response.substring(0,5) == '<span')
	{
		document.getElementById('twitter').innerHTML = response+document.getElementById('twitter').innerHTML;
		document.getElementById('tweet_submit').innerHTML = "<input type='submit' value='Tweet this' onclick='tweet_this()'/>";		
	}
	else
		document.getElementById('twitter').innerHTML = response;
}
function removeRow(json, campaign, nojson) 
{
	if(!nojson)
	{
		var json_array = eval('(' + json + ')');
		var id = json_array['id'];	
	}
	else
		var id = json;
	
	if(campaign)
	{
		var credits = json_array['credits'];		
		//Update credit count on page
		document.getElementById('cur_credits').innerHTML = credits;
	}
	var tr = document.getElementById(id);
	if (tr) 
	{
		if (tr.nodeName == 'TR') 
		{
			var tbl = tr; // Look up the hierarchy for TABLE
			while (tbl != document && tbl.nodeName != 'TBODY')
			{
				tbl = tbl.parentNode;
			}
	 
			if (tbl && tbl.nodeName == 'TBODY') 
			{
				while (tr.hasChildNodes()) 
				{
					tr.removeChild( tr.lastChild );
				}
			var Parent = tr.parentNode;
			tr.parentNode.removeChild( tr );
			}
			//Insert filler if none left
			if(id != 'filler')
			{
				nodeNum = Parent.childNodes.length; 
				if(nodeNum == 2)
				{
					if(campaign)
						var text = "You don't have  any campaigns.";
					else
						var text = "You don't have any sites.";
					insert_filler(Parent.id, text);
				}
			}
	    } 
	    else 
	    {
	 		//alert( 'Specified document element is not a TR. id=' + id );
	    }
	} 
	else 
	{
		//alert( 'Specified document element is not found. id=' + id );
	}
}
//Current slide
var cur_slide = 0;
function slide_to(num)
{
	//Get rid of timeout
	clearTimeout(home_timeout);
	//Update colors
	 $('#link'+cur_slide).animate({ color: "#ffffff" }, 500);
	 $('#link'+num).animate({ color: "#FA9300" }, 500);
	//Hide old one
	//Direction
	if(num < cur_slide)	
		$("#slide"+cur_slide).hide('slide',{direction:"right"}, 500, function(){$("#slide"+num).show('slide',{direction:"left"},500);});
	else if(num > cur_slide)
		$("#slide"+cur_slide).hide('slide',{direction:"left"}, 500, function(){$("#slide"+num).show('slide',{direction:"right"},500);});
	
	cur_slide = num;	
}
/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!					
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup without jQuery magic!
function loadPopup(title, content, count){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$('#backgroundPopup').fadeIn("slow");
		$('#popupContact').fadeIn("slow");
		document.getElementById('popup_title').style.display = 'block';
		document.getElementById('contactArea').style.display = 'block';
		replace_html(document.getElementById('popup_title'), title);
		replace_html(document.getElementById('contactArea'), content);
		popupStatus = 1;
	}
}
//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$('#backgroundPopup').fadeOut("slow");
		$('#popupContact').fadeOut("slow");
		popupStatus = 0;
	}
}

//centering popup
function centerPopup(id, id2){
	//request data for centering

	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();
	
	if(id)
		var pos = findPos(document.getElementById(id+'_assign'))
	else if(id2)
		var pos = findPos(document.getElementById(id2))
	else
		var pos = 170;
	pos = pos-150;
	if(pos<0)
		pos = windowHeight/2-popupHeight/2;
	//centering
	$("#popupContact").css({
		"position": "absolute",
		"top": pos,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#backgroundPopup").css({
		"height": windowHeight
	});
	
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){

	//CLOSING POPUP
	//Click the x event!
	$("#popupContactClose").click(function(){
		disablePopup();
	});
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
});
function findPos(obj) 
{
	var curtop = 0;
	if(obj)
	{
		if (obj.offsetParent) 
		{
			do {
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}
	}
return curtop;
}
function findPosX(obj) 
{
	var curtop = 0;
	if (obj.offsetParent) 
	{
		do {
			curtop += obj.offsetLeft;
		} while (obj = obj.offsetParent);
	}
return curtop;
}
function replace_html(el, html) {
	if( el ) {
                var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
                //var oldEl = el;
                var newEl = document.createElement(oldEl.nodeName);

                // Preserve any properties we care about (id and class in this example)
                newEl.id = oldEl.id;
                newEl.className = oldEl.className;

                //set the new HTML and insert back into the DOM
                newEl.innerHTML = html;
                if(oldEl.parentNode)
        	        oldEl.parentNode.replaceChild(newEl, oldEl);
                else
		        oldEl.innerHTML = html;

                //return a reference to the new element in case we need it
                return newEl;
	}
};
//Loading img
if (document.images)
{
  pic1= new Image(16,16); 
  pic1.src="/images/loading.gif"; 
}
//Tooltips
var cur_user = 0;
var go = true;
var tooltip=function()
{
	var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h,smallw;
	var ie = document.all ? true : false;
	return{
		show:function(v,doc, userid, hide_pic, smallw1)
		{
			if(tt == null)
			{
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				tt.setAttribute('onmouseover', "go=false;");
				tt.setAttribute('onmouseout', "go=true;setTimeout('tooltip.hide();', 1000);");
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				tt.appendChild(c);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				if(smallw1)
					smallw = smallw1;
				else
					smallw = false
   			}
			this.pos(doc);
   			//lazy
			w = 120;
			tt.style.display = 'block';
			if(v)
				c.innerHTML = v;
			else if(cur_user != userid)
			{
				cur_user = userid;
				//Load prof
				c.innerHTML = 'loading...';
				if(hide_pic)
					var extras = '&hide_pic=t';
				else
					var extras = '';
				
				XMLHttpRequestObject = ajax_start();
				display_ajax_html('get_profile', '&id='+userid+extras, '', XMLHttpRequestObject, update_profile, userid, c);
			}
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie)
			{
				tt.style.width = tt.offsetWidth;
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
  		},
		showchatinfo:function(v,doc, userid, hide_pic, smallw1)
		{
			if(tt == null)
			{
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				tt.setAttribute('onmouseover', "go=false;");
				tt.setAttribute('onmouseout', "go=true;setTimeout('tooltip.hide();', 1000);");
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				tt.appendChild(c);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				if(smallw1)
					smallw = smallw1;
				else
					smallw = false
   			}
			this.chatpos(doc);
   			//lazy
			w = 120;
			tt.style.display = 'block';
			if(v)
				c.innerHTML = v;
			else if(cur_user != userid)
			{
				cur_user = userid;
				//Load prof
				c.innerHTML = 'loading...';
				if(hide_pic)
					var extras = '&hide_pic=t';
				else
					var extras = '';
				
				XMLHttpRequestObject = ajax_start();
				display_ajax_html('get_chatinfo', '&id='+userid+extras, '', XMLHttpRequestObject, update_profile, userid, c);
			}
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie)
			{
				tt.style.width = tt.offsetWidth;
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
  		},
  		pos:function(doc)
  		{
  			var u = findPos(doc);
  			var l = findPosX(doc);
			//var u = ie ? event.clientY + document.docElement.scrollTop : e.pageY;
			//var l = ie ? event.clientX + document.docElement.scrollLeft : e.pageX;

			tt.style.top = (u) + 15 + 'px';
			if(!smallw)
				tt.style.left = (l + left) + 200 + 'px';
			else
				tt.style.left = (l + left) + 100 + 'px';				
  		},
  		chatpos:function(doc)
  		{
  			var u = findPos(doc);
  			var l = findPosX(doc);
			//var u = ie ? event.clientY + document.docElement.scrollTop : e.pageY;
			//var l = ie ? event.clientX + document.docElement.scrollLeft : e.pageX;

			tt.style.top = (u) + 8 + 'px';
			if(!smallw)
				tt.style.left = (l + left) + 120 + 'px';				
			else
				tt.style.left = (l + left) + 50 + 'px';				
  		},
  		fade:function(d)
 		{
   			var a = alpha;
  			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
    		var i = speed;
   			if(endalpha - a < speed && d == 1)
   			{
    			i = endalpha - a;
   			}
   			else if(alpha < speed && d == -1)
   			{
    			i = a;
   			}
   				alpha = a + (i * d);
   				tt.style.opacity = alpha * .01;
   				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}
  			else
  			{
    			clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function()
 		{
 		 	//don't wanna comment this, it's a pain, gl
  			if(go)
	  		{
				clearInterval(tt.timer);
				tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
			}
		}
	};
}();
function update_profile(json, userid, c)
{
	if(cur_user == userid)
	{
		if(json.length > 75)
			c.innerHTML = json;
		else
			c.innerHTML = json + "<p>No info listed</p>";
	}
}

function Encode_Special_Chars(str)
{
	str=escape(str).replace("+", "%2B");
	return str;
}

function validatekeyword()
{
	/*
	if ( document.frmsitekeyword.txtkeyword.value=="")
	{
		alert("Enter the Site keyword.");
		document.frmsitekeyword.txtkeyword.focus();
		return false;
	}
	*/
	return true;
}

function add_article(no_callback)
{


	//Pass values
	var category = urlEncode(document.getElementById('cmbcategory').value);
	var articletitle = urlEncode(document.getElementById('articletitle').value);
	var description = urlEncode(document.getElementById('description').value);
	//var content = urlEncode(document.getElementById('elm1').value);
	var content =  tinyMCE.get('elm1').getContent();

	if ( category==-1 )
	{
		alert("Select the Category of the Article");
		return false;
	}	
	
	if ( content.length>2500 )
	{
		alert("The No of Characters must be less than 2500.");
		return false;	
	}	

	//Give a loading message
	document.getElementById('article_submit').innerHTML = '<img src="images/small_load.gif" alt="loading" />';

	//Switch to active tab
	$("#tabs").tabs('select', 2);
		
	XMLHttpRequestObject = ajax_start();

	//Insert row
	if(!no_callback)
	{		
		var args = '&category='+category+'&articletitle='+Encode_Special_Chars(articletitle)+'&description='+Encode_Special_Chars(description)+'&content='+Encode_Special_Chars(content);
		display_ajax_html('add_article', args, '', XMLHttpRequestObject, insert_article, true);
	}
	else
	//show message
	{
		
		var args = '&category='+category+'&articletitle='+Encode_Special_Chars(articletitle)+'&description='+Encode_Special_Chars(description)+'&content='+Encode_Special_Chars(content);
		display_ajax_html('add_article', args, 'contactArea', XMLHttpRequestObject);	
	}
	
}

function edit_article(article_id, action)
{

	if(action != 'delete')
	{
		//Loading img
		document.getElementById('edit_article_message').innerHTML = "<img src='images/small_load.gif' alt='loading' />";
	}
	XMLHttpRequestObject = ajax_start();
	if(action == 'edit')
	{
		$('#edit_article').fadeIn('slow');
		display_ajax_html('article_info', '&article_id='+article_id, '', XMLHttpRequestObject, update_article, 'S');
		document.getElementById('edit_article_message').innerHTML = "";
		
	}
	else if(action == 'cancel')
	{
		display_ajax_html('article_info', '&cancel=T&article_id='+article_id, '', XMLHttpRequestObject, update_article);
		$('#edit_article').fadeOut('slow');
		document.getElementById('edit_article_message').innerHTML = "";	
	}
	else if(action == 'save')
	{
		//Pass values
		var category = urlEncode(document.getElementById('cmbcategory_'+article_id).value);
		var content =  tinyMCE.get('elm_'+article_id).getContent();
		var articletitle = urlEncode(document.getElementById('articletitle_'+article_id).value);
		var description = urlEncode(document.getElementById('description_'+article_id).value);		
		
		if ( category==-1 )
		{
			alert("Select the Category of the Article");
			return false;
		}
		
		if ( content.length>2500 )
		{
			alert("The No of Characters must be less than 2500.");
			return false;	
		}		

		var args = '&category='+category+'&articletitle='+Encode_Special_Chars(articletitle)+'&description='+Encode_Special_Chars(description)+'&content='+Encode_Special_Chars(content);

		display_ajax_html('article_info', '&save=T&article_id='+article_id+args, '', XMLHttpRequestObject, update_article, 'T');
		document.getElementById('edit_article_message').innerHTML = "";
		
	}
	else if(action == 'delete')
	{
		var answer = confirm('Are you sure you want to delete this article? ');
		if(answer)
			display_ajax_html('article_info', '&delete=T&article_id='+article_id, '', XMLHttpRequestObject, removeArticle, 'T');
	}
		
}


//For Article Update
function update_article(json, highlight)
{
	//See if error or not
	if(json.indexOf("{") == -1)
	{
		var arr = json.split('_');
		var id = arr[0];
		var error = arr[1];
		alert(error);
		edit_article(id, 'cancel');
	}
	else
	{
		var json_array = eval('(' + json + ')');
		var alerttext = "";
		
		for(var i in json_array)
		{
			if(i != 'perc' && i != 'credits')
			{
				document.getElementById(i).innerHTML = json_array[i];
				//Get row name
				//alerttext = alerttext + json_array[i];
				row_id = document.getElementById(i).parentNode;
			}
		}
		
		if(highlight == 'T')
		{
			//Update credit count on page
			//highlight = credits
			var new_row = row_id.id.split('_');
			new_row = new_row[1];

			//Highlight value: json_array['perc']
			$("#edit_article").effect('highlight', {}, 1500);
			$('#edit_article').fadeOut('slow');
			
		}
		//Select box
		else if(highlight == 'S')
		{
			//get id
			var new_row = row_id.id.split('_');
			new_row = new_row[1];
			//select box fancy
			//$("#edit_article").msDropDown();
		}

		/*
		if ( tinyMCE.get('elm_'+new_row) )
		{
			tinyMCE.execCommand('mceRemoveControl',false,'elm_'+new_row);
		}
		*/
		
	tinyMCE.init({
			// General options
			mode : "textareas",
			theme : "advanced",
			editor_selector : "mceEditor",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist",

			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext|,bullist,numlist,|,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,preview,|,forecolor,backcolor,fullscreen",

			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			content_css : "css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js",

			// Style formats
			style_formats : [
				{title : 'Bold text', inline : 'b'},
				{title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
				{title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
				{title : 'Example 1', inline : 'span', classes : 'example1'},
				{title : 'Example 2', inline : 'span', classes : 'example2'},
				{title : 'Table styles'},
				{title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
			],

			// Replace values for the template plugin
			template_replace_values : {
				username : "Some User",
				staffid : "991234"
			}
		});	
		
		//tinyMCE.get('elm_'+new_row).remove();
		if ( tinyMCE.get('elm_'+new_row) )
		{
			tinyMCE.execCommand('mceRemoveControl',false,'elm_'+new_row);
		}
	}
}


function removeArticle(json, campaign, nojson) 
{
	if(!nojson)
	{
		var json_array = eval('(' + json + ')');
		var id = json_array['id'];	
	}
	else
		var id = json;

	var tr = document.getElementById(id);
	if (tr) 
	{
		if (tr.nodeName == 'TR') 
		{
			var tbl = tr; // Look up the hierarchy for TABLE
			while (tbl != document && tbl.nodeName != 'TBODY')
			{
				tbl = tbl.parentNode;
			}
	 
			if (tbl && tbl.nodeName == 'TBODY') 
			{
				while (tr.hasChildNodes()) 
				{
					tr.removeChild( tr.lastChild );
				}
			var Parent = tr.parentNode;
			tr.parentNode.removeChild( tr );
			}
			//Insert filler if none left
			if(id != 'filler')
			{
				nodeNum = Parent.childNodes.length; 
				if(nodeNum == 2)
				{
					if(campaign)
						var text = "You don't have  any campaigns.";
					else
						var text = "You don't have any sites.";
					insert_filler(Parent.id, text);
				}
			}
	    } 
	    else 
	    {
	 		//alert( 'Specified document element is not a TR. id=' + id );
	    }
	} 
	else 
	{
		//alert( 'Specified document element is not found. id=' + id );
	}
}

function dupe_article(article_id)
{
	XMLHttpRequestObject = ajax_start();
	display_ajax_html('add_article', '&dupe=T&id='+article_id, '', XMLHttpRequestObject, insert_article, true);
}

function addCredit_Member(article_id)
{
	XMLHttpRequestObject = ajax_start();
		
	var args = 'articlecredit=Y&article_id='+article_id;
	display_ajax_html('article_credit', args, '', XMLHttpRequestObject, assigncredit, true);
}

function assigncredit(msg)
{
	$("#credit_message").innerHTML=msg;
}

function saveProfileWidget()
{
	var bgcolor = urlEncode(document.getElementById('bgcolor1').value);
	var txtcolor = urlEncode(document.getElementById('txtcolor1').value);
	var numsites = urlEncode(document.getElementById('txtnumsites').value);
	
	XMLHttpRequestObject = ajax_start();
		
	var args = 'profilewidget=Y&bgcolor='+bgcolor+'&txtcolor='+txtcolor+'&numsites='+numsites;
	display_ajax_html('profile_widget', args, '', XMLHttpRequestObject, profilewidget, true);
	
}

function profilewidget(msg)
{
	//$("#credit_message").innerHTML=msg;
	window.location.href="/promote";	
}

