var cropzoom;

function getXMLHTTPRequest() {
    try {
        req = new XMLHttpRequest();
    } catch(err1) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (err2) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (err3) {
                req = false;
            }
        }
    }
    return req;
}


function ValidateEmailBusiness(Campo){
    var perfect = true;

	with (Campo){
		// Validar que los caracteres que contiene la cuenta de correo
		// esten dentro de los caracteres de la siguiente lista
		var car_validos = "0123456789abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKMNLOPQRSTUVWXYZ@.-_"
		var car_otros = "@.-_";

		for (var i=0; i < value.length; i++) {
			var ch = value.substring(i, i+1);
			if (car_validos.indexOf(ch) == -1) perfect = false;
		}

		apos = value.indexOf("@");
		lastpos = value.length-1;

		// Validar primer y ultimo caracter
		var car1 = value.substring(0, 1);
		var car2 = value.substring(lastpos, lastpos+1);
		if ((car_otros.indexOf(car1) != -1) || (car_otros.indexOf(car2) != -1)) perfect = false;


		// Validar anterior y siguiente caracter despues de "@"

		car1 = value.substring(apos-1, apos);
		car2= value.substring(apos+1, apos+2);
		if ((car_otros.indexOf(car1) != -1) || (car_otros.indexOf(car2) != -1)) perfect = false;

		// Buscar si existe otro simbolo "@" en el campo
		var subcadena = value.substring(apos + 1, 100);

        a2pos = subcadena.indexOf("@");
		spacepos = value.indexOf(" ");
		dotpos = value.lastIndexOf(".");
		posh=subcadena.indexOf(".");

        var business = subcadena.substring(0, posh);
        if(ltrim(rtrim(business)).toUpperCase()=="HOTMAIL" || ltrim(rtrim(business)).toUpperCase()=="YAHOO" ||
            ltrim(rtrim(business)).toUpperCase()=="GMAIL" || ltrim(rtrim(business)).toUpperCase()=="AOL" ){
            perfect = false;
        }

		//if (apos < 1 || a2pos != -1 || dotpos - apos < 2 || lastpos - dotpos > 3 || lastpos - dotpos < 2 || spacepos != -1) {
		if (apos < 1 || a2pos != -1 || lastpos - dotpos < 2 || spacepos != -1||posh==-1) perfect = false;
    }
	if (!perfect){
		//alert(Mensaje);
		//window.scrollTo(200,200);
		//Campo.focus();
		return false;
    }
    return true;
}

function validateFormFields(obj, ruleList){
    var returnString = true;
    var $element;
    var id;
    var value;

    //var list = new Array();
	// .filter('[id^="tb"]').
    $(":input", obj).filter(':enabled,[type="hidden"]').each( function (i){
        $element = $(this);
        id = $element.attr("id");
        value = $element.val();

        //list[i] = id;

        if (/^tbl/.test(id)){          
            value = $.trim(value);
            if(value.length == 0){
                returnString = id;
                return false;
            }
        }else if(/^tbP/.test(id)){
            value = $.trim(value);            
            if(value.length == 0){                
                returnString = id;
                return false;
            }else if(!validatePhoneOffice(value)) {
                    returnString = id;
                    return false;
            }
        }else if(/^tbN/.test(id)){
            if (!(/^[0-9]+$/.test(value))){
                returnString = id;
                return false;
            }
        }else if(/^tbxN/.test(id)){
            value = $.trim(value);
            if(value.length != 0){
                if (!(/^[0-9]+$/.test(value))){
                    returnString = id;
                    return false;
                }
            }
        }else if(/^tbE/.test(id)){
            if(!validateEmail(value)) {
			//if(!ValidateEmailBusiness($element)){
                returnString = id;
                return false;
            }
        }else if(/^tbxE/.test(id)){
            value = $.trim(value);
            if(value.length != 0){
                if(!validateEmailExcept(value)) {
                    returnString = id;
                    return false;
                }
            }
        }

        if( id in ruleList ) {
            returnString = ruleList[id].call(this,value);
            if( returnString === true) {
                return true;
            } else if(returnString === false ) {
                returnString = id;
            }

            return false;
        }

    });

	//returnString = 'tblFirstName';
    //alert(list.join(','));
    return returnString;
}


