// © Copyright APRA Limited 2007. All rights reserved.
// Javascript specific to Production Music.

// This flag is set to true when an Ajax call is made, and set to false on the receipt of the response.
var awaitingResponse = false;


var rateCalcHelpWin;

function openRateCalcHelpWindow() {
	rateCalcHelpWin = window.open('RateCalculationHelp.action?openRateCalcHelpWindow','rateCalcHelpWin','scrollbars=yes,height=700,width=800,left=50,top=0');
	rateCalcHelpWin.focus();
}

function calculateAmtLicenceAgreed() {

	var amtLicenceAgreed = document.getElementById("amtlicenceagreed");
	var feeValue = document.getElementById("cdfee").value;
	var amtCalculatedValue = document.getElementById("amtCalculated").value;
	var newValue;	

	var discountPercent = document.getElementById("discountPercent");
	if (feeValue == "S") {
		newValue = isNaN(amtCalculatedValue) ? "" : amtCalculatedValue
		discountPercent.value = "0.00"
	} else if ((feeValue == "T") || (feeValue == "C")) {
		var discountPercentValue = discountPercent.value;
		newValue = isNaN(discountPercentValue) ? "" : amtCalculatedValue - ( amtCalculatedValue * discountPercentValue / 100 );
		
	} else if (feeValue == "A") {
		var unitFeeValue = document.getElementById("unitFee").value;
		var noUnitsValue = document.getElementById("noUnitsHidden").value;
		
		// Remove any dollar signs.
		unitFeeValue = (unitFeeValue + "").replace(/[,%\$]/g,""); 
		newValue = 0;
		newValue = unitFeeValue * noUnitsValue;
	} else if (feeValue == "B") {
		newValue = amtLicenceAgreed.value;
	} else {
		newValue = "";
	}

	if (! amtLicenceAgreed.readOnly) {
		// Remove any dollar signs.
		newValue = (newValue + "").replace(/[,%\$]/g,""); 
	} else {
		newValue = formatCurrency(newValue);
	}

	amtLicenceAgreed.value = newValue;
}

function calculateDiscountPercent() {

	// Manage the discount percentage.
	var discountPercent = document.getElementById("discountPercent");
	var feeValue = document.getElementById("cdfee").value;
	
	if (feeValue == "S" || feeValue == "A" || feeValue == "B" ) {
		// Clear the discount field and disable it.
		discountPercent.value = "0.00";
		disableField(discountPercent);
	} else if (feeValue == "T") {
		// Set the discount field to 50% and disable it.
		discountPercent.value = "50.00";
		disableField(discountPercent);
	} else if (feeValue == "C") {
		/* 
		If the fee value is "C"ampaign, the discount percentage is calculated based on the first of three values 
		to be found to be greater than zero (in this order):
		
			* noVersions (if it is greater than 1)
			* number of key numbers
			* number or works (if there are no key numbers)
		
		Regardless of which of the above fields in which the value is found, the discount percent will be set as follows:
			
			Value	Resulting Percentage
			4-6			20
			7-9			25
			10+			30
		*/
		var decidingValue;
		var newDiscountValue;			
		var noVersions = document.getElementById("noVersions");
		
		if (noVersions.value > 1) {
			decidingValue = noVersions.value;
		}

		if (4 == decidingValue || 5 == decidingValue || 6 == decidingValue ) {
			newDiscountValue = "20.00";
		} else if (7 == decidingValue || 8 == decidingValue || 9 == decidingValue ) {
			newDiscountValue = "25.00";
		} else if (decidingValue >= 10 ) {
			newDiscountValue = "30.00";
		} else {
			newDiscountValue = "0.00";
		}

		// Set the discount field and enable it.
		discountPercent.value = newDiscountValue;

		disableField(discountPercent);		
	}
		
}

function calculateUnitFee() {
	var feeValue = document.getElementById("cdfee").value;
	var newValue;
	var unitFee = document.getElementById("unitFee");
	var noUnitsValue = document.getElementById("noUnitsHidden").value;						
	var amtLicenceAgreedValue = document.getElementById("amtlicenceagreed").value;

	// Remove any dollar signs.
	amtLicenceAgreedValue = (amtLicenceAgreedValue + "").replace(/[,%\$]/g,""); 
	
	// determine the fee per unit
	newValue = amtLicenceAgreedValue / noUnitsValue;
	newValue = formatCurrency(newValue);
	unitFee.value = newValue;
}

