﻿//Note:	MClient object (used below) is declared in MCVClient.Master.
//		It is the ChiltonsOnline MVC javascript client API
//*****************
//General use functions and vars
//*****************

var parentSelector = "#indexYears";

this.getBaseUrl = function() {
	switch (this.environment) {
		case "dev":
			return "http://nyalbchilton01/CL.Chilton.DIY.Web/";
		case "local":
			return "http://localhost/CL.Chilton.DIY.Web/";
		default:
			return (this.location.protocol + '//' + this.location.host + '/');
	}
}

var defaultOption = '<option value="-1">(Select)</option>';

function callDiyService(methodName, inputObject, successCallback, errorCallback) {
    var input = null;
    if (!(inputObject === undefined)) {
        input = jQuery.param(inputObject);
    }
    
    $.ajax(
		{
		    url: getBaseUrl() + "DIY.asmx/" + methodName,
		    success: successCallback,
		    error: errorCallback,
		    data: input,
		    type: "GET",
		    dataType: "json",
		    contentType: "application/json"
		}
	);
}

//var defaultOption = '<option value="-1">(Select)</option>';

//function callDiyService(methodName, inputObject, successCallback, errorCallback) {
//    var basedir = document.location.href;
//    basedir = basedir.substring(0, basedir.lastIndexOf('/')) + '/';
//	var input = null;
//	if (!(inputObject === undefined)) {
//		input = jQuery.param(inputObject);
//	}

//	$.ajax(
//		{
//			url: basedir + "DIY.asmx/" + methodName,
//			success: successCallback,
//			error: errorCallback,
//			data: input,
//			type: "GET",
//			dataType: "json",
//			contentType: "application/json"
//		}
//	);
//}

function getSelectedOptionValue(selectSelector) {
	return $(parentSelector).find(selectSelector + " :selected").attr("value");
}

function fillOptions(data, selectId, keyPropertyName, valuePropertyName) {
	var output = [];
	output.push(defaultOption);

	for (var i = 0; i < data.d.length; i++) {
		output.push('<option value="' + data.d[i][keyPropertyName] + '">' + data.d[i][valuePropertyName] + '</option>');
	}

	$(parentSelector).find(selectId).html(output.join(''));
}

function clearOptions(selectors) {
	$(parentSelector).find(selectors)
		.find('option')
		.remove()
		.end()
		.append('<option value="-1">(Select)</option>')
		.val('-1');
}

function able(selector, enable) {
	if (enable) {
		$(parentSelector).find(selector).removeAttr('disabled');
	} else {
	    $(parentSelector).find(selector).attr('disabled', 'disabled');
	}
}

//*****************
//Login functions
//*****************
function initLoginUI() {
	//Button source images, get from ChiltonsOnline MVC client:
	//alert("MClient.getThemeBaseUrl() returned: " + MClient.getThemeBaseUrl());
	
	$("#diy_login_button").attr("src", MClient.getThemeBaseUrl() + "images/btn-login.jpg");
	$("#diy_register_button").attr("src", MClient.getThemeBaseUrl() + "images/btn-register.png");
	$("#diy_additional_products").attr("src", MClient.getThemeBaseUrl() + "images/additional-products.png");
	$("#diy_screenshot").attr("src", MClient.getThemeBaseUrl() + "images/diy-screen.jpg");
	
	$('#diy_login_user, #diy_login_pw').keyup(function (e) { //login on enter key hit in user or pw field
		if (e.keyCode == 13) {
			$("#diy_login_button").click();
		}
	});

	$('#diy_login_button').keydown(function(e) { //login on enter key hit on button (doesn't work)
		if (e.keyCode == 13) {
			$("#diy_login_button").click();
		}
	});
}

function doLogin() {
	var UserName = q($("#diy_login_user").val());
	var Password = q($("#diy_login_pw").val());
	callDiyService("Login", { UserName: UserName, Password: Password, CallerPageClassName: q("Index") }, onLoginCallSuccess, onLoginCallFailure);
}

function q(input) {
	if (input) {
		return "\"" + input + "\"";
	} else {
		return "\"\"";
	}
}

