var sourceLanguage = 0;
var translatorSourceLanguageSelectValue = 0;
var destinationLanguage = new Array();
var translatorLanguage = new Array();
var translatorCompany = new Array();
var languageType = "";
var selectableLanguages;
var selectableLanguagesIds;
var selectableCompanies;
var selectableCompaniesIds;
var defaultTextLanguageInputField;
var defaultTextSourceLanguageInputField;
var defaultTextTargetLanguageInputField;
var defaultTextCompanyInputField;
var warningSourceTargetLanguageSame;
var warningTargetSourceLanguageSame;
var warningLanguageAlreadySelected;
var warningLanguageCombinationAlreadySelected;
var warningCompanyAlreadySelected;

$j(document).ready(function(){

	var autocompleteOptions = {
		delay:10,
		minChars:1,
		matchSubset:1,
		onFindValue:findValue,
		autoFill:true,
		maxItemsToShow:10
	};
	
	$j("#SourceLanguage, #DestinationLanguages, #TranslatorSourceLanguages, #TranslatorTargetLanguages, #TranslatorCompanies").addClass('hint');	
	$j("#SourceLanguage, #DestinationLanguages").val(defaultTextLanguageInputField);
	$j("#TranslatorCompanies").val(defaultTextCompanyInputField);
	
	$j("#TranslatorSourceLanguages").val(defaultTextSourceLanguageInputField);
	$j("#TranslatorTargetLanguages").val(defaultTextTargetLanguageInputField);
	
	$j("#SourceLanguage, #DestinationLanguages").focus(function() {
		if($j(this).val() == defaultTextLanguageInputField)
		{
			$j(this).val("");
			$j(this).removeClass('hint');	
		}
	});

	$j("#TranslatorSourceLanguages").focus(function() {
		if($j(this).val() == defaultTextSourceLanguageInputField)
		{
			$j(this).val("");
			$j(this).removeClass('hint');	
		}
	});

	$j("#TranslatorTargetLanguages").focus(function() {
		if($j(this).val() == defaultTextTargetLanguageInputField)
		{
			$j(this).val("");
			$j(this).removeClass('hint');	
		}
	});

	$j("#TranslatorCompanies").focus(function() {
		if($j(this).val() == defaultTextCompanyInputField)
		{
			$j(this).val("");
			$j(this).removeClass('hint');	
		}
	});

	var sourceLanguageAutocompleteOptions = Object.clone(autocompleteOptions);
	sourceLanguageAutocompleteOptions.onItemSelect = selectSourceItem;
	
	$j("#SourceLanguage").autocompleteArray(
		selectableLanguages,
        sourceLanguageAutocompleteOptions
	);

	var destinationLanguagesAutocompleteOptions = Object.clone(autocompleteOptions);
	destinationLanguagesAutocompleteOptions.onItemSelect = selectDestinationItem;

	$j("#DestinationLanguages").autocompleteArray(
		selectableLanguages,
        destinationLanguagesAutocompleteOptions
	);

	var translatorSourceLanguagesAutocompleteOptions = Object.clone(autocompleteOptions);
	translatorSourceLanguagesAutocompleteOptions.onItemSelect = selectTranslatorSourceItem;

	var translatorTargetLanguagesAutocompleteOptions = Object.clone(autocompleteOptions);
	translatorTargetLanguagesAutocompleteOptions.onItemSelect = selectTranslatorTargetItem;
		
	$j("#TranslatorSourceLanguages").autocompleteArray(
		selectableLanguages,
        translatorSourceLanguagesAutocompleteOptions
	);

	$j("#TranslatorTargetLanguages").autocompleteArray(
		selectableLanguages,
        translatorTargetLanguagesAutocompleteOptions
	);
		
	var translatorCompaniesAutocompleteOptions = Object.clone(autocompleteOptions);
	translatorCompaniesAutocompleteOptions.onItemSelect = selectCompanyItem;		

	$j("#TranslatorCompanies").autocompleteArray(
		selectableCompanies,
        translatorCompaniesAutocompleteOptions
	);
			
	$j(".remove").livequery(function(){
		$j(this).click(function(){
			
			if($j(this).hasClass('company')) {
    			var removeCompany = $j(this).attr('rel');
    			var removeCompanyId = getCompanyId(findIndex(removeCompany, selectableCompanies));			    
			}
			else if($j(this).hasClass('translator')) {
    			var removeCombinationId = $j(this).attr('rel');
			}
			else {
    			var removeLang = $j(this).attr('rel');
    			var removeLangId = getLanguageId(findIndex(removeLang, selectableLanguages));			    
			}
			
			if($j(this).hasClass('source')) {
				$j("#source_"+removeLangId).remove();
				$j("#sourceField_"+removeLangId).remove();
				$j("#SourceLanguage").show();
				$j("#SourceLanguage").focus();
				$j("#sourceLangList").html("");
				sourceLanguage = 0;
			}else if($j(this).hasClass('destination')) {
				$j("#destination_"+removeLangId).remove();
				$j("#destinationField_"+removeLangId).remove();
				destinationLanguage.splice(findIndex(removeLang, destinationLanguage), 1);
			}else if($j(this).hasClass('translator')) {
                $j("#translator_"+removeCombinationId).remove();
                $j("#translatorField_"+removeCombinationId).remove();
                translatorLanguage.splice(findIndex(removeCombinationId, translatorLanguage), 1);
    		}else if($j(this).hasClass('company')) {
    			$j("#company_"+removeCompanyId).remove();
    			$j("#companyField_"+removeCompanyId).remove();
    			translatorCompany.splice(findIndex(removeCompany, translatorCompany), 1);
    		}
		});
	});
		
});

