// prepare the form when the DOM is ready
$(document).ready(function() {
	if (document.getElementById("defaultSend") != undefined)
	{
		document.getElementById('defaultSend').style.display = 'none';
	}

	if (document.getElementById("ajaxSend") != undefined)
	{
		document.getElementById('ajaxSend').style.display = 'inline';
	}

	if (document.getElementById("emailinput") != undefined)
	{
		document.getElementById('emailinput').style.display = 'none';
	}
	// bind form using ajaxForm
    $('#htmlForm').ajaxForm({
beforeSubmit: validate,
        // target identifies the element(s) to update with the server response
        target: '#htmlTarget',

        // success identifies the function to invoke when the server response
        // has been received; here we apply a fade-in effect to the new content
        success: function() {
            $('#htmlTarget').fadeIn('slow');
            $('#htmlForm').fadeOut('slow');
        }
    });
		function submit_search()
		{
			var select_value = $('#comparerates select#state').val();
			var base_url = "/state/";
			var category = '';

			var current_url = window.location.href;
			if ((current_url.search('/stateserv/') > 0) || (current_url.search('&cat=') > 0))
			{
				base_url = "/stateserv/";
			}

			if ((current_url.search('--phone-service') > 0) || (current_url.search('=phone%20service') > 0))
			{
				category = '--phone-service';
			}

			else if ((current_url.search('--high-speed-internet') > 0) || (current_url.search('=high%20speed%20internet') > 0))
			{
				category = '--high-speed-internet';
			}

			else if ((current_url.search('--cable-television') > 0) || (current_url.search('=cable%20television') > 0))
			{
				category = '--cable-television';
			}

			else if ((current_url.search('--satellite-television') > 0) || (current_url.search('=satellite%20television') > 0))
			{
				category = '--satellite-television';
			}

			else if ((current_url.search('--cellular') > 0) || (current_url.search('=cellular') > 0))
			{
				category = '--cellular';
			}

			else if ((current_url.search('--voip') > 0) || (current_url.search('=voip') > 0))
			{
				category = '--voip';
			}

			else if ((current_url.search('--bundled-services') > 0) || (current_url.search('=bundled%20services') > 0))
			{
				category = '--bundled-services';
			}

			if ((current_url.search('--dialup-internet') > 0) || (current_url.search('=dialup%20internet') > 0))
			{
				category = '--dialup-internet';
			}


			var states = new Array()
			states['AL'] = 'alabama';
			states['AK'] = 'alaska';
			states['AZ'] = 'arizona';
			states['AR'] = 'arkansas';
			states['CA'] = 'california';
			states['CO'] = 'colorado';
			states['CT'] = 'connecticut';
			states['DE'] = 'delaware';
			states['DC'] = 'district-of-columbia';
			states['FL'] = 'florida';
			states['GA'] = 'georgia';
			states['HI'] = 'hawaii';
			states['ID'] = 'idaho';
			states['IL'] = 'illinois';
			states['IN'] = 'indiana';
			states['IA'] = 'iowa';
			states['KS'] = 'kansas';
			states['KY'] = 'kentucky';
			states['LA'] = 'louisiana';
			states['ME'] = 'maine';
			states['MD'] = 'maryland';
			states['MA'] = 'massachusetts';
			states['MI'] = 'michigan';
			states['MN'] = 'minnesota';
			states['MS'] = 'mississippi';
			states['MO'] = 'missouri';
			states['MT'] = 'montana';
			states['NE'] = 'nebraska';
			states['NV'] = 'nevada';
			states['NH'] = 'new-hampshire';
			states['NJ'] = 'new-jersey';
			states['NM'] = 'new-mexico';
			states['NY'] = 'new-york';
			states['NC'] = 'north-carolina';
			states['ND'] = 'north-dakota';
			states['OH'] = 'ohio';
			states['OK'] = 'oklahoma';
			states['OR'] = 'oregon';
			states['PA'] = 'pennsylvania';
			states['RI'] = 'rhode-island';
			states['SC'] = 'south-carolina';
			states['SD'] = 'south-dakota';
			states['TN'] = 'tennessee';
			states['TX'] = 'texas';
			states['UT'] = 'utah';
			states['VT'] = 'vermont';
			states['VA'] = 'virginia';
			states['WA'] = 'washington';
			states['WV'] = 'west-virginia';
			states['WI'] = 'wisconsin';
			states['WY'] = 'wyoming';

			var new_location = base_url+states[select_value]+category+'.html';
			window.location = new_location;
			return false;
		}
		$('#comparerates .btn').click(submit_search);

$('#subscribecheck').click(
    function () {
        if ($('#subscribecheck:checked').val() == undefined)
        {
            $('#emailinput').fadeOut('slow');
        } else {
            $('#emailinput').fadeIn('slow');
        }
    });
    qa.init();

    //"more" sub-menu display/hide
    $('#nav_more').hover(
      function () {
        $('#moresubmenu').css("display","block");
      },
      function () {
        $('#moresubmenu').css("display","none");
      }
    );


});
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;
}

