// login function
function login(language) {

    // english language by default
    if (language == null)
       language = 'en';
    getDictionary(language);

    var username = document.getElementById('extUsername').value;
    if (username == '') {
        alert(getMessage('userRequired'));
        return false;
    }
    
    var password = document.getElementById('extPassword').value;
    if (password == '') {
        alert(getMessage('passwdRequired'));
        return false;
    }

    DWREngine.setAsync(true);
    LoginManager.getUserEnvironment(username, {
        callback:function(str) {
            loginManagement(str);
        }
    });
}

// login management
function loginManagement(value) {
    // user unknown
    if (value == '0') {
        alert(getMessage('userUnknown'));
    }

    // area de clientes user
    else if (value == '1') {
        loginAdc();
    }

    // oigaa user
    else if (value == '2') {
        loginOigaa(true);
    }

    // area de clientes and oigaa user
    else if (value == '3') {
        chooseLogin();
    }

    // error
    else {
        alert(getMessage('undefinedError'));
    }
}


function chooseLogin() {
    var dialogContent = "<table cellspacing='5' cellpadding='5'>";
    dialogContent += "<tr><td colspan='2'><span class='titol'>Por favor, seleccione su aplicaci&oacute;n:</span></td></tr>";
    dialogContent += "<tr><td></td></tr>";
    dialogContent += "<tr><td><img src='/img/logo_oigaa.png'></td>";
    dialogContent += "<td align='left'><a class='textLogin' href='#' onclick='loginOigaa(false); return false;'>Oigaa</a></td></tr>";
    dialogContent += "<tr><td></td></tr>";
    dialogContent += "<tr><td><img src='/img/logo_adc.gif'></td>";
    dialogContent += "<td align='left'><a class='textLogin' href='#' onclick='loginAdc(); Dialog.closeInfo(); return false;'>Area de Clientes</a></td></tr></table>";
    setDialogContent(dialogContent, true);
}

// login to area de clientes
function loginAdc() {
    document.loginForm.submit();
}

// login oigaa function
function loginOigaa(isdirectly) {
  var username = document.getElementById('extUsername').value;
  var password = document.getElementById('extPassword').value;
  loginOigaaData(username, password, isdirectly);
}

function loginOigaaData(username, password, isdirectly) {
  var xmlhttp=false;
  var resultAuth;

  if (isdirectly)
    setDialogContent("<br><img src='/img/progress.gif'><span style='FONT-SIZE: 12px; WIDTH: 50%'>"+getMessage("authenticating")+"</span>", isdirectly);
  else
    setDialogContent("<br><img src='/img/progress.gif'><span style='FONT-SIZE: 12px; WIDTH: 50%'>"+getMessage("authenticating")+"</span>", isdirectly);

  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  // and security blocked creation of the objects.
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
  @end @*/

  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp=false;
    }
  }

  if (!xmlhttp && window.createRequest) {
    try {
      xmlhttp = window.createRequest();
    } catch (e) {
      xmlhttp=false;
    }
  }

  var params = "userName="+username+"&userPasswd="+password;
  xmlhttp.open("POST", "/login/login?",true);

  //Send the proper header information along with the request
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.setRequestHeader("Content-length", params.length);
  xmlhttp.setRequestHeader("Connection", "close");
  
  xmlhttp.onreadystatechange=function() {
    if(xmlhttp.readyState==4){
      resultAuth=xmlhttp.getResponseHeader("Result");
      if(xmlhttp.getResponseHeader("Location")==null || xmlhttp.getResponseHeader("Location")==""){
        setDialogContent("<span style='FONT-SIZE: 12px; WIDTH: 50%'>" + getMessage(resultAuth) + 
                         "<br><a href='javascript:Dialog.closeInfo()'><br>" + getMessage("tryMoreLater") + "</a></span>");
        setTimeout('Dialog.closeInfo()',1000);

      } else if (xmlhttp.getResponseHeader("Location")=="Authentication-error" || 
                xmlhttp.getResponseHeader("Location")=="Authentication-error-sendtoken" ) {
        setDialogContent("<span style='FONT-SIZE: 12px; WIDTH: 50%'><BR/>" + getMessage(resultAuth) + 
                         "<br><a href='javascript:Dialog.closeInfo()'><br>"+getMessage("tryAgain") +"</a></span>");
        setTimeout('Dialog.closeInfo()',2000);

      } else if (xmlhttp.getResponseHeader("Location")=="Authentication-error-passwd-required") {
        alert(getMessage(resultAuth));
        setTimeout('Dialog.closeInfo()',10);

      } else {
        var newLocation = xmlhttp.getResponseHeader("Location");
        window.open(newLocation,'OIIGA','width=380,height=690,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
        setDialogContent("<span style='FONT-SIZE: 12px; WIDTH: 50%'><BR/>"+getMessage(resultAuth)+"</span>");
        setTimeout('Dialog.closeInfo()',3000);
      }
    } else {
      setTimeout('Dialog.closeInfo()',4000);
    }

    //resetAuthFields();
  }

  xmlhttp.send(params);
}


function setDialogContent(content) {
    setDialogContent(content, false);
}