function validateFormFieldsExcept(obj, ruleList){
    var returnString = true;
    var $element;
    var id;
    var value;

    //var list = new Array();
	// .filter('[id^="tb"]').
    $(":input", obj).filter(':enabled,[type="hidden"]').each( function (i){
        $element = $(this);
        id = $element.attr("id");
        value = $element.val();

        //list[i] = id;

        if (/^tbl/.test(id)){
            value = $.trim(value);
            if(value.length == 0){
                returnString = id;
                return false;
            }
        }else if (/^tblN/.test(id)){
            value = $.trim(value);
            if(value.length == 0){
                returnString = id;
                return false;
            }else{
                if(!validatePhoneOffice(value)) {
                    returnString = id;
                    return false;
                }
            }
        }else if(/^tbN/.test(id)){
            if (!(/^[0-9]+$/.test(value))){
                returnString = id;
                return false;
            }
        }else if(/^tbxN/.test(id)){
            value = $.trim(value);
            if(value.length != 0){
                if (!(/^[0-9]+$/.test(value))){
                    returnString = id;
                    return false;
                }
            }
        }else if(/^tbE/.test(id)){
            if(!validateEmailExcept(value)) {
			//if(!ValidateEmailBusiness($element)){
                returnString = id;
                return false;
            }
        }else if(/^tbxE/.test(id)){
            value = $.trim(value);
            if(value.length != 0){
                if(!validateEmailExcept(value)) {
                    returnString = id;
                    return false;
                }
            }
        }

        if( id in ruleList ) {
            returnString = ruleList[id].call(this,value);
            if( returnString === true) {
                return true;
            } else if(returnString === false ) {
                returnString = id;
            }

            return false;
        }

    });

	//returnString = 'tblFirstName';
    //alert(list.join(','));
    return returnString;
}


/*function cambiarDisplay(id,ac,idb) {
	
   try
   {
	  if (!document.getElementById)
	  return false;
	  fila = document.getElementById(id);
	  filab= document.getElementById(idb);
	  tipo = ac;
	  if (fila.style.display != "none" && tipo=="Hidden_field" ) {
		fila.style.display = "none"; //ocultar fila 
		filab.style.display = "none"; //ocultar fila
	  } if (fila.style.display == "none" && tipo=="Show_field" ) {
		fila.style.display = ""; //mostrar fila 
		filab.style.display = ""; //ocultar fila
	  }
   }catch(error){
	   alert(error+" id -> "+id+" -> "+ac+" -> "+idb);
   }
}*/

function cambiarDisplay(id,ac,idb) {
	
   try
   {
	  if (!document.getElementById)
	  return false;
	  fila = document.getElementById(id);
	  filab= document.getElementById(idb);
	  tipo = ac;
	
	  if (fila.style.display != "none" && tipo=="Hidden_field" ) {
		fila.style.display = "none"; //ocultar fila 
		filab.style.display = "none"; //ocultar fila
		$(":input", fila).attr("disabled", true);
	  }if (fila.style.display == "none" && tipo=="Show_field" ) {
		fila.style.display = ""; //mostrar fila 
		filab.style.display = ""; //ocultar fila
		$(":input", fila).removeAttr("disabled");
	  }
   }catch(error){
	   alert(error+" id -> "+id+" -> "+ac+" -> "+idb);
   }
}

function changedStatus(){
    var div = document.getElementById("chagedStatus");
    div.innerHTML = '<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Do you want publish this image?</p>';
    $('#chagedStatus').dialog('open');
	
}
	