function calculateStandardFee() {
	// To calculate the standard fee we require the licence code, the territory, and the total units.
	// If they are all present, do an AJAX call to calculate the standard fee.
	// If they are not all present, set the standard fee field to $0.00
	var territory = document.getElementById("territory").value.replace(/^\s+|\s+$/g,"");
	var tariff = document.getElementById("licencecode").value;
	var totalUnits = document.getElementById("noUnitsHidden").value;
	var standardFee = document.getElementById("standardFee");
	var standardFeeHidden = document.getElementById("standardFeeHidden");
	var originalStandardFee = standardFee.innerHTML;
	var feeNotKnown = "Not&nbsp;known";

	// amtCalculated is the hidden field behind standardFee.
	var amtCalculated = document.getElementById("amtCalculated");

	if (territory.length > 0 && tariff.length > 0 && totalUnits > 0) {

		// alert("Calculating standard fee for territory [" + territory + "] and licence code [" + tariff + "] and total units [" + totalUnits + "]. Original value was [" + originalStandardFee + "].");
		
		awaitingResponse = true;

		standardFee.innerHTML = "Calculating...";

	    var params = Form.serialize(document.ratecalculationform);    
	 	params = "calculateStandardFee" + "&" + params;
		
		// Get the Javascript from the server to repopulate the select.
		new Ajax.Request(document.ratecalculationform.action,
			{
			    method:'post',
			    postBody:params,
			    onSuccess: function(transport){
					var response = transport.responseText || "0.00";
					var evalresponse = eval(response);
					awaitingResponse = false;							
					
					calculateAmtLicenceAgreed();	
					
					calculateUnitFee();
					
			    },
			    onFailure: function(){ 
			    	alert('A problem occurred while calculating the standard fee for this sales detail.  You might like to try again.');	
			    	standardFee.innerHTML = originalStandardFee;
			    	standardFeeHidden.value = 0;
			    	amtCalculated.value = "";
			    	awaitingResponse = false; 
			    	
			    	calculateAmtLicenceAgreed();
			    }
			  });		
		
	} else {
		standardFee.innerHTML = feeNotKnown;
		standardFeeHidden.value = 0;
		amtCalculated.value = "";
		calculateAmtLicenceAgreed();
	}
}

function categoryChanged(){

	// clear out licence code, standard fee and agreed licence amt
	document.getElementById("licencecode").value = "";
	
	document.getElementById("noVersions").value = "0";
	document.getElementById("noUnitsHidden").value = "0";
	document.getElementById("unitFee").value = "";
	discountPercent = document.getElementById("discountPercent").value = "";
	amtCalculated = document.getElementById("amtCalculated").value ="";
	
	document.getElementById("amtlicenceagreed").value = "";
	document.getElementById("standardFee").innerHTML = "&nbsp;";
	
	// Clear out the sectors option box.
	var sectors = document.getElementById("sector");
	while (sectors.options.length > 0) {
		sectors.removeChild(sectors.options[0]);
	}

	// Clear out the usages option box.
	var usages = document.getElementById("usage");
	while (usages.options.length > 0) {
		usages.removeChild(usages.options[0]);
	}
	
	// Clear out the fee type option box.
	var fees = document.getElementById("cdfee");
	while (fees.options.length > 0) {
		fees.removeChild(fees.options[0]);
	}
	
	// if no Country entered so do not retrieve the sector and usage.
	var countryFieldOptions = document.getElementById("countryField").options;	
	var countryFieldValue = countryFieldOptions[countryFieldOptions.selectedIndex].value;	
	
	if ( countryFieldValue == null || countryFieldValue == "" ) {
		return;
	}
	
	// if the type of productionhas not been entered do not retrieve the sector and usage.
	var typeOfProductionOptions = document.getElementById("typeOfProduction").options;	
	var typeOfProductionValue = typeOfProductionOptions[typeOfProductionOptions.selectedIndex].value;	
	
	if ( typeOfProductionValue == null || typeOfProductionValue == "" ) {
		return;
	}
	
	var transferDateValue =  document.getElementById("transferDate").value
	if ( transferDateValue == null || transferDateValue == "" ) {
		return;
	}
	

    var params = Form.serialize(document.ratecalculationform);    
 	// params = "calculateStandardFee" + "&" + params;	 	
 	params = "loadSectorUsageAjax" + "&" + params;
	
	// Get the Javascript from the server to repopulate the select.
	new Ajax.Request(document.ratecalculationform.action,
		{
		    method:'post',
		    postBody:params,
		    onSuccess: function(transport){
				var response = transport.responseText || "0.00";
				var evalresponse = eval(response);
				awaitingResponse = false;							
				
		    },
		    onFailure: function(){ 
		    	alert('A problem occurred while loadind the Sector and Usage.  You might like to try again.');	
		    	standardFee.innerHTML = originalStandardFee;
		    	standardFeeHidden.value = 0;
		    	amtCalculated.value = "";
		    	awaitingResponse = false; 
		    }
		  });
			  
	  prepareForm("1");
	  manageNoOfVersions();
}