qa =
{
	values:{},
	init:function()
	{
		tb_init('a.thickbox.post_answer');
		// ---
		// CLICK ON ANSWER LINK, POPULATE QUESTION_ID
		// ---
		$('.post_answer').click(
			function()
			{
				var question_id = $(this).attr('question_id');
				$('.answer_form input[name="question_id"]').val(question_id);
			}
		);

		// ---
		// ANSWER FORM SUBMISSION
		// ---
		$('.answer_form form').submit(qa.submit_answer);

		// ---
		// QUESTION FORM SUBMISSION
		// ---
		$('.question_form form').submit(qa.submit_question);
	},
	submit_answer:function()
	{
		// CURRENTLY NOT GETTING THE QUESTION_ID
		var question_id	= $('.answer_form input[name="question_id"]').val();
		var email	= $('.answer_form input[name="email"]').val();
		var answer	= $('.answer_form textarea[name="answer"]').val();

		if(email.length == 0)
		{
			alert("Please enter an email");
			return false;
		}
		else if(!util.validate_email(email))
		{
			alert("Please enter a valid email. username@domain.com");
			return false;
		}

		if(answer.length == 0)
		{
			alert("Please enter an answer");
			return false;
		}

		$.ajax({
			type:'GET',
			url:'/qa.php',
			dataType:'json',
			data: {'type':'answer','email':email,'question_id':question_id,'answer':answer},
			processData:true,
			timeout:60000,
			success:qa.success_answer,
			error:qa.failure_answer
			});
		return false;
	},
	success_answer:function(data)
	{
		if(data.result == true)
		{
			$('.js_clear').val('');
			alert("Thank you. Your answer will be reviewed shortly.");
			$('#TB_closeWindowButton').click();
		}
		else
		{
			alert("Sorry, we're having some technical difficulties. Please contact support and/or retry. Thank you");
		}
	},
	failure_answer:function()
	{
		alert("Sorry, we're having some technical difficulties. Please contact support and/or retry. Thank you");
		$('#TB_closeWindowButton').click();
	},
	submit_question:function()
	{
		var email	= $('.question_form input[name="email"]').val();
		var name	= $('.question_form input[name="name"]').val();
		var keyword1	= $('.question_form input[name="keyword"]').val();
		var keyword2	= $('.question_form select[name="keyword"]').val();
		var question	= $('.question_form textarea[name="question"]').val();

		if(email.length == 0)
		{
			alert("Please enter an email");
			return false;
		}
		else if(!util.validate_email(email))
		{
			alert("Please enter a valid email. username@domain.com");
			return false;
		}

		if(typeof(keyword1) == 'undefined')
		{
			if(typeof(keyword2) == 'undefined')
			{
				alert("Sorry, we're having technical difficulties. Please contact support.");
				return false;
			}
			else
			{
				keyword = keyword2;
			}
		}
		else
		{
			keyword = keyword1;
		}

		if(question.length == 0)
		{
			alert("Please enter a question");
			return false;
		}


		$.ajax({
			type:'GET',
			url:'/qa.php',
			dataType:'json',
			data: {'type':'question','email':email,'keyword':keyword,'question':question},
			processData:true,
			timeout:60000,
			success:qa.success_question,
			error:qa.failure_question
			});
		return false;
	},
	success_question:function(data)
	{
		if(data.result == true)
		{
			$('.js_clear').val('');
			alert("Thank you. Your question will be reviewed shortly.");
		}
		else
		{
			alert("Sorry, we're having some technical difficulties. Please contact support and/or retry. Thank you");
		}
	},
	failure_question:function()
	{
		alert("Sorry, we're having some technical difficulties. Please contact support and/or retry. Thank you");
		return false;
	}
}
util =
{
	validate_email:function(email)
       {
	       var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	       return reg.test(email);
	       // {
       }
}

function validate(formData, jqForm, options) {
    // jqForm is a jQuery object which wraps the form DOM element
    //
    // To validate, we can access the DOM elements directly and return true
    // only if the values of both the username and password fields evaluate
    // to true

    var form = jqForm[0];
	var alertMessage = '';
    var subscribestatus = $('#subscribecheck:checked').val();
	if(subscribestatus != undefined)
	{
		// subscribe box is checked, we should validate email.
        var email = $('#emailinput input').val();
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        var result =  reg.test(email);
	}
    if (form.type.value == "--" || form.state.value == "--" || !form.provider.value || !form.price.value || !IsNumeric(form.price.value) || (subscribestatus == 'on' && !result)) {
		if (form.type.value == "--")
		{
			alertMessage = alertMessage + 'Please select a service type.' + "\n";
		}
		if (form.state.value == "--")
		{
			alertMessage = alertMessage + 'Please select a state.' + "\n";
		}
		if (!form.provider.value)
		{
			alertMessage = alertMessage + 'Please enter your provider.' + "\n";
		}
		if (!form.price.value || !IsNumeric(form.price.value))
		{
			alertMessage = alertMessage + 'Please enter the amount of your monthly bill.' + "\n";
		}
		if (subscribestatus == 'on' && !result)
		{
			alertMessage = alertMessage + 'Please enter a valid email address.' + "\n";
		}
        alert(alertMessage);
        return false;
    }
}