﻿
document.observe("dom:loaded", AddProduct);

var SelectedState = ''

function SubmitForm(Form) {
  var Succeeded

  var SubmitButton = $$('#SubmitContainer input[type=submit]')[0]
  SubmitButton.disabled = true

  new Ajax.Request('FormJSON.aspx?cmd=Submit',
	{
		method: 'post',
		parameters: $('RegistrationForm').serialize(true),
		asynchronous: false,
		onSuccess: function(t) {
			Response = t.responseText.evalJSON()

			ValidationTexts = $$('.ValidationMessage').each(function(x) {
				x.update();
				try {
					x.style.display = 'none'
				} catch (Error) { };
			});
			

			if (!Response.Success) {
				SubmitButton.disabled = false;
				$(Response.InputID).focus()
				$(Response.InputID).select()
				$('RegistrationForm').className = Response.InputID
				if (Response.Message.length)
					$(Response.InputID + 'Validation').innerHTML = Response.Message
				$(Response.InputID + 'Validation').style.display = 'inline'
			}

			if (Response.RedirectURL.length)
				document.location = decodeURI(Response.RedirectURL)
		}
	})

	return false
	
}

// ----------------------------------------------------------------------------

function GetStates(CountryID,State) {
  var Succeeded

  new Ajax.Request('FormJSON.aspx?cmd=GetStates&CountryID=' + CountryID,
	{
		method: 'post',
		asynchronous: false,
		onSuccess: function(t) {
			Response = t.responseText.evalJSON()
			$('Province').options.length = 0
			var Opt = document.createElement('option')
			$('Province').appendChild(Opt)
			for (var i in Response) {
				var Opt = document.createElement('option')
				Opt.value = i + '|' + Response[i]
				Opt.innerHTML = Response[i]

				// If the state is passed in (opt param), select the appropriate option
				if (typeof State != "undefined") {
					if (State == Opt.value)
						Opt.setAttribute('selected','selected')
				}

				$('Province').appendChild(Opt)
			}
		}
	})

  return Succeeded
}

// ----------------------------------------------------------------------------

function GetCities(StateID) {
  var Succeeded

  new Ajax.Request('FormJSON.aspx?cmd=GetCities&StateID=' + StateID,
	{
    method: 'post',
    asynchronous: false,
    onSuccess: function(t) {
      Response = t.responseText.evalJSON()
      $('City').options.length = 0
      var Opt = document.createElement('option')
      $('City').appendChild(Opt)
      for (var i in Response) {
        var Opt = document.createElement('option')
        Opt.value = i + '|' + Response[i]
        Opt.innerHTML = Response[i]
        $('City').appendChild(Opt)
      }
    }
	})

  return Succeeded
}

// ----------------------------------------------------------------------------