function checkSubmitOk() {
	// Checks whether it is OK to submit the form, usually by determining whether an Ajax request is in progress.
	if (isAwaitingResponse()) {
		alert("The system is awaiting a response from the server, and cannot process your request at the moment.  Click the OK button in a couple of seconds to try your command again.");
	}
	return ! isAwaitingResponse();
}


function clearAll(){
	// clear out all fields
	document.getElementById("countryField").options.selectedIndex = 0;
	document.getElementById("typeOfProduction").options.selectedIndex = 0;
	document.getElementById("transferDate").value = ""
	document.getElementById("licencecode").value = "";	
	document.getElementById("noVersions").value = "0";
	document.getElementById("noUnitsHidden").value = "0";
	document.getElementById("unitFee").value = "";
	discountPercent = document.getElementById("discountPercent").value = "";
	amtCalculated = document.getElementById("amtCalculated").value ="";	
	document.getElementById("amtlicenceagreed").value = "";
	document.getElementById("standardFee").innerHTML = "&nbsp;";
	
	// Clear out the sectors option box.
	var sectors = document.getElementById("sector");
	while (sectors.options.length > 0) {
		sectors.removeChild(sectors.options[0]);
	}

	// Clear out the usages option box.
	var usages = document.getElementById("usage");
	while (usages.options.length > 0) {
		usages.removeChild(usages.options[0]);
	}
	
	// Clear out the fee type option box.
	var fees = document.getElementById("cdfee");
	while (fees.options.length > 0) {
		fees.removeChild(fees.options[0]);
	}
	
}

function clearField(field) {
	field.value = "";
}



function disableField(field) {
	field.className = "data";
	field.readOnly = true;
}

function discountPercentChanged() {
	calculateAmtLicenceAgreed();
}

function enableField(field, isMandatory) {
	isMandatory ? field.className = "mandatory" : field.className = ""; 
	field.readOnly = false;
}

function feeChanged() {
	var newValue = document.getElementById("cdfee").value;
	var unitFee = document.getElementById("unitFee");
	var noVersions = document.getElementById("noVersions");
	var	amtLicenceAgreed = document.getElementById("amtlicenceagreed");
	var noUnitsValue = document.getElementById("noUnitsHidden").value;
	var amtLicenceAgreedValue = document.getElementById("amtlicenceagreed").value;
		
	if (newValue == "A") {
		// Unit Fee Agreed
		enableField(unitFee, true);
		disableField(amtLicenceAgreed)
		// If Unit Fee Agreed, calculate the unit fee.
		
		// Remove any dollar signs.
		amtLicenceAgreedValue = (amtLicenceAgreedValue + "").replace(/[,%\$]/g,""); 
		
		
		try {unitFee.value = formatCurrency(amtLicenceAgreedValue / noUnitsValue);}catch(e){}
		// Quote becomes mandatory
		document.getElementById("quote").className = "mandatory";
	} else if (newValue == "B") {
		// Prod Fee Agreed
		disableField(unitFee);
		enableField(amtLicenceAgreed, true)
		// Quote becomes mandatory
		document.getElementById("quote").className = "mandatory";
	} else {
		disableField(unitFee);
		disableField(amtLicenceAgreed);
		// Quote becomes non-mandatory
		document.getElementById("discountPercent").value = "0.00";		
	}
	
	// Clear the unit fee if the type is not Unit Fee Agreed.
	if (newValue != "A") {
		unitFee.value = "";
	}
	
	if (newValue == "C" || newValue == "T" ) {
		enableField(noVersions, true);
		calculateDiscountPercent();
	} else {
		// noVersions.value = "1";
		// disableField(noVersions);
		var prodNoUnits = document.getElementById("noUnitsHidden");		
		if ( prodNoUnits !== null ) {
			var prodNoUnitsValue = document.getElementById("noUnitsHidden").value;		
			var noUnits = document.getElementById("noUnits");
			var totalUnits = document.getElementById("noUnitsHidden");
			var discountPercent = document.getElementById("discountPercent");
			
					
			//noUnits.innerHTML = prodNoUnitsValue;		
			//totalUnits.value = prodNoUnitsValue;
			discountPercent.value = 0.00;
			calculateStandardFee();
			calculateUnitFee();
		} 
		
		
		return;
	}	


	// Calculate the amt licence agreed.
	calculateAmtLicenceAgreed();

	calculateUnitFee();
}