function onLoginCallSuccess(WebResultArgs) {
	if (WebResultArgs.d.Code != 0) {
		$("#diy_login_message").text("");
		onLoginCallFailure(WebResultArgs);
	} else {
		$("#diy_login_error_message").text("");
		if (WebResultArgs.d.ShouldRedirect) {
			$("#diy_login_message").text("Redirecting...");
			location.href = WebResultArgs.d.RedirectUrl;
		} else {
			$("#diy_login_message").text(WebResultArgs.d.Message);
		}
	}
}

function onLoginCallFailure(WebResultArgs) {
	var Message = "";

	if (WebResultArgs.d) {
		Message = WebResultArgs.d.Message;
	} else {
		Message = WebResultArgs.responseText;
	}
	
	$("#diy_login_error_message").text(Message);
}

//*****************
//Vehicle selector functions
//*****************
function initVehicleSelectorUI() {
    parentSelector = "#indexYears";
	able("input[name='diy_price_choice'], .diy_choose_vehicle, .diy_year_select, .diy_make_select, .diy_model_select", true);

    
	$(".diy_year_select").change(
		function() {
			var year = getSelectedOptionValue(".diy_year_select");
			
			if (year != "-1") {
				getMakes(getSelectedOptionValue(".diy_year_select"));
			} else {
				clearOptions(".diy_make_select, .diy_model_select");
				able("input[name='diy_price_choice'], .diy_choose_vehicle", false);
			}
		}
	);

	$(".diy_make_select").change(
		function() {			
			var year = getSelectedOptionValue(".diy_year_select");
			var make = getSelectedOptionValue(".diy_make_select");
			
			if (year != "-1" && make != "-1") {
				getModels(year, make);
			} else {
				clearOptions(".diy_model_select");
				able("input[name='diy_price_choice'], .diy_choose_vehicle", false);
			}
		}
	);

	$(".diy_model_select").change(
		function() {
			if (getSelectedOptionValue(".diy_model_select") != "-1") {
				able("input[name='diy_price_choice'], .diy_choose_vehicle", true);
			} else {
				able("input[name='diy_price_choice'], .diy_choose_vehicle", false);
			}
		}
	);

	able("input[name='diy_price_choice'], .diy_choose_vehicle", false);
	getYears();
}

function getYears() {
    callDiyService("GetYearList", undefined, onGetYearsCallSuccess, onCcdCallFailure);
}

function onGetYearsCallSuccess(data, textStatus, xhr) {
    fillOptions(data, ".diy_year_select", "YearId", "YearId");
	clearOptions(".diy_make_select, .diy_model_select");
}

function getMakes(year) {
    $(parentSelector).find(".diy_make_select :selected").text("Loading makes...");
	able("input[name='diy_price_choice'], .diy_choose_vehicle", false);
	callDiyService("GetMakeList", { YearId: year }, onGetMakesCallSuccess, onCcdCallFailure);
}

function onGetMakesCallSuccess(data, textStatus, xhr) {
	fillOptions(data, ".diy_make_select", "MakeId", "MakeName");
}

function onCcdCallFailure(xhr) {
	alert("Unexpected service call error: " + xhr.statusText + "\n\nDetails:\n\n" + xhr.responseText);
}

function getModels(year, make) {
	$(parentSelector).find(".diy_model_select :selected").text("Loading models...");
	able("input[name='diy_price_choice'], .diy_choose_vehicle", false);
	callDiyService("GetModelList", { YearId: year, MakeId: make }, onGetModelsCallSuccess, onCcdCallFailure);
}

function onGetModelsCallSuccess(data, textStatus, xhr) {
	fillOptions(data, ".diy_model_select", "ModelId", "ModelName");
}

function doSelectVehicle() {
	var year = getSelectedOptionValue(".diy_year_select");
	var make = getSelectedOptionValue(".diy_make_select");
	var model = getSelectedOptionValue(".diy_model_select");
	callDiyService("GetBaseVehicleId", { YearId: year, MakeId: make, ModelId: model }, onGetBVCallSuccess, onCcdCallFailure);
}

function onGetBVCallSuccess(data, textStatus, xhr) {
	if (data.d) {
		$(".diy_choose_vehicle").val("Redirecting...");
		able("input[name='diy_price_choice'], .diy_choose_vehicle, .diy_year_select, .diy_make_select, .diy_model_select", false);
		var newLoc = 'pub/vehicle_detail.aspx?b=' + data.d;		
		location.href = newLoc;
	} else {
		alert("Error: Could not find the requested vehicle.");
	}
}
