﻿/// <reference path="jquery.js" />


$(document).ready(function () {
	$("#quotesend").click(function () {
		RateQuote();
		return false;
	});
});


function AJAXCall(JSON, WebUrl, Success, Failure) {
	$("#Processing").show();

	$.ajax({
		type: "POST",
		url: WebUrl,
		data: "{" + JSON + "}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: Success,
		error: Failure
	});
}

function InitRateQuoteForm() {
	$("#origin").val("");	
	$("#destination").val("");
	$("#weight").val("");
	$("#items").val("");
	$("#contactname").val("");
	$("#contactphone").val("");
	$("#email").val("");
}

function RateQuote() {
    checkValidValue(); //check to see if any of the required fields has value 'Required'
    var JSONString = "contactname: '" + $('#contactname').val() + "'"
                    + ", origin:'" + $("#origin").val() + "'"
                    + ", contactphone:'" + $("#contactphone").val() + "'"
					+ ", email:'" + $("#email").val() + "'"
					+ ", destination:'" + $("#destination").val() + "'"
					+ ", weight:'" + $("#weight").val() + "'"
				    + ", items:'" + $("#items").val() + "'";

	AJAXCall(JSONString, "index.aspx/RateQuote", RateQuoteAJAXSucceeded, RateQuoteAJAXFailed);
}

function RateQuoteAJAXSucceeded(result) {
	var data = result.d;
	data = $.parseJSON(data);

	if ($.isArray(data)) {
	    displayValidationMsg(data);
	}
	else {
	    $("#quotestatus").html(data);
	    InitRateQuoteForm();
	}
}

function RateQuoteAJAXFailed(result) {
	$("#quotestatus").html("Upload failed.");
}

function displayValidationMsg(data) {
    $('#contactname').val(data[0]);
    $('#contactphone').val(data[1]);

    if ($('#contactname').val() == 'Required') {
        $('#contactname').css('color', 'red');
    }

    if ($('#contactphone').val() == 'Required') {
        $('#contactphone').css('color', 'red');
    }

    $('#contactphone, #contactname').focus(function () {
        if ($(this).val() == 'Required') {
            $(this).val('').css('color', 'black');
        }
    });
}

function checkValidValue() {
    if ($('#contactname').val() == 'Required') {
        $('#contactname').val('');
    }

    if ($('#contactphone').val() == 'Required') {
        $('#contactphone').val('');
    }
}
