function GotoWebmail() {
    // fetch language information from 
    var lang  = document.getElementById('int_lang').value;

    // array for atmail lang selection
    var langArray = Array();
    langArray['pl'] = 'polish';
    langArray['de'] = 'german';
    langArray['fr'] = 'french';
    langArray['es'] = 'espanol';
    langArray['en'] = 'english';
    langArray['it'] = 'italiano';
    langArray['nl'] = 'dutch';

    //arrar for ilohamail lang selection
    var illohamailLangArray = Array();
    illohamailLangArray['pl'] = 'pl/';
    illohamailLangArray['de'] = 'de/';
    illohamailLangArray['fr'] = 'fr/';
    illohamailLangArray['es'] = 'es/';
    illohamailLangArray['en'] = 'eng_GB/';
    illohamailLangArray['it'] = 'it';
    illohamailLangArray['nl'] = 'nl';

    if( !checkMail() )
    {
        return false;
    }
    var username = $("#webmail_username").val()
    var webmailType = $("#webmailType").val();
    var password = $("#password").val();
    
    switch(webmailType) {
    case "horde":
        $("#imapuser").val( username )
        $("#pass").val( password )
        break;
    case "squirrelmail":
        $("#login_username").val( username )
        $("#secretkey").val( password )
        break;
    case "ilohamail":
        $("#user").val( username )
        // $("#password").val( password )
        $("#int_lang").val( illohamailLangArray[lang] );
        break;
    case "roundcube":
        $("#user_").val( username )
        $("#pass_").val( password )
        break;
    case "atmail":
        if(username.indexOf('@') == -1){
	          var user_array = username.split('%');
        } else {
	          var user_array = username.split('@');
        }
        $("#username").val( user_array[0] );
        $("#pop3host").val( user_array[1] );
        $("#MailType").val('imap');
        $("#NewWindow").val('1');
        $("#Language").val( langArray[lang] );
        break;
    case "ox":
        $("#username").val( username )
        break;
    }
}

function checkMail()
{
    var emailString = $("#webmail_username").val();
    var webmailLang = $("#int_lang").val();
	  emailRegExp = /^[_a-z\u00A1-\uFFFF0-9-]+(\.[_a-z\u00A1-\uFFFF0-9-]+)*(@|%)[a-z\u00A1-\uFFFF0-9-]+(\.[a-z\u00A1-\uFFFF0-9-]+)*(\.([a-z]){2,6})$/;
	  if(emailRegExp.test(emailString)){
		    return true;
	  }else{
		    alert(emailError[webmailLang]);
		    return false;
	  }
}

var ommit = 1;
var BrowserVer = new BrowserVerChk();

// set default highlight on page load
function setOnLoad() {
    var webmailLang = $("#int_lang").val();

    //trigger changeInterface function call after selecting webmail interface
    //it's required becaouse setting option by value doesn't trriger this action
    //it allow us hide additional atmail iterface selection when user choose other 
    //intereface then atmail
    $("#interface")
    .change( changeInterface )
    .selectOptions(webmailDefault, true)
    .change()

    $("#LoginType").change( BrowserVsInterface );  

	  // set default webmailType
    $("#webmailType").val(webmailDefault);
    $("#webmail_username").focus();

    //change action after first submit and submit once again
    if( $("#password").val() ){
        var ifSSL = $("#secure_login").attr('checked');
        var method = '';

        // check if secure channel should be used
        if( ifSSL ){
	          method = 'ssl';
        } else {
	          method = 'plain';
        }
        
        url = '';
        if( typeof(webmailUrl[webmailDefault][webmailLang]) == 'undefined' ){
            url = webmailUrl[webmailDefault]['default'][method];
        } else {
            url = webmailUrl[webmailDefault][webmailLang][method]
        }
        
        $("#logon").attr('action', url);

        $("#logon").submit( secondSubmit );
        $("#logon").submit();
    }
    else {
        $("#logon").submit( firstSubmit );
    }
}

function submitForm(webmailType) {
    $("#webmailType").val(webmailType);
	  GotoWebmail();
}


function changeInterface() {
    var webmail = $("#interface option:selected").val();
    var webmail_type = webmail;

    // For some webmail selection change form layout
    if (webmail == 'atmail')
    {
        $("#fade_text").removeClass('fade');
        $("#fade_select").removeClass('fade');
        $("#LoginType").attr('disabled', false);
        if( $("#LoginTypeInput").val() ){
            $("#LoginType").selectOptions( $("#LoginTypeInput").val() );
        }
    }
    else if(webmail == 'ox') {
		    if (BrowserVer.Type != 'MSIE' && BrowserVer.Type != 'Firefox') {
		        if( confirm ("Your Browser does not match the recommended requirements for this Interface.\nYou are using " + BrowserVer.TypeLong + " Version " + BrowserVer.Version + ", You need Firefox or Internet Explorer.\nAre you sure you want to select this interface?") == true) 
            {
                $("#secure_login").attr('checked', true).attr('disabled', true)
		        }
            else{
                $("#interface").selectOptions('roundcube', true)
            }
        }
        else {
            $("#secure_login").attr('checked', true).attr('disabled', true)
        }
    }        

    if( webmail != 'atmail' ) {
        $("#fade_text").addClass('fade');
        $("#fade_select").addClass('fade');
        $("#LoginType").attr('disabled', true);
    }

    if( webmail != 'ox') {
        $("#secure_login").removeAttr('disabled');
    }
}

