/*******************************************************
 * Javascript Quotation functions
 * Used along the quotation process
 *******************************************************/

function FormatNumber(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}

	function blockTargetLanguage(frm, sourceLang) {
		for(var i=0; i < frm.targetlang.length; i++){
			if(frm.targetlang[i].value == sourceLang) {
				frm.targetlang[i].checked = false;
			}
		}
		buildTranslationParamsHtml(frm, 'paramsContainer');
	}

	function checkTargetLanguagueSelection(frm, targetElement) {

	    var sourceLang = parseInt(frm.iqFrom1_lang.value);

	    $$('.targetLangs').each(function(e){

            if (e.checked && sourceLang == e.value) {
    			e.checked = false;
    			alert('Source language and Target language must be different!');
    		}
	    });

		buildTargetLanguagesHtml(frm, 'targetContainer');

		return false;
	}

	function buildTranslationParamsHtml(frm, container) {
		var html = '<b>' + frm.src_wordcount.value + '</b> words in ' + getDropdownSelectedText(frm.iqFrom1_lang) + ' - Type ' + getDropdownSelectedText(frm.iq_type) + ' - Currency: ' + getDropdownSelectedText(frm.iq_currency) + '<br/>';
		document.getElementById(container).innerHTML = html;
	}


	function buildTargetLanguagesHtml(frm, container) {

		var html = getSelectedLanguages(frm);
		if (html.length) html = 'Into: <b>' + html + '</b>';
		document.getElementById(container).innerHTML = html;
	}


	function getSelectedLanguages(frm) {
		var html = '';
		for(var i=0; i < frm.targetlang.length; i++){
			if(frm.targetlang[i].checked) {
				if (html.length) html += ', ';
				html += document.getElementById('targetLang_' + frm.targetlang[i].value).childNodes[0].nodeValue;
			}
		}

		return html;
	}


	function validateQuotation(frm) {
		var value = '' + frm.iqFrom1_lang.value;
		var item = document.getElementById('src_wordcount');
		if (!isNumber(item)) item.value = '';

		for(var i=0; i < frm.targetlang.length; i++){
			if (parseInt(value) == parseInt(frm.targetlang[i].value)) {
				frm.targetlang[i].checked = false;
			}
		}
		if (checkForm(frm)) {
			frm.submit();
		}
	}

	function validateHomeQuotation(frm) {
		var item = document.getElementById('src_wordcount');
		if (!isNumber(item)) item.value = '';


		//onsubmit="if(checkForm(this)){ processHomeQuote(1); };return false;

		if (checkForm2(frm)) {

            if ($F('iqFrom1_lang') == $F('iqTo1_lang')) {
    			alert('Source language and Target language must be different!');
    			return false;
    		}

			processHomeQuote(1)
			//frm.submit();
		}
	}

	function saveQuotationContact(frm) {
		var item1 = document.getElementById('ac_email');
		var item2 = document.getElementById('ac_email2');

		if (item1.value != item2.value) item2.value = '';

		if (checkForm(frm)) {
			frm.submit();
		}
	}


	function selectDelivery(frm, delivery) {

		var send = false;

		if (frm.targetlang.type == 'checkbox'){
            send = send || frm.targetlang.checked;
		} else {
    		for (i = 0; i < frm.targetlang.length; i++) {
    			send = send || frm.targetlang[i].checked;
    		}
		}


		if (send) {
			frm.delivery.value = delivery;
			frm.submit();
		} else {

			document.getElementById("error").style.display = 'block';
		}
	}

	function contactIAMChange(control) {
		var org = document.getElementById("organization");
		var fname = document.getElementById("firstName");
		var lname = document.getElementById("lastName");

		if (control.value == "Company") {
			org.className = "required";
			fname.className = "required";
			lname.className = "required";
			org.style.display = "";
			//fname.style.display = "none";
			//lname.style.display = "none";
		} else {
			org.className = "";
			fname.className = "required";
			lname.className = "required";
			org.style.display = "none";
			fname.style.display = "";
			lname.style.display = "";
		}
	}

	/***********************************************************
	 * Realiza el proceso de calculo de las traducciones
	 * cuando se selecciona o deselecciona un elemento de
	 * traducci�n
	 ***********************************************************/
	function recalculateQuotation(frm, deliveryCount, VAT) {
		var delPrices = new Array(deliveryCount);
		var languageCount = 1;
		if (frm.targetlang.length) languageCount = frm.targetlang.length;

		var hasTranslations = false;
		for (i = 0; i < languageCount; i++) {
			var control;

			var cellValue = 0;
			var className = "languageNormal";
			if (languageCount == 1) control= frm.targetlang;
			else control= frm.targetlang[i];

			if (control.checked) {
				hasTranslations = true;
				for (c = 1; c <= deliveryCount; c++) {
					if (delPrices[c - 1] == null) delPrices[c - 1] = 0;

					try {
						cellValue = parseFloat(document.getElementById("price_" + control.value + "_" + c).innerHTML);
					} catch (e) {
						cellValue = 0;
					}

					delPrices[c - 1] = delPrices[c - 1] + cellValue;
				}
			} else {
				className = "languageNone";
			}
			document.getElementById("languageRow_" + control.value).className = className;
		}

		if (hasTranslations) {
			document.getElementById("error").style.display = 'none';
			document.getElementById("subtotalRow").className = "subtotalNormal";
		} else {
			document.getElementById("error").style.display = 'block';
			document.getElementById("subtotalRow").className = "subtotalNone";
		}

		for (c = 1; c <= deliveryCount; c++) {
			if (delPrices[c - 1] == null) delPrices[c - 1] = 0;
			document.getElementById("subtotal_" + c).innerHTML = parseFloat(delPrices[c - 1]).toFixed(2);
			document.getElementById("VAT_" + c).innerHTML = (delPrices[c - 1] * parseFloat(VAT) / 100).toFixed(2);
			document.getElementById("total_" + c).innerHTML = (delPrices[c - 1] + parseFloat((delPrices[c - 1] * parseFloat(VAT) / 100).toFixed(2))).toFixed(2);
		}

		buildTargetLanguagesHtml(frm, 'targetContainer');
	}

	function addExtrasToPrice(extra_id) {
		var price = parseFloat(document.getElementById("price").value);
		var extraPrice = parseFloat(document.getElementById("extra_" + extra_id).value);
		var vatPrice = price * parseFloat(document.getElementById("vat").value) / 100;
		var vatExtra = extraPrice * parseFloat(document.getElementById("vat").value) / 100;

		var subtotal = price + extraPrice;
		var vat = vatPrice + vatExtra;
		var totalPrice = subtotal + vat;
		document.getElementById("subtotal").innerHTML = FormatNumber(subtotal.toFixed(2));
		document.getElementById("VAT").innerHTML = FormatNumber(vat.toFixed(2));
		document.getElementById("total").innerHTML = FormatNumber(parseFloat(totalPrice).toFixed(2));
	}