function AddProduct() {

	// Create an incrementing ID based on the number of existing registrations
	var RegID = parseInt($$('.ProductRegistration').length) + 1

	var SerialLabelText
	var SubmitButtonText
	var ProductCategoryLabelText
	var ProductIDLabelText
	var DealerCountryLabelText
	var DealerNameLabelText
	var DealerNameTypeInLabelText
	var PurchaseDateLabelText
    var PurchasePriceLabelText
    var SelectedCultureText
	
	// Get the translations for elements created on the page
	new Ajax.Request('FormJSON.aspx?cmd=GetAddProductTranslations',
	{
		method: 'post',
		asynchronous: false,
		onSuccess: function(t) {
			Response = t.responseText.evalJSON()
				
			SerialLabelText	 = Response.SerialLabelText
			SubmitButtonText = Response.SubmitButtonText
			ProductCategoryLabelText = Response.ProductCategoryLabelText
			ProductIDLabelText = Response.ProductIDLabelText
			DealerCountryLabelText = Response.DealerCountryLabelText
			DealerNameLabelText = Response.DealerNameLabelText
			DealerNameTypeInLabelText = Response.DealerNameTypeInLabelText
			PurchaseDateLabelText = Response.PurchaseDateLabelText
			PurchasePriceLabelText = Response.PurchasePriceLabelText
			SelectedCultureText = Response.SelectedCultureText			
		}
	})

	// Create the container (DIV) for the product
	var ProductDiv = new Element('div', { 'class': 'ProductRegistration', id: 'ProductRegistration_' + RegID })
	$('ProductList').insert(ProductDiv)

	// Delete Button
	if (RegID > 1) {
		ProductDiv.insert(DeleteButton = new Element('span', { 'class': 'DeleteButton' }));
		DeleteButton.observe('click', function() { $('ProductRegistration_' + RegID).remove() });
	}

	// Hidden marker
	ProductDiv.insert(new Element('input', {type:'hidden', value:'1', name:'Marker_' + RegID}));

	// Hidden SpecificProductID
	ProductDiv.insert(new Element('input', { type: 'hidden', name: 'ItemID_' + RegID, id: 'ItemID_' + RegID }));

	// Hidden SpecificProductID
	ProductDiv.insert(new Element('input', { value: '0', type: 'hidden', name: 'IsShown_' + RegID, id: 'IsShown_' + RegID }));

	// Create the container for the serial number input
	var SerialContainer = new Element('p');
	ProductDiv.insert(SerialContainer);

	// Serial number label
	SerialContainer.insert(new Element('label').update(SerialLabelText + ' *'))

	// Serial number input
	SerialContainer.insert(new Element('input', { type: 'text', name: 'ProductSerial_' + RegID, id: 'ProductSerial_' + RegID }));

	// Serial number submit button
	SerialContainer.insert(SubmitSerialButton = new Element('input', { type: 'button', value: SubmitButtonText, 'class': 'SubmitSerialButton' }));
	SubmitSerialButton.observe('click', function() { SendSerialNumber(this.previousSibling.value, RegID) });

	// Serial number validation message
	SerialContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'ProductSerial_' + RegID + 'Validation' }));

	// Serial number help
	SerialContainer.insert(SerialNumberHelp = new Element('img', { src: 'shared/images/help.png', 'class': 'HelpButton' }));
	SerialNumberHelp.observe('click', function() { window.open('instructions.aspx?Culture=' + SelectedCultureText, '_blank', 'height=800,width=650,location=no,menubar=no,resizable=yes,status=no,toolbar=no,scrollbars=yes') });

	// DIV to hold additional product details
	var SubProductDiv = new Element('div', { id: 'SubProductDiv_' + RegID });
	ProductDiv.insert(SubProductDiv);	
	
	// Create the container for the product categories
	var ProductCategoryContainer = new Element('p');
	SubProductDiv.insert(ProductCategoryContainer);

	// Product category label
	ProductCategoryContainer.insert(new Element('label').update(ProductCategoryLabelText + ' *'));

	// Product category SELECT
	ProductCategoryContainer.insert(ProductListSelect = new Element('select', { name: 'ProductCategory_' + RegID, id: 'ProductCategory_' + RegID }));
	ProductListSelect.observe('change', function() { SendProductCategory(this, RegID) });

	// Product category validation message
	ProductCategoryContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'ProductCategory_' + RegID + 'Validation' }));
	
	// Create the container for the product ID
	var ProductIDContainer = new Element('p');
	SubProductDiv.insert(ProductIDContainer);

	// Product ID label
	ProductIDContainer.insert(new Element('label').update(ProductIDLabelText + ' *'));

	// Product ID
	ProductIDContainer.insert(ProductSelect = new Element('select', { name: 'ProductID_' + RegID, id: 'ProductID_' + RegID }));
	ProductSelect.observe('change', function() { SelectProduct(this.value, RegID) });

	// Product ID validation message
	ProductIDContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'ProductID_' + RegID + 'Validation' }));

	// Container for dealer country
	var DealerCountryContainer = new Element('p');
	SubProductDiv.insert(DealerCountryContainer);

	// Dealer country label
	DealerCountryContainer.insert(new Element('label').update(DealerCountryLabelText + ' *'));

	// Dealer country
	DealerCountryContainer.insert(DealerCountry = new Element('select', { name: 'DealerCountry_' + RegID, id: 'DealerCountry_' + RegID }));
	DealerCountry.observe('change', function() { PopulateDealers(this.value, RegID) });

	// Dealer country validation message
	DealerCountryContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'DealerCountry_' + RegID + 'Validation' }));

	// Container for dealer name
	var DealerNameContainer = new Element('p')
	SubProductDiv.insert(DealerNameContainer)

	// Dealer name label
	DealerNameContainer.insert(new Element('label').update(DealerNameLabelText + ' *'));

	// Dealer name
	DealerNameContainer.insert(new Element('select', { name: 'DealerName_' + RegID, id: 'DealerName_' + RegID }));

	// Dealer name validation message
	DealerNameContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'DealerName_' + RegID + 'Validation' }));

	// Container for dealer type in name
	var DealerNameTypeInContainer = new Element('p');
	SubProductDiv.insert(DealerNameTypeInContainer);

	// Dealer name type in label
	DealerNameTypeInContainer.insert(new Element('label').update(DealerNameTypeInLabelText));

	// Dealer name type in
	DealerNameTypeInContainer.insert(new Element('input', { type: 'text', name: 'DealerNameTypeIn_' + RegID, id: 'DealerNameTypeIn_' + RegID }));

	// Container for purchase date
	var PurchaseDateContainer = new Element('p');
	SubProductDiv.insert(PurchaseDateContainer);

	// Purchase date label
	PurchaseDateContainer.insert(new Element('label').update(PurchaseDateLabelText + ' *'));
	
	// Purchase date
	PurchaseDateContainer.insert(PurchaseDate = new Element('input', { name: 'PurchaseDate_' + RegID, id: 'PurchaseDate_' + RegID, readonly: true }));

	// Add caledar control
	var dp_cal = new Epoch('epoch_popup', 'popup', PurchaseDate);
	dp_cal.updatePos(PurchaseDate)

	// Purchase date validation message
	PurchaseDateContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'PurchaseDate_' + RegID + 'Validation' }));

	// Container for purchase price
	var PurchasePriceContainer = new Element('p');
	SubProductDiv.insert(PurchasePriceContainer);

	// Purchase price label
	PurchasePriceContainer.insert(new Element('label').update(PurchasePriceLabelText + ' *'));

	// Purchase price
	PurchasePriceContainer.insert(new Element('input', { name: 'PurchasePrice_' + RegID, id: 'PurchasePrice_' + RegID }));

	// Purchase price validation message
	PurchasePriceContainer.insert(new Element('span', { 'class': 'ValidationMessage', id: 'PurchasePrice_' + RegID + 'Validation' }));
	
	// Enable the submit button container
	$('SubmitContainer').style.display = 'block';

	SubProductDiv.className = 'HiddenProduct';  //Added here for calendar compatability

}