function errorMessage(message){
    var divMessage = document.getElementById("errorAccion");
    divMessage.innerHTML = '<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' +message+ '</p>';
    $('#errorAccion').dialog('open');
}
/*
 * Muestra el mensaje de Error
 */
function viewMessage(divMessage,Message,viewText){
    if(viewText==1){
        
        $(divMessage).html(Message).show();
    /*divMessage.style.display = "";
        divMessage.innerHTML=Message;
		alert(Message);*/
    }else{
        $(divMessage).hide().html('');
    // sdivMessage.style.display = "none";
    }
}
/*
 * Pasa el focus al campo especificado
 */
function goToError(field){
    $('#'+field).focus();
}
/*
 * Validacion de Email
 */

function validateEmail(fieldEmail){	
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/.test(fieldEmail)){
            if (/^.+@(HOTMAIL\.COM|GMAIL\.COM|YAHOO\.COM|AOL\.COM)$/.test(fieldEmail.toUpperCase())){
                    return false;
            }
       return true;
    }else{
        return false;
    }
}

function validateEmailExcept(fieldEmail){	
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/.test(fieldEmail)){            
       return true;
    }else{
        return false;
    }
}
function validatePhoneOffice(string){
   if (/^[\d()\-+\.\s]+$/.test(string)){
        return true;
    }else{
        return false;
    }
}

function validateCharacterEspecial(string){
    if (/^[a-z0-9]+$/i.test(string)){
        return true;
    }else{
        return false;
    }
}

//Valida si el E-mail valido 
function ValidateEmailOther(Campo, Mensaje){
    var perfect = true;

    with (Campo){
        // Validar que los caracteres que contiene la cuenta de correo
        // esten dentro de los caracteres de la siguiente lista
        var car_validos = "0123456789abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKMNLOPQRSTUVWXYZ@.-_"
        var car_otros = "@.-_";

        for (var i=0; i < value.length; i++) {
            var ch = value.substring(i, i+1);
            if (car_validos.indexOf(ch) == -1) perfect = false;
        }

        apos = value.indexOf("@");
        lastpos = value.length-1;

        // Validar primer y ultimo caracter
        var car1 = value.substring(0, 1);
        var car2 = value.substring(lastpos, lastpos+1);
        if ((car_otros.indexOf(car1) != -1) || (car_otros.indexOf(car2) != -1)) perfect = false;


        // Validar anterior y siguiente caracter despues de "@"

        car1 = value.substring(apos-1, apos);
        car2= value.substring(apos+1, apos+2);
        if ((car_otros.indexOf(car1) != -1) || (car_otros.indexOf(car2) != -1)) perfect = false;

        // Buscar si existe otro simbolo "@" en el campo
        var subcadena = value.substring(apos + 1, 100);
        a2pos = subcadena.indexOf("@");
        spacepos = value.indexOf(" ");
        dotpos = value.lastIndexOf(".");
        posh=subcadena.indexOf(".");

        //if (apos < 1 || a2pos != -1 || dotpos - apos < 2 || lastpos - dotpos > 3 || lastpos - dotpos < 2 || spacepos != -1) {
        if (apos < 1 || a2pos != -1 || lastpos - dotpos < 2 || spacepos != -1||posh==-1) perfect = false;
        }

    if (!perfect)
    {
        //alert(Mensaje);
        //window.scrollTo(200,200);
        //Campo.focus();
        return false;
    }
    return true;
}
/*
 * Validar Zip Code
 */
function validateZipCode(campo) {
    var RegExPattern = /^([0-9]{2}|[0-9][0-9]|[0-9][0-9])[0-9]{3}$/;

    if ((campo.value.match(RegExPattern)) && (campo.value!='')) {
        return true;
    } else {
        return false;
    }
}