function setDialogContent(content, isFirstTime) {
    if (isFirstTime) {
        var divcontent = "<div id='dialogdiv' align='center'>" + content + "</div>";
        Dialog.info(divcontent, {className: "alphacube",width:220, height:100, top:380, okLabel: "close", ok:function(win) {return true;}});

    } else {
        document.getElementById('dialogdiv').innerHTML = content;
    }
}


// remind data function
function remindData(language) {

	// english language by default
   if (language == null)
      language = 'en';
   getDictionary(language);

	var divcontent = "<div align='center' id='recaptcha_widget'>";
	divcontent += "<table cellspacing='5' cellpadding='5'>";
	divcontent += "<tr><td><img src='/img/blank.gif' height='10px' width='1px'/></td></tr>";
	divcontent += "<tr><td align='right'><span class='text10'>" + getMessage('remindPwdText') + "</span></td>";
	divcontent += "  <td><input type='text' id='remindEmail' name='remindEmail' value='' class='camptext'/></td></tr>";
	divcontent += "<tr><td></td></tr>";
	divcontent += "<tr><td><div id='recaptcha_div' align='center'></div></td></tr>";
	divcontent += "<tr><td colspan='2' align='right'><div id='recaptcha_image' style='border: 2px black solid;'></div></td>";
	divcontent += "  <td valign='bottom'><div><a href='javascript:Recaptcha.reload()'><img style='border: 0px' src='http://api.recaptcha.net/img/blackglass/refresh.gif' alt='Refresh' title='Reload'/></a></div></td></tr>";
	divcontent += "<tr><td align='right'><span class='text10'>" + getMessage('remindCaptchaText') + "</span></td>";
	divcontent += " <td><input type='text' id='recaptcha_response_field' name='recaptcha_response_field' class='camptext'/></td></tr>";
	divcontent += "<tr><td><img src='/img/blank.gif' height='12px' width='1px'/></td></tr>";
	divcontent += "<tr><td colspan='3' align='center'>";
	divcontent += "  <div id='remindBtn'><a href='#' onClick='remindAction(); return false;'><img src='/img/esp/bt_enviar_off.gif' border='0' onMouseOver='this.src=\"/img/esp/bt_enviar_on.gif\"' onMouseOut='this.src=\"/img/esp/bt_enviar_off.gif\"'></a></div>";
	divcontent += "  <div id='processing' style='display:none'><img src='/img/progress.gif'><span class='text10'>Processing...</span></div>";
	divcontent += "</td></tr>";
	divcontent += "</table></div>";
	
	var win = new Window('remindWin', 
		{className: "greylighting",width:410, height:190, top:380, left:480, 
			title: "<span class='titol'>" + getMessage('remindPwdTitle') + "</span>", destroyOnClose: true });
	win.getContent().innerHTML = divcontent;
	win.show();

	Recaptcha.create("6LcLNwMAAAAAALCmp8vUukF8qzWJ6MqDyqpn8dO5",
		"recaptcha_div", {
   	theme: "custom",
   	lang: language,
   	custom_theme_widget: "recaptcha_widget"
   	//callback: Recaptcha.focus_response_field
	});
}

// remind action
function remindAction() {
	var username = document.getElementById('remindEmail').value;    
   var reChallenge = document.getElementById("recaptcha_challenge_field").value;
   var reResponse  = document.getElementById("recaptcha_response_field").value;
   
	if (username == '') {
   	alert(getMessage('remindAllDataRequired'));
   	document.getElementById('remindEmail').focus();
   	return;
	}
	
   if (reResponse == '') {
   	alert(getMessage('remindAllDataRequired'));
   	document.getElementById("recaptcha_response_field").focus();
   	return;
   }
   
   document.getElementById('remindBtn').style.display = 'none';
   document.getElementById('processing').style.display = 'block';
    
   DWREngine.setAsync(true);
	RemindLoginData.remindData(username, reChallenge, reResponse, {
       callback:function(str) {
           remindManagement(str);
       }
   });
}

// remind result management
function remindManagement(value) {
    // user unknown
    if (value == '0') {
        alert(getMessage('userUnknown'));
        Windows.close('remindWin');
    }

    // ok area de clientes
    else if (value == '1') {
        alert(getMessage('remindAdc'));
        Windows.close('remindWin');
    }
    
    // ok oigaa
    else if (value == '2') {
        alert(getMessage('remindOigaa'));
        Windows.close('remindWin');
    }
    
    // ok area de clientes y oigaa
    else if (value == '3') {
        alert(getMessage('remindAdcOigaa'));
        Windows.close('remindWin');
    }
    
	 // words bad spelled
    else if (value == '-2') {
        alert(getMessage('remindCaptchaError'));
        Recaptcha.reload();
        document.getElementById('processing').style.display = 'none';
        document.getElementById('remindBtn').style.display = 'block';
        document.getElementById("recaptcha_response_field").value = '';
        document.getElementById("recaptcha_response_field").focus();
    }
    
    // error
    else {
        alert(getMessage('undefinedError'));
        Windows.close('remindWin');
    }
}