function findValue(li) {
	if( li == null ) return alert("No match!");
	if( !!li.extra ) var sValue = li.extra[0];
	else var sValue = li.selectValue;
}

function langType(lang) {
	languageType = lang;
}

function selectSourceLanguage(language_id) {
	lang = selectableLanguages[findIndex(language_id, selectableLanguagesIds)];
	addLanguage(lang, "source");	
}

function selectTargetLanguages(language_ids) {
	language_ids.each(function(language_id) { 
		lang = selectableLanguages[findIndex(language_id, selectableLanguagesIds)];
		addLanguage(lang, "destination");	
	});	
}

function selectTranslatorLanguageCombinations(language_combination_ids) {
    language_combination_ids.each(function(combination) {
        addLanguageCombination(combination);
	});
}

function selectTranslatorCompanies(company_ids) {
	company_ids.each(function(company_id) { 
		company = selectableCompanies[findIndex(company_id, selectableCompaniesIds)];
		addCompany(company);	
	});	
}

function selectSourceItem(li) {
	findValue(li);
	addLanguage(li.selectValue, languageType);
	$j("#SourceLanguage").val("");
}

function selectDestinationItem(li) {
	findValue(li);
	addLanguage(li.selectValue, languageType);
	$j("#DestinationLanguages").val("");
}

function selectTranslatorSourceItem(li) {
    $j('#TranslatorTargetLanguages').focus();
    translatorSourceLanguageSelectValue = li.selectValue;
}

function selectTranslatorTargetItem(li) {
    if( $j("#TranslatorSourceLanguages").val() == $j("#TranslatorTargetLanguages").val() )
    {
        alert(warningSourceTargetLanguageSame);
    }
    else
    {
        addLanguageCombinationFromInput(translatorSourceLanguageSelectValue, li.selectValue);
    }
    
    $j("#TranslatorSourceLanguages").val("");
    $j("#TranslatorTargetLanguages").val("");
    $j("#TranslatorSourceLanguages").focus();
}

function selectCompanyItem(li) {
	findValue(li);
	addCompany(li.selectValue);
	$j("#TranslatorCompanies").val("");
}

function formatItem(row) {
	return row[0] + " (id: " + row[1] + ")";
}