/*******************************************************
 * Javascript Uploader
 *******************************************************/
	//uploader = new FileUploader('uploader', 'handleResponse');


	function uploadQuotation(frm, id) {
		hideDiv('fileContainer');
		showAjaxWheel('ajaxWheelContainer', 'Uploading data to server');
		setTimeout("", 5000);
		frm.submit();
		//uploader.upload('frmUpload', 'uploadHandler.php?id=' + id);
	}

	function handleResponse() {

		/*if (uploader.hasErrors()) {

			hideDiv('ajaxWheelContainer');
			showDiv('fileContainer');
		} else {*/
			var id = document.getElementById("translation").value;
			window.location.href = 'accept_contact.php?id=' + id;
		/*}*/
	}

/*******************************************************
 * Javascript General Functions
 *******************************************************/
	function getDropdownSelectedText(cbo) {
		var index = cbo.selectedIndex;
		var selected_text = cbo.options[index].text;

		if (cbo.value == 0 || cbo.value == '') selected_text = null;
		if (selected_text == null) selected_text = '';

		return selected_text;
	}


	function isNumber(field) {
		return field.value.match(/^\d+$/);
	}


	function showDiv(element_id) {
		var div = document.getElementById(element_id);
		div.style.display = 'block';
	}

	function hideDiv(element_id) {
		var div = document.getElementById(element_id);
		div.style.display = 'none';
	}

	function showAjaxWheel (container_id, msg) {
		var container = document.getElementById(container_id);
		container.innerHTML = "<img src=\"../rsrc/bigrotation.gif\" border=\"0\" /><b>" + msg + "</b>";
		showDiv(container_id);

	}