function changeListDay(month){
    var arrayNumDiasMes = new Array();
    arrayNumDiasMes[0] = 31;
    arrayNumDiasMes[1] = 29;
    arrayNumDiasMes[2] = 31;
    arrayNumDiasMes[3] = 30;
    arrayNumDiasMes[4] = 31;
    arrayNumDiasMes[5] = 30;
    arrayNumDiasMes[6] = 31;
    arrayNumDiasMes[7] = 31;
    arrayNumDiasMes[8] = 30;
    arrayNumDiasMes[9] = 31;
    arrayNumDiasMes[10]= 30;
    arrayNumDiasMes[11]= 31;

    month-=1;
    var string_option = "<select class='selectBirth' name='birth_day' id='birth_day' style='width:53px'>";
    string_option    += "<option value=''>Day</option>";
    for(index=1;index<=arrayNumDiasMes[month];index++){
        string_option += "<option value=" +index+ ">" +index+"</option>";
    }
    string_option    += "</select>";

    var div_day = document.getElementById("div_day");
    div_day.innerHTML = string_option;

}

function validatePassword(value){
	var localValue = $.trim(value);	
	return ( /^[^\s]{6,}/.test(localValue) );
}

function validatePhone(numero){
    if(numero==""){
        return false;
    }else if (!/^([0-9-])*$/.test(numero)){
        return false;
    }else if(numero.length < 10){
        return false;
    }else{
        return true;
    }
}

function validateLogin(){
    
}


function deplazarScroll(){
    destination = $("#anchorAlert").offset().top;
    $("html:not(:animated),body:not(:animated)").animate({
        scrollTop: destination
    }, 800 );
}

function charaterCounter(namefield, maxlimit, countfield) {
    var wordcounter = $('#'+namefield).val().length;

    if (wordcounter >= maxlimit) {
        if(countfield!=undefined){
            $('#'+countfield).html("0 Characters left");
        }
        limitChar(namefield, maxlimit, countfield);
    }else {
        if(countfield!=undefined){
            $('#'+countfield).html(""+ (maxlimit - wordcounter)+" Characters left");
        }
    }
}

function limitChar(namefield, maxlimit) {
    $('#'+namefield).val($('#'+namefield).val().substring(0, maxlimit));
    $('#'+namefield).scrollTop = maxlimit;
}

function validateFile(archivo){
    var extensiones_permitidas = new Array(".png",".gif",".jpg",".jpeg",".mpg", ".mpeg", ".mov", ".wmv", ".avi",".mp4");
    var mierror = "";
    
    //recupero la extensión de este nombre de archivo
    var extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
    var permitida = false;
    for (var i = 0; i < extensiones_permitidas.length; i++) {
        if (extensiones_permitidas[i] == extension) {
            permitida = true;
            break;
        }
    }
    if (!permitida) {
        return false;
    }else{
        return true;
    }
}

