// Load jQuery
google.load("jquery", "1.3.2");
google.load('visualization', '1', {'packages': ['geomap','piechart']});
google.setOnLoadCallback(function() {
	$("a.external").each(function(){
		$(this).attr("target","_blank");
	});
	/*
	 * Start Inner Label Methods
	 */
	function replaceInnerLabels(){
		$(".inner-label").each(function(){
			if($(this).val()==''){
				$(this).val($(this).attr('title'));
			}
		});
		return true;
	}
	$(".inner-label").each(function(){
		if($(this).val()==''){
			$(this).val($(this).attr('title'));
		}
	});
	$(".inner-label").focus(function(){
		if($(this).val() == $(this).attr('title')){
			$(this).val('');
		}
	});
	$(".inner-label").blur(function(){
		if($(this).val() == ''){
			$(this).val($(this).attr('title'));
		}
	});
	$("form").submit(function(){
		$(".inner-label").each(function(){
			if($(this).val()==$(this).attr('title')){
				$(this).val('');
			}
		});
	});
	/*
	 * End Inner Label Methods
	 */
	$("button.modal").attr("disabled","disabled");
	$(".label").remove();
	$("button.finish").click(function(){
		if($(this).attr("disabled")){
			return false;
		} else {
			$('#dialog').jqmHide();
		}
	});
	$("#signature-form").submit(function(e){
		var throwError = false;
		$("#signature-form .required").each(function(){
			if($(this).val()== ''){
				throwError = true;
			}
		});
		if(throwError){
			replaceInnerLabels();
			alert("Please complete the form before continuing\nThanks");
			return false;
		}
		if(!throwError){
			verifyCityState()
			return true;
		} else {
			return false;
		}
	});
	$("#state").blur(function(){
		if($(this).val() != $(this).attr('title') && $(this).val() != ''){
			verifyCityState();
		}
	});
	$(".step-1").keypress(function(){
		if(isFirstStepComplete()){
			$("button.modal").removeAttr("disabled");
		} else {
			$("button.modal").attr("disabled","disabled");
		}
	}).blur(function(){
		if(isFirstStepComplete()){
			$("button.modal").removeAttr("disabled");
		} else {
			$("button.modal").attr("disabled","disabled");
		}
	});
	$(".step-2").keypress(function(){
		if(isSecondStepComplete()){
			$("button.finish").removeAttr("disabled");
		} else {
			$("button.finish").attr("disabled","disabled");
		}
	}).blur(function(){
		if(isSecondStepComplete()){
			$("button.finish").removeAttr("disabled");
		} else {
			$("button.finish").attr("disabled","disabled");
		}
	});
	
	$("#terms.step-2").click(function(){
		if(isSecondStepComplete()){
			$("button.finish").removeAttr("disabled");
		} else {
			$("button.finish").attr("disabled","disabled");
		}
	});
	$(".terms").click(function(){
		if(isCommentComplete(this)){
			$(this).parents("form").find("button").removeAttr("disabled");
		} else {
			$(this).parents("form").find("button").attr("disabled","disabled");
		}
	});
	$(".step-comment").blur(function(){
		if(isCommentComplete(this)){
			$(this).parents("form").find("button").removeAttr("disabled");
		} else {
			$(this).parents("form").find("button").attr("disabled","disabled");
		}
	});
	/*
	 * Google Visualization
	 */
	if($("#map_canvas").size()==1){
		drawMap();
	}
	if($("#chart_div").size()==1){
		drawChart();
	}
	/*
	 * Modal Functions
	 */
	$('button.modal').click(function(){
		$('#dialog').find("#captcha").prepend($("#recaptcha_widget_div"));
		$('#dialog').jqmShow();
		
		return false;
	});
	$('#dialog').jqm();
	
	$(".auto-select").click(function(){$(this).select();});
	
	$(".reply-form").each(function(){
		$(this).jqm();
		$(this).jqDrag('.jqDrag');
	});
	$(".reply").click(function(){
		var d = $(this).parents(".signature").find(".reply-form");
		d.find(".button-block").prepend($("#recaptcha_widget_div"));
		d.jqmShow();
		return false;
	});
	$(".closing").each(function(){
		$(this).children(".links").hide();
	});
	$(".closing").mouseover(function(){
		$(this).children(".links").show();
	})
	$(".closing").mouseout(function(){
		$(this).children(".links").hide();
	});
	$(".sub-questions").each(function(){
		$(this).hide();
	})
	$(".show-sub-questions").click(function(){
		if($(this).val()=='1'){
			$(this).parents("dl").next().show();
		} else {
			$(this).parents("dl").next().hide();
		}
	});
	$(".recommend-reply").click(function(){
		recommendReply($(this).next().text());
		$(this).hide();
		var total = $(this).parents(".recommend").children(".total").text()*1+1;
		$(this).parents(".recommend").children(".total").text(total);
		return false;
	});
	$(".recommend-signature").click(function(){
		recommendSignature($(this).next().text());
		$(this).hide();
		var total = $(this).parents(".recommend").children(".total").text()*1+1;
		$(this).parents(".recommend").children(".total").text(total);
		return false;
	});
	$(".report-reply-abuse").click(function(){
		var id = $(this).parents(".user-reply").find(".reply-number").text();
		reportReplyAbuse(id);
		$(this).hide().after("Abuse Reported");
		return false;
	});
	$(".report-signature-abuse").click(function(){
		var id = $(this).parents(".signature").find(".signature-number").text();
		reportSignatureAbuse(id);
		$(this).hide().after("Abuse Reported");
		return false;
	});
});
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};
function verifyCityState(){
	var geocode = new GClientGeocoder();
	if($("#city").val() ==''
		|| $("#state").val() ==''){
		return false;
	}
	geocode.getLatLng($("#city").val()+', '+$("#state").val(),
			function(obj){
				geocode.getLocations(obj,function(obj){
					var city      = new String();
					var stateName = new String();
					var stateAbbr = new String();
					$(obj.Placemark).each(function(){
						if(this.AddressDetails.Accuracy == 5) {
							// City
							var loc = this.address.split(",",3);
							city  = loc[0].trim();
						} else if(this.AddressDetails.Accuracy == 2) {
							// State Name
							var loc = this.address.split(",",2);
							stateName  = loc[0].trim();
							stateAbbr  = this.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
						}
					});

					// Verify Returned Geocode Matches User input
					if((stateName.toUpperCase() != $("#state").val().toUpperCase() && stateAbbr.toUpperCase() != $("#state").val().toUpperCase()) || city.toUpperCase() != $("#city").val().toUpperCase() ){
						if((stateName.toUpperCase() == $("#state").val().toUpperCase() || stateAbbr.toUpperCase() == $("#state").val().toUpperCase())){
							$("#state").val(stateName);
							updateDatabase(stateName,city);
							return true;
						}
					} else {
						$("#state").val(stateName);
						$("#city").val(city);
						updateDatabase(stateName,city);
						return true;
					}
				});
		});
}
function updateDatabase(state_name,city_name){
	$.post("/scripts/updateDatabase.php", { state:state_name, city:city_name },function(data){
		//console.log(data);
	});
}
function recommendSignature(id){
	$.post("/scripts/recommendSignature.php", { signatures_id:id },function(data){
		//console.log(data);
	});
}
function recommendReply(id){
	$.post("/scripts/recommendReply.php", { replies_id:id },function(data){
		//console.log(data);
	});
}
function updateDatabase(state_name,city_name){
	$.post("/scripts/updateDatabase.php", { state:state_name, city:city_name },function(data){
		//console.log(data);
	});
}
function reportReplyAbuse(id){
	$.post("/scripts/reportReplyAbuse.php", { replies_id:id },function(data){
		//console.log(data);
	});
}
function reportSignatureAbuse(id){
	$.post("/scripts/reportSignatureAbuse.php", { signatures_id:id },function(data){
		//console.log(data);
	});
}
function drawMap() {
    var data = new google.visualization.DataTable();
    $.ajax({
    	  url: "/scripts/fetchLocations.php",
    	  cache: false,
    	  async: false,
    	  success: function(xml){
    		var i=0;
    		data.addRows($(xml).find('location').size());
    	    data.addColumn('string', 'State');
    	    data.addColumn('number', 'Signatures');
	    	$(xml).find('location').each(function(){
		    	data.setValue(i, 0, $(this).find('name').text());
		        data.setValue(i, 1, parseInt($(this).find('total').text()));
		        i++;
	    	});
    	  }
    	});

    var options = {};
    options['region'] = "US";
    options['showLegend'] = false;
    options['colors'] = [0xCCCCFF, 0x000066]; //blue colors
    options['width'] = 330;
    options['height'] = 200;
    options['dataMode'] = 'regions';

    var container = document.getElementById('map_canvas');
    var geomap = new google.visualization.GeoMap(container);
    geomap.draw(data, options);
    //google.visualization.events.addListener(geomap, 'regionClick', function(data){updateMap(data.region);});
 };
 function drawChart() {
     var data = new google.visualization.DataTable();
     data.addColumn('string', 'Issue');
     data.addColumn('number', 'Total Signatures');

    
     $.ajax({
   	  url: "/scripts/fetchPoliticalIssues.php",
   	  cache: false,
   	  async: false,
   	  success: function(xml){
         data.addRows($(xml).find('issue').size());
    	 var i=0;
         $(xml).find('issue').each(function(){
    	    	data.setValue(i, 0, $(this).find('name').text());
    	        data.setValue(i, 1, parseInt($(this).find('total').text()));
    	        i++;
     	});
   	  }
   	});

     var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
     chart.draw(data, {width: 330, height: 200, is3D: true,title:'Primary Concerns of Our Users'});
 }
 function updateMap(region) {
	    var data = new google.visualization.DataTable();
	    $.ajax({
	    	  url: "/scripts/fetchLocationsByState.php",
	    	  cache: false,
	    	  async: false,
	    	  data: 'region='+region,
	    	  success: function(xml){
	    		var i=0;
	    		data.addRows($(xml).find('location').size());
	    	    data.addColumn('string', 'City');
	    	    data.addColumn('number', 'Signatures');
		    	$(xml).find('location').each(function(){
			    	data.setValue(i, 0, $(this).find('name').text());
			        data.setValue(i, 1, parseInt($(this).find('total').text()));
			        i++;
		    	});
	    	  }
	    	});

	    var options = {};
	    options['region'] = 'US';
	    options['showLegend'] = false;
	    options['colors'] = [0xCCCCFF, 0x000066]; //blue colors
	    options['width'] = 330;
	    options['height'] = 200;
	    options['dataMode'] = 'markers';

	    var container = document.getElementById('map_canvas');
	    var geomap2 = new google.visualization.GeoMap(container);
	    geomap2.draw(data, options);
};
function isFirstStepComplete()
{
	var stepComplete = true;
	$(".step-1").each(function(){
		if(($(this).val()=='' &&
				$(this).hasClass("required")) ||
			($(this).hasClass("inner-label") &&
				$(this).val()==$(this).attr("title") &&
				$(this).hasClass("required"))){
			stepComplete = false;
		}
	});
	return stepComplete;
}
function isSecondStepComplete()
{
	var stepComplete = true;
	if($("#signature-form input:checked").length > 0){
		$(".step-2").each(function(){
			if(($(this).val()=='' &&
					$(this).hasClass("required")) ||
				($(this).hasClass("inner-label") &&
					$(this).val()==$(this).attr("title") &&
					$(this).hasClass("required"))){
				stepComplete = false;
			}
		});
	} else {
		stepComplete = false;
	}

	return stepComplete;
}
function isCommentComplete(d)
{
	var stepComplete = true;
	if($(d).parents("form").find("input:checked").length > 0){
		$(d).parents("form").find(".step-comment").each(function(){
			if(($(this).val()=='' &&
					$(this).hasClass("required")) ||
				($(this).hasClass("inner-label") &&
					$(this).val()==$(this).attr("title") &&
					$(this).hasClass("required"))){
				stepComplete = false;
				console.log($(this).attr("id"));
			}
		});
	} else {
		stepComplete = false;
	}

	return stepComplete;
}