function getNewSalesDetail() {
	location.href='/cms/productionmusic/LicenceApplication.action?newSalesDetail=&_sourcePage=/productionmusic/salesdetails.jsp';
	return;
}

function isAwaitingResponse() {
	// Check whether an Ajax request is in progress. 
	return awaitingResponse;
}

function licenceCodeChanged() {
	// Uppercase and trim the licence code.
	document.getElementById("licencecode").value = document.getElementById("licencecode").value.toUpperCase().replace(/^\s+|\s+$/g,"");
	selectCorrespondingSector();		
	selectCorrespondingUsage();
	repopulateTerritories();
	manageNoOfVersions();
	// manageNoOfUnits();
	calculateStandardFee();
}

function limitUsage(type) {
	// Uppercase and trim the string.
	if (type.length > 0) {
		type = type.toUpperCase().replace(/^\s+|\s+$/g,"");
	}

	// Rebuild the select.
	//rebuildUsages();

	// Hide all the usages except for those prefixed by the argument, type.
	var usage = document.getElementById("usage");
	var usageOptions = usage.options;

	// Only hide all the "wrong" ones if there's a least one "right" one.
	// Otherwise the list will empty if the user types an invalid code.
	// We want it to slim down to valid usages for the code we're given.
	// This will require two passes through the list.

	if ( type.length > 0 ) {
		var inputTypeIsValid = false;

		for (var i = 0; i < usageOptions.length; i++ ) {
			if ( usageOptions[i].value.indexOf(type) == 0 ) {
				inputTypeIsValid = true;
			}
		}

		if (inputTypeIsValid) {
			// Remove invalid usage types if possible, but leave any blank options.
			for (var i = 0; i < usageOptions.length; i++ ) {	
				if ( ! usageOptions[i].value.indexOf(type) == 0 && usageOptions[i].value != " ") {
					usage.removeChild(usageOptions[i]);
					i--;
				}
			}	
			
		} else {
			alert ("This is not a valid Licence Code.  Please try again.");
			setTimeout("document.getElementById(\"licencecode\").focus()", 1);
			setTimeout("document.getElementById(\"licencecode\").select()", 1);
		}
	} 
}

function manageNoOfVersions() {
	var numberOfVersions = document.getElementById("noVersions");

	var typeProductionOptions = document.getElementById("typeOfProduction").options;
	var typeProductionValue = typeProductionOptions[typeProductionOptions.selectedIndex].value;	
	
	if ( typeProductionValue == "AD" ){
		// Enable the Number of Versions field if the licence code is Advertising.
		enableField(numberOfVersions, true);
	} else {
		// Disable the Number of Versions field if the licence code is not Advertising, and reset it to the value 1.
		numberOfVersions.value = 1;
		noVersionsChanged();
		disableField(numberOfVersions);		
	}
}

function noUnitsChanged() {
	calculateStandardFee();
}