function validateLogin(obj){
			
	if ($("#activePage").val()==="true"){
		var r = confirm("Your registration has not been completed. If you decide to leave the Cognizant Community 2011 website now, your information will not be saved and you will need to restart the registration process.");
		if (r == true){
			$("#activePage").val("false");
			validateLogin();	
		}else{
			return;
		}
	}else{
		try{
			
		$(window).unbind('beforeunload');	
			
		 var emailAddress     = document.getElementById('tbEemailLogin');
		 var passwordRegister = document.getElementById('tblpasswordLogin');
		 $('#btnLogin').attr('disable',true);
		 
		if ($("#tbEemailLogin").val()==""){
			showHideAlertLogin(1);
			goToError(emailAddress.id, '');
			return false;
		}else if(!validateEmail(document.getElementById('tbEemailLogin').value) || ($("#tblpasswordLogin").val()=="")){
		    showHideAlertLogin(11);
			goToError(emailAddress.id, '');
			return false;
		/*}
		
		var ruleList = {};
		var returnVarId = validateFormFields(obj, ruleList);
		if (returnVarId!==true){			
			$('#btnLogin').attr('disable',false);			
			showHideAlertLogin(1);			
			goToError(returnVarId, '');
			return false;
		}
		 
		 
		 if(!validateEmail(document.getElementById('tbEemailLogin').value)){
				 $('#btnLogin').attr('disable',false); 
				 showHideAlertLogin(1);
				 goToError(emailAddress.id,'');
				 return false;
		 }else if($("#passwordRegister").val() == ""){ 
				 $('#btnLogin').attr('disable',false); 
				 showHideAlertLogin(1);
				 goToError(passwordRegister.id,'');
				 return false;*/
		 }else{
			 $.ajax({
				type: "POST",
				url: "../mod_login/login.php.php",
				async: true,
				data: "tbEemailAddressForgot="+$("#tbEemailLogin").val()+"&tblpasswordRegister="+$("#tblpasswordLogin").val()+"&typeValidate=1",
				success: function(msgHtml){					
					if(msgHtml==0){
						 showHideAlertLogin(9);
						 $("#tbEemailLogin").val("");
						 $("#tblpasswordLogin").val("");
						 return false;
					}else{
						validateIfLogin(0, '');
						$("#tbEemailLogin").val("");
						$("#tblpasswordLogin").val("");
						return false;
					}
				},
				beforeSend: function(){				
				  $('#boxRegister').hide();
				  $('#loading').show();
				},
				complete: function(){
				  $('#loading').hide();
				  $(window).bind('beforeunload');	
				}
			});
		 }
		}catch (e){
			alert(e);
		}
	}
}

function showHideAlertLogin(action){
    if(action == 1){ // Mostramos el Alert y Ocultamos el login
        var htmlEmail = '<div id="text-register-title-text">Please fill in all fields.</div>';
        $('#boxRegister').hide();
        $('#boxAlert').show();
        $('#textInfoLogin').html(htmlEmail);
    }else if(action == 2){ // Oculta el Alert y se muestra el login
        $('#boxAlert').hide();
        $('#boxRegister').show();
    }else if(action == 3){ // Oculta el Login y se muestra forgot your password
        $('#boxRegister').hide();
        $('#boxForgot').show();
    }else if(action == 4){ // Oculta el forgot your password  y se muestra Login
        $('#boxForgot').hide();
        $('#boxRegister').show();
    }else if(action == 5){ // Oculta el forgot your password  y se muestra el Alert
        var htmlEmail = '<div id="box-register-title-forgot">Invalid Info</div><div id="text-register-title-text">Type an email address</div>';
        //$('#boxForgot').hide();
		 $('#boxAlertForgot').hide();
		 $('#boxAlertForgotInvalid').hide();
		 $('#boxForgot').show();       
        $('#textInfo').html(htmlEmail);
    }else if(action == 6){ // Oculta el Alert y se muestra el forgot your password
        $('#boxAlertForgot').hide();
		$('#boxAlertForgotInvalid').hide();
        //$('#boxForgot').show();
		$('#boxRegister').show();
		
    }else if(action == 7){ // Oculta el forgot your password  y se muestra el Alert
        var htmlEmail = '<div id="box-register-title-forgot">Invalid Info</div><div id="text-register-title-text">Please provide a valid Email Address.</div>';
        $('#boxForgot').hide();		
        $('#boxAlertForgotInvalid').show();
        $('#textInfoInvalid').html(htmlEmail);
    }else if(action == 8){ // Oculta el forgot your password  y se muestra el Alert
        var htmlEmail = '<div id="box-register-title-forgot">Forgot your password</div><div id="text-register-title-text">A new password has been sent to your account.</div>';
        $('#boxForgot').hide();
        $('#boxAlertForgot').show();
        $('#textInfo').html(htmlEmail);
    }else if(action == 9){ // Oculta el forgot your password  y se muestra el Alert
        var htmlEmail = '<div id="box-register-title-forgot">Message from system</div><div id="text-register-title-text">User/password combination is incorrect.</div>';
        $('#boxRegister').hide();
        $('#boxAlert').show();
        $('#textInfoLogin').html(htmlEmail);
    }else if(action == 10){ // Oculta el forgot your password  y se muestra el Alert
        $('#boxAlertForgot').hide();
        $('#boxForgot').show();		
    }else if(action == 11){ // Oculta el forgot your password  y se muestra el Alert
        var htmlEmail = '<div id="text-register-title-text">User/password combination is incorrect.</div>';
        $('#boxRegister').hide();
        $('#boxAlert').show();
        $('#textInfoLogin').html(htmlEmail);	
    }
    
}