// ----------------------------------------------------------------------------


function SendSerialNumber(SerialNumber,RegID) {

    var ProductTypeList
    var NumItems = 0

    new Ajax.Request('FormJSON.aspx?cmd=SendSerialNumber',
	{
	    method: 'post',
	    parameters: { SerialNumber: SerialNumber },
	    asynchronous: false,
	    onSuccess: function(t) {
	        Response = t.responseText.evalJSON()

	        if (Response.NoSerial == true) {
	            alert(Response.Message)
	            return false;
	        }

	        if (Response.Error == true) {
	            alert(Response.Message)
	            return false;
	        }

	        //clear serial number validation message, if any
	        $('ProductSerial_' + RegID + 'Validation').style.display = 'none'

	        $('SubProductDiv_' + RegID).className = 'ShownProduct'
	        $('IsShown_' + RegID).value = '1'

	        ProductListSelect = $('ProductCategory_' + RegID)
	        ProductListSelect.options.length = 0
	        $('ProductID_' + RegID).options.length = 0
	        $('DealerCountry_' + RegID).options.length = 0
	        $('DealerName_' + RegID).options.length = 0


	        for (var i in Response.Data) {
                NumItems++
	        }
	        
	        // Add a blank option if more than one choice is returned
	        if (NumItems > 1) {
	            var Opt = document.createElement('option')
	            Opt.value = '-1'
	            Opt.innerHTML = Response.ChooseProductType
	            ProductListSelect.appendChild(Opt)
	        }

	        for (var i in Response.Data) {
	            var Opt = document.createElement('option')
	            Opt.value = i
	            Opt.innerHTML = Response.Data[i]
	            ProductListSelect.appendChild(Opt)
	        }

	        // If only one choice was returned, trigger the onclick event
	        if (typeof (Response.Data[2]) == "undefined")
	            SendProductCategory(Opt, RegID)

	    }
	})

}