function noVersionsChanged() {
	// Number of units = PMSD noVersions * Production noUnits.
	// This means if the number of versions changes, the number of units must be recalculated.
	var pmsdNoVersions = document.getElementById("noVersions").value;
	var productionNoUnits = document.getElementById("productionUnits");
	var productionNoUnitsValue = 0;
	
	if ( productionNoUnits != null ) {
		var productionNoUnitsValue = document.getElementById("productionUnits").value;
		var noUnits = pmsdNoVersions * productionNoUnits;
	
		if (isNaN(noUnits)) {
			noUnits = "0.00";
		}	
		
		document.getElementById("noUnitsHidden").value = noUnits;
		document.getElementById("noUnits").innerHTML = noUnits;
	} else {
		var productionNoUnitsValue = document.getElementById("noUnitsHidden").value;
		var noUnits = pmsdNoVersions * productionNoUnitsValue;
	
		if (isNaN(noUnits)) {
			noUnits = "0.00";
		}	
		
		document.getElementById("noUnitsHidden").value = noUnits;
	
	}
	
	
	
	noUnitsChanged();
	
	calculateDiscountPercent();
	calculateUnitFee();
}

function prepareForm(cdStatus) {

	if ( cdStatus != "1" ) {
		var countryFieldOptions = document.getElementById("countryField").options;
		countryFieldOptions.selectedIndex = 0;
		
		var typeOfProductionOptions = document.getElementById("typeOfProduction").options;
		typeOfProductionOptions.selectedIndex = 0;
	}

	var licencecode = document.getElementById("licencecode");
	disableField(licencecode)
	
	feeChanged();
	selectCorrespondingUsage();
	selectCorrespondingSector();
	
	var discountPercent = document.getElementById("discountPercent");	
	disableField(discountPercent);	
	
	 manageNoOfVersions();
	// manageNoOfUnits();
		
	repopulateTerritories();			
}

function rebuildUsages() {	
	var usage = document.getElementById("usage");
	var usageOptions = usage.options;

	usage.style.visibility = "hidden";
	
	while (usageOptions.length > 0) {
		usage.removeChild(usageOptions[0]);
	}

	// Add a blank option at the start.
	var blankOption = new Option (" ");
	blankOption.value = " ";
	usage.options[0] = blankOption;

	for (var i = 1; i <  usageCodes.length; i++ ) {
		var newOption = new Option (usageValues[i]);
		newOption.value = usageCodes[i];		
		usage.options[usageOptions.length] = newOption;
	}
	
	
	usage.style.visibility = "visible";
	
	var licenceCodeValue = document.getElementById("licencecode").value;
	usage.value = licenceCodeValue;
}

function repopulateTerritories() {

	var licenceCode = document.getElementById("licencecode").value.toUpperCase();

	// Clear out the territories box.
	var territories = document.getElementById("territory");
	while (territories.options.length > 0) {
		territories.removeChild(territories.options[0]);
	}
	// Add a "Loading..." option to cover us while we're ajaxing.
	territories.options[0] = new Option("Loading...", "" );

	// If the usage field is disabled, a valid licence code has been selected.
	// If both Sector and Usage has a value then reload the territory.
	var sectorsOption = document.getElementById("sector").options;
	var usagesOptions = document.getElementById("usage").options;
	var sectorsSelectedIndex = sectorsOption.selectedIndex;
	var usagesSelectedIndex = usagesOptions.selectedIndex;
	
	//if (document.getElementById("usage").readOnly) {
	if ( sectorsSelectedIndex > 0 &&  usagesSelectedIndex > 0 ) {

		awaitingResponse = true;

	    var params = Form.serialize(document.ratecalculationform);    
	 	params = "reloadTerritoryList" + "&" + params;
		
		// Get the Javascript from the server to repopulate the select.
		new Ajax.Request(document.ratecalculationform.action,
			{
			    method:'post',
			    postBody:params,
			    onSuccess: function(transport){
					var response = transport.responseText || "No valid territories were found";
					// Remove the "Loading..." option.
					territories.removeChild(territories.options[0]);
					var evalresponse = eval(response);
					awaitingResponse = false;							
			    },
			    onFailure: function(){ 
			    	alert('A problem occurred while updating territories for your new licence code.  You might like to try again.');	
			    	awaitingResponse = false; 
			    }
			  });
		
	} else {
		// Add a blank option.
		territories.options[0] = new Option("Select the Sector and Usage first", "" );
	}
}