function validateForgot(){
    try{
     var emailAddressForgot     = document.getElementById('emailAddressForgot');
     $('#btnForgot').attr('disable',true);
     if(!validateEmail(document.getElementById('emailAddressForgot').value)){
             $('#btnForgot').attr('disable',false); 
             showHideAlertLogin(5);
             goToError(emailAddressForgot.id,'');
             return false;
     }else{
         $.ajax({
            type: "POST",
            url: "../mod_login/forgot.php.php",
            async: true,
            data: "tbEemailAddressForgot="+$("#emailAddressForgot").val(),
            success: function(msgHtml){
                if(msgHtml==0){
                     //showHideAlertLogin(7);
					 showHideAlertLogin(7);
                     goToError(emailAddressForgot.id,'');
                     $("#emailAddressForgot").val("");
                     return false;
                }else{
                    showHideAlertLogin(8);
                    $("#emailAddressForgot").val("");
                    //setTimeout("showHideAlertLogin(4);",1000);
                    return false;
                }
            },
			beforeSend: function(){
			  $('#boxForgot').hide();			 	  
			  $('#loading').show();
			},
			complete: function(){
			  $('#loading').hide();
			}
        });
     }
    }catch (e){
        alert(e);
        return false;
    }
}

function validateIfLogin(booleanLogin, nameSession){	
    var fragmentoTexto;
    var url;
    if (booleanLogin==0){
        $.ajax({
            type: "POST",
            url: "../mod_login/login.php.php",
            async: true,
            data: "typeValidate=2",
            success: function(msgHtml){				
                if(msgHtml != 0){
                    $('#boxRegister').hide();
                    $('#boxSession').show();
                    fragmentoTexto = msgHtml.split('**');
                    $('#nameRegister').html(fragmentoTexto[0]);
                    if (fragmentoTexto[1]==1){
                        url = "../mod_registration/summary_clients.php";
                    }else{
                        url = "../mod_registration/summary_employee.php";
                    }
                    document.location = url;
                    //return false;
                }
            }
        });
    }else{
        $('#boxRegister').hide();
        $('#boxSession').show();
        $('#nameRegister').html(nameSession);
        return false;
    }
}

function ir()
  {
	  
    /*if (event.keyCode == 13)
    {
      validateLogin();
    }*/
  }
  
function logOutLogin(){
    $.ajax({
        type: "POST",
        url: "../mod_login/login.php.php",
        async: true,
        data: "typeValidate=3",
        success: function(){
            $('#boxSession').hide();
            $('#boxRegister').show();
			document.location = "../mod_registration/";
            return false;
        },
		beforeSend: function(){
		  $('#boxRegister').hide();
  		  $('#boxSession').hide();		  
		  $('#loading').show();
		},
		complete: function(){
		  $('#loading').hide();
		}
    });
}

function activeMenu(idMenu){
	
//	alert(idMenu)
    $('#'+idMenu).addClass('active');
}


function numberToCurrency1(amount){
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}
// end of function CommaFormatted()

//Colocamos ventana de carga de ajax
function blockUIAjaxSend(message){
    if(message==undefined){
        message="";
    }
    $.blockUI({
        showOverlay: true,
        css: {
            message: message,//'<h1>Please wait...</h1>',
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff',
            'z-index': '20000'
        }
    });
}
//Quitamos ventana de carga de ajax
function unBlockUIAjaxSend(){
    $.unblockUI();
}