function secondSubmit() {
    if( checkMail() )
    {
        if( $("#password").val() ){
            document.getElementById('LoginTypeInput').value = document.getElementById('LoginType').value;
        }
        submitForm(document.getElementById('interface').value);
        return true;
    }
    else {
        return false;
    }
}

function firstSubmit() {
    if( checkMail() )
    {
        if( $("#password").val() ){
            document.getElementById('LoginTypeInput').value = document.getElementById('LoginType').value;
            return true;
        }
        return false;
    } 
    else {
        return false;
    }
}

function injectDomain() {
    //Check if we allready got username from cookie
    if( $("#webmail_username").val() ){
        return;
    }

    var user_domain = document.domain;
    var domain_regex = /^(mail\.)(.*)/;
    var test_domain = user_domain.replace(domain_regex, "$1");
    if (test_domain == 'mail.') {
        user_domain = user_domain.replace(domain_regex, "@$2");
        $("#webmail_username").val(user_domain)
        setSelectionRange($("#webmail_username").val(),0,0);
    }
}

function setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

function BrowserVerChk() {
	  this.Type = false;
	  this.TypeLong = false;
	  this.Version = false;
	  this.LateGen = false;

	  if (navigator.appVersion.indexOf("MSIE") != -1) {
		    this.Type = "MSIE";
		    this.TypeLong = "Internet Explorer";
		    var TempArray = navigator.appVersion.split("MSIE");
		    this.Version = parseFloat(TempArray[1]);
		    if (this.Version >= 6) this.LateGen = true;
	  } else if (navigator.userAgent.indexOf("Firefox") != -1) {
		    this.Type = "Firefox";
		    this.TypeLong = "Firefox";
		    var VersionIndex = navigator.userAgent.indexOf("Firefox") + 8;
		    this.Version = (navigator.userAgent.charAt(VersionIndex) + "." + navigator.userAgent.charAt(VersionIndex + 2)) * 1;
		    if (this.Version >= 1.5) this.LateGen = true;
	  } else if(navigator.userAgent.indexOf("Safari") != -1)	{
		    this.Type = "Safari";
		    this.TypeLong = "Safari";
		    this.LateGen = true;
	  } else if(navigator.userAgent.indexOf("Iceweasel") != -1) {
		    this.Type = "Iceweasel";
		    this.TypeLong = "Iceweasel";
		    var VersionIndex = navigator.userAgent.indexOf("Iceweasel") + 10;
		    this.Version = (navigator.userAgent.charAt(VersionIndex) + "." + navigator.userAgent.charAt(VersionIndex + 2)) * 1;
		    if (this.Version >= 1.5) this.LateGen = true;
	  } else if(window.opera) {
		    this.Type = "Opera";
		    this.TypeLong = "Opera";
		    this.Version = window.opera.version();
		    this.LateGen = true;
	  }
}

function BrowserVsInterface() {
	  //document.body.style.cursor = "wait";
	  var SelectedInterface = document.getElementById('LoginType').selectedIndex;
	  var ConfirmUser = false;
	  if (SelectedInterface > 0) {
		    if (SelectedInterface == 1 && BrowserVer.LateGen != true) {
			      if (BrowserVer.Type == "Firefox") {
				        ConfirmUser = "Firefox Version 1.5 or later";
			      } else {
				        ConfirmUser = "Internet Explorer Version 6 or later";
			      }
		    } else if (SelectedInterface == 2 && (BrowserVer.Type != "MSIE" || BrowserVer.LateGen != true)) {
			      ConfirmUser = "Internet Explorer Version 6 or later";
		    } else if (SelectedInterface == 3 && BrowserVer.Type != "Firefox" && BrowserVer.Type != "Iceweasel") {
			      ConfirmUser = "Firefox Version 1.0 or later";
		    } else {
			      ConfirmUser = false;
		    }
	  }

	  if (ConfirmUser != false) {
		    if (confirm ("Your Browser does not match the recommended requirements for this Interface.\nYou are using " + BrowserVer.TypeLong + " Version " + BrowserVer.Version + ", You need " + ConfirmUser + ".\nAre you sure you want to select this atmail interface?") == true) {
			      ConfirmUser = false;
		    }
        else{
            $("#LoginType").selectOptions('ajax', true)
        }
	  }
}

$( function($){
    setOnLoad();
    injectDomain();
});