function searchForProduction() {
	searchString = document.getElementById("searchTitle").value;
	var formAction;

	// If the search title is empty, list all the productions for the user.
	if (searchString.length > 0) {
		formAction = "/cms/productionmusic/SearchProduction.action?listProductionsByTitle&searchTitle=" + searchString + "&_sourcePage=/productionmusic/salesdetails.jsp";
	} else {
		formAction = "/cms/productionmusic/SearchProduction.action?listAllYourProductions&_sourcePage=/productionmusic/salesdetails.jsp";
	}
	
	document.ratecalculationform.action = formAction;
	document.ratecalculationform.submit();
	
	return;
}

function sectorChanged() {
	var sector = document.getElementById("sector");
	var licenceCode = document.getElementById("licencecode");
	var licenceCodeValue = licenceCode.value.toUpperCase().replace(/^\s+|\s+$/g,"");
	
	var sectorValue = "";
	if ( sector.selectedIndex > 0 ) {
		sectorValue = sector.options[sector.selectedIndex].value;
	}

	// Set the licence code field to the code of the sector dropdown if necessary.
	if (licenceCodeValue.charAt(0) != sectorValue && sectorValue != " ") {
		licenceCode.value = sector.options[sector.selectedIndex].value;		
	}	
	// Limit the usages list to the new sector code.
	limitUsage(licenceCode.value);
	
	// If sector is changed to Advertisement, reset number of versions to 1.
	// Commented out, as this code is firing on page load, overridding the values from the database.
	//if (sectorValue == "A") {
	//	document.getElementById("noVersions").value = 1;
	//	noVersionsChanged();
	//	manageNoOfVersions();
	//}
}

function selectCorrespondingSector() {
	var sector = document.getElementById("sector");
	var sectorOptions = sector.options;
	var sectorOptionFound = false;

	var licenceCode = document.getElementById("licencecode");
	var newValue = licenceCode.value.toUpperCase().replace(/^\s+|\s+$/g,"");

	// Select a corresponding sector if possible, using only
	// the first character of the licence code's value (the sector
	// code is a single character).
	var firstCharacter = newValue.charAt(0);

	for (var i = 0; i < sectorOptions.length; i++ ) {
		if (sectorOptions[i].value == firstCharacter) {
			sector.selectedIndex = i;
			// Disable the sector field.
			//disableField(sector);
			//sector.disabled = true;
			//sector.className = "disabledSelect";
			// Limit the usages to the selected sector, based on the
			// first three characters of the new value, not just the first character.
			sectorOptionFound = true;
			break;
		}
	}

//	if (! sectorOptionFound) {
//		sector.selectedIndex = 0;
//		enableField(sector, true);
//		sector.disabled = false;
//	} 	
	
	sectorChanged();
}

function selectCorrespondingUsage() {
	var usage = document.getElementById("usage");
	var usageOptions = usage.options;
	var usageOptionFound = false;

	var licenceCode = document.getElementById("licencecode");
	var newValue = licenceCode.value.toUpperCase().replace(/^\s+|\s+$/g,"");

	// Select a corresponding usage type to the licence code, if possible.
	// If the usage matches the current licence code, select it
	// and disable the usage box.
	
	// If there is no match, progressively take a character off
	// the end and look again.
	
	for (var i = 0; i < usageOptions.length; i++ ) {
		if (usageOptions[i].value == newValue) {
			usage.selectedIndex = i;
			usageOptionFound = true;
			// Disable the usage field.
			//disableField(usage);
			//usage.disabled = true;
			//usage.className = "disabledSelect";
			break;
		}
	}
	
//	if (! usageOptionFound) {
//		usage.selectedIndex = 0;
//		enableField(usage, true);
//		usage.disabled = false;
//	} 
}

function territoryChanged() {
	calculateStandardFee();
}

function unitFeeChanged() {
	calculateAmtLicenceAgreed();
}

function usageChanged() {
	var usage = document.getElementById("usage");
	var licenceCode = document.getElementById("licencecode");
	var newValue = usage.value;
	licenceCode.value = newValue;	
	licenceCodeChanged();
}