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 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 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.border = '1px solid #008C00';		
	}
	else
	{
		document.getElementById(form+'_message').innerHTML = "<img src='/images/arrow.gif' alt='>'/> "+message+" <img src='/images/arrow_opp.gif' alt='<'/>";
		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 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 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 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.listgetting.me/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 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 />@MikeGartner thanks for the free squeeze page and products! http://www.listgetting.me/ref/"+refname+"<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'))\">@MikeGartner thanks for the free squeeze page and products! http://www.listgetting.me/ref/"+refname+"</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 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;
	}
};