// ----------------------------------------------------------------------------

function SendProductCategory(senderElement, RegID) {
	new Ajax.Request('FormJSON.aspx?cmd=GetListOfProducts',
	{
		method: 'post',
		parameters: {
			ProductCategoryID: senderElement.value,
			SerialNumber: $('ProductSerial_' + RegID).value
		},
		asynchronous: false,
		onSuccess: function(t) {
			Response = t.responseText.evalJSON()

			var ResponseLength = 0
			for (var test in Response) {
				ResponseLength++
			}

			NewProductSelect = $('ProductID_' + RegID)
			NewProductSelect.options.length = 0

			//clear product category validation message, if any
			$('ProductCategory_' + RegID + 'Validation').style.display = 'none'

			$('DealerCountry_' + RegID).options.length = 0
			$('DealerName_' + RegID).options.length = 0

			// If more than one item as received in the Response, show an empty OPTION tag
			if (ResponseLength > 1) {
			    var Opt = document.createElement('option')
			    Opt.value = '-1|'
				NewProductSelect.appendChild(Opt)
			}

			for (var i in Response) {
				var Opt = document.createElement('option')
				Opt.value = i + '|' + Response[i]
				Opt.innerHTML = Response[i]
				NewProductSelect.appendChild(Opt)
			}

			// If only one item was received, trigger the onclick function
			if (ResponseLength == 1)
				SelectProduct(Opt.value, RegID)

		}
	})

}

// ----------------------------------------------------------------------------


function SelectProduct(ProductID, RegID) {
	new Ajax.Request('FormJSON.aspx?cmd=GetDealer',
	{
		method: 'post',
		parameters: {
			ModelID: $('ProductID_' + RegID).value,
			SerialNumber: $('ProductSerial_' + RegID).value
		},
		asynchronous: false,
		onSuccess: function(t) {
		Response = t.responseText.evalJSON()

			//Set the hidden form field
			if (Response.ItemID != undefined)
				$('ItemID_' + RegID).value = Response.ItemID

            //clear product ID validation message, if any
            $('ProductID_' + RegID + 'Validation').style.display = 'none'

			var DealerCountrySelect = $('DealerCountry_' + RegID)

			// Populate the dealer country drop-down
			for (var i in Response.DealerCountries) {
				var Opt = document.createElement('option')
				Opt.value = i
				if (parseInt(Response.SelectedCountry) == parseInt(i)) Opt.selected = true
				Opt.innerHTML = Response.DealerCountries[i]
				DealerCountrySelect.appendChild(Opt)
			}

			if (Response.Dealer.DealerName != undefined) {

				var DealerNameSelect = $('DealerName_' + RegID)	
				
					var Opt = document.createElement('option')
					Opt.value = Response.Dealer.DealerID + '|' + Response.Dealer.DealerName
					Opt.innerHTML = Response.Dealer.DealerName 
					DealerNameSelect.appendChild(Opt)

			}


		}
	})
}


// ----------------------------------------------------------------------------


function PopulateDealers(CountryCode3, RegID) {

	new Ajax.Request('FormJSON.aspx?cmd=GetDealersByCountry',
	{
		method: 'post',
		parameters: { CountryCode3: CountryCode3},
		asynchronous: false,
		onSuccess: function(t) {
			Response = t.responseText.evalJSON()

			ProductListSelect = $('DealerName_' + RegID)
			ProductListSelect.options.length = 0

			//clear dealer country validation message, if any
			$('DealerCountry_' + RegID + 'Validation').style.display = 'none'

			// Add a blank option
			var Opt = document.createElement('option')
			ProductListSelect.appendChild(Opt)

			for (var i in Response) {
				var Opt = document.createElement('option')
				Opt.value = i + '|' + Response[i]
				Opt.innerHTML = Response[i]
				ProductListSelect.appendChild(Opt)
			}

		}
	})


}
