$(document).ready(function(){  
	//LOADING POPUP  
	//Click the button event!  
	$("#sign_up_button").click(function(){  
		//centering with css  
		centerPopup();  
		//load popup  
		loadPopup();
		resetPopup();
		resetValues();
		return false;
	});

	//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();  
		}  
	});
	
	// hijack the form submit
	$('#id_submit').bind('click',function(){
		resetPopup();
		$.post('/support/petition/process_form',$('#help_us_form').serialize(),function(data){

			var result = eval(data);
			
			// if the post was a success then display thank you popover
			if(result.success){
				window.location = '/support/petition';
			}
			else {
				jQuery.each(result.errors, function(i, val) {
					if (val.length) {
						$('#id_' + i).css('background-color','#ffd200');
						$('#id_' + i).after(val);
					};					
				});
				centerPopup();
			}
			// if not mark incorrect fields on the form
			},'json');

			return false;
		});
	
});


//SETTING UP OUR POPUP  
//0 means disabled; 1 means enabled;  
var popupStatus = 0;

//loading popup with jQuery magic!  
function loadPopup(){  
	//loads popup only if it is disabled  
	if(popupStatus==0){  
		$("#backgroundPopup").css({  
			"opacity": "0.7"  
		});  
		$("#backgroundPopup").fadeIn("slow");  
		$("#popupContact").fadeIn("slow");  
		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;  
	}  
}

function resetValues(){
	$('#help_us_form input:text').each(function(index,elm){
		$(elm).val('');
	});
	$('#help_us_form textarea').val('');
}


function resetPopup(){
	$('#help_us_form input:text').each(function(index,elm){
		$(elm).css('background-color','#ffffff');
	});
	$('#help_us_form textarea').css('background-color','#ffffff');
	$('ul.errorlist').remove();
}

//centering popup  
function centerPopup(){  
	//request data for centering  
	var windowWidth = document.documentElement.clientWidth;  
	var windowHeight = document.documentElement.clientHeight;  
	var popupHeight = $("#popupContact").height();  
	var popupWidth = $("#popupContact").width();  
	
	var top = windowHeight/2-popupHeight/2;
	var left = windowWidth/2-popupWidth/2;
	
	if (top < 0) {
		top = 20;
	}
	
	//centering  
	$("#popupContact").css({  
		"position": "absolute",  
		"top": top,  
		"left": left  
	});  
	//only need force for IE6  

	$("#backgroundPopup").css({  
		"height": document.body.clientHeight,
		"width": windowWidth
	});  

}