function lookupLocal(){
	var oSuggest = $j("#DestinationLanguages")[0].autocompleter;

	oSuggest.findValue();

	return false;
}

function addLanguage(lang, type) {
	if(lang != "") {
		var languageId = getLanguageId(findIndex(lang, selectableLanguages));
		switch (type) {
			case "source":
				if(jQuery.inArray(lang, destinationLanguage) == -1) {
					sourceLanguage = getLanguageId(findIndex(lang, selectableLanguages));
					$j("#SourceLanguage").hide();
					$j("#DestinationLanguages").focus();
					$j("#sourceLangList").append('<li id="source_'+languageId+'" class="dataList">'+lang+' <span rel="'+lang+'" class="remove source">| remove</span></li>');
					$j("#languageContainer").append('<input type="text" id="sourceField_'+languageId+'" name="job[source_language_id]" value="'+sourceLanguage+'" />');
				} else {
					alert(warningSourceTargetLanguageSame);
				}
			break;
			case "destination":
				if(jQuery.inArray(lang, destinationLanguage) != -1) {
					alert(warningLanguageAlreadySelected);
				} else if(getLanguageId(findIndex(lang, selectableLanguages)) == sourceLanguage) {
					alert(warningTargetSourceLanguageSame);
				} else {
					$j("#destinationLangList").append('<li id="destination_'+languageId+'" class="dataList">'+lang+' <span rel="'+lang+'" class="remove destination">| remove</span></li>');
					$j("#languageContainer").append('<input type="text" id="destinationField_'+languageId+'" name="target_language_ids[]" value="'+languageId+'" />');
					destinationLanguage.push(lang);
				}
			break;
		}
	}
}

function addLanguageCombination(combination) {
 	label = selectableLanguages[findIndex(combination.source_language_id, selectableLanguagesIds)] + " &rarr; " + selectableLanguages[findIndex(combination.target_language_id, selectableLanguagesIds)];

	$j("#translatorLangList").append('<li id="translator_'+combination.id+'" class="dataList">'+label+' <span rel="'+combination.id+'" class="remove translator">| remove</span></li>');
	$j("#languageContainer").append('<input type="text" id="translatorField_'+combination.id+'" name="translator[language_combination_ids][]" value="'+combination.id+'" />');

	translatorLanguage.push(combination.id);
}

function addLanguageCombinationFromInput(sourceLang, targetLang) {
   	var sourceLanguageId = getLanguageId(findIndex(sourceLang, selectableLanguages));
   	var targetLanguageId = getLanguageId(findIndex(targetLang, selectableLanguages));

    $j.ajax({
      type: "POST",
      url: "/language_combinations/create_unless_exists",
      data: "source_lang=" + sourceLanguageId + "&target_lang=" + targetLanguageId,
      dataType: "json",
      success: function(combination){
        if(jQuery.inArray(combination.id, translatorLanguage) != -1) {
            alert(warningLanguageCombinationAlreadySelected);
        }
        else {
            addLanguageCombination(combination);         
        }		        
      }
    });	
}

function addCompany(company) {
	if(company != "") {
		var companyId = getCompanyId(findIndex(company, selectableCompanies));
        if(jQuery.inArray(company, translatorCompany) != -1) {
            alert(warningCompanyAlreadySelected);
        } else {
            $j("#translatorCompanyList").append('<li id="company_'+companyId+'" class="dataList">'+company+' <span rel="'+company+'" class="remove company">| remove</span></li>');
            $j("#companyContainer").append('<input type="text" id="companyField_'+companyId+'" name="translator[company_ids][]" value="'+companyId+'" />');
            translatorCompany.push(company);
        }
	}    
}

function findIndex(item, arr) {
	var len = arr.length;
	var i=0;
	for (i=0;i<=len;i++) {
		if(arr[i] == item) {
			return i;
		}
	}
}

function getLanguageId(num) {
	return selectableLanguagesIds[num];
}

function getCompanyId(num) {
    return selectableCompaniesIds[num];
}