var regis = new Array();
var emails = new Array();
var num = 0;
var numEmails = 0;
function categorySelected(cat){
    location.href= Settings.base_url + 'eventspub/index/' + cat;
}
function stepTwo(){
    if(arraySize(regis) == 0 && $('#others').attr('checked')){
        $('#addError').html('Please enter attendee information.');
        $('#addError').slideToggle("slow");
        setTimeout("$('#addError').slideToggle(1000)", 2500);
    }
    else {
        $('#stepone').toggle();
        //printArray();
        setTitles();
        $('#steptwo').toggle();
    }
}
function setTitles(){
    var cant = arraySize(regis);
    var placesFree = $('#placesFree').attr('value');
    //if($('#me').attr('checked') || $('#meandot').attr('checked')){
        cant++;
    //}
    var cost = 0;
    var title = '';
    var subTitle = 'Please enter your payment options for the total of <span style="color: #72a64b">$';
    if(cant > placesFree){
        cost = $('#cost').html()*placesFree;
        title = 'Registering ' + placesFree + ' attendees';
        subTitle += cost + ' (' + placesFree + ' attendees)</span>:';
    }
    else{
        cost = $('#cost').html()*cant;
        title = 'Registering ' + cant + ' attendees';
        subTitle += cost + '</span>:';
    }
    if($('#me').attr('checked') || $('#meandot').attr('checked')){
        title += ' (including yourself)';
    }
    if(cost == '0'){
        $('#payment').addClass('ocult');
        $('#subTitle').addClass('ocult');
    }
    subTitle += '<br/><small> Please send a single payment for the full amount due.</small>'
    $('#titleStepTwo').html(title);
    $('#subTitle').html(subTitle);
}
function addRegistrant(){
    if($('#other_firstname').attr('value') == ''){
        $('#addError').html('First Name not be blank');
        $('#addError').slideToggle("slow");
        setTimeout("$('#addError').slideToggle(1000)", 2500);
    }
    else if($('#other_lastname').attr('value') == ''){
        $('#addError').html('Last Name not be blank');
        $('#addError').slideToggle("slow");
        setTimeout("$('#addError').slideToggle(1000)", 2500);
    }
    else if($('#other_email').attr('value') == '' || !isEmail('other_email')){
        $('#addError').html('Email is invalid');
        $('#addError').slideToggle("slow");
        setTimeout("$('#addError').slideToggle(1000)", 2500);
    }
    else{
        var email = $('#other_email').attr('value');
        var idEvent = $('#Eventid').attr('value');
        $.get(Settings.base_url + "event_registrations/isRegistered/"+idEvent+"/"+email, {},
            function(data){
                isRegistered = data;
                if(isRegistered == '1'){
                    $('#addError').html('The User has already been registered for this event');
                    $('#addError').slideToggle("slow");
                    setTimeout("$('#addError').slideToggle(1000)", 2500);
                }
                else{
                    $('#addError').html('');
                    var aux = new Array();
                    var placesFree = $('#placesFree').attr('value');
                    aux['first'] = $('#other_firstname').attr('value');
                    aux['last'] = $('#other_lastname').attr('value');
                    aux['email'] = $('#other_email').attr('value');
                    append = "<div id='other" + num + "' class='ocult'><table><tr><td style='width: 300px;'>" + aux['first'] + ' ' + aux['last'] + ' - ' + aux['email']
                    + "</td><td><a href='javascript:delRegistrant(" + num + ")'>remove</a></td><td style='width: 167px;'>";
                    /* La variable regis contiene los valores de los registrantes agregados
                     * pero no tiene al usuario que esta registrando por eso para comparar
                     * se agrega uno en caso de que tambien se esta registrando a si mismo
                    */
                    var cantmax = 0;
                    if($('#me').attr('checked') || $('#meandot').attr('checked'))
                        cantmax = arraySize(regis)+1;
                    else
                        cantmax = arraySize(regis);
                    if(cantmax >= placesFree ){
                        append += "add in the waiting list";
                    }
                    append += "</td></tr></table></div>";
                    $('#othernames').append(append);
                    regis[num] = aux;
                    $('#other' + num).slideDown("slow");
                    clearFields('addreg');
                    num++;
                }
            });
    }
}
function delRegistrant(id){
    delete regis[id];
    //regis[id] = null;
    $('#other' + id).slideUp();
    $('#other' + id).remove();
    dibujarLista();
}
function dibujarLista(){
    var placesFree = $('#placesFree').attr('value');
    var append = '';
    $('#othernames').slideUp();
    $('#othernames').empty();
    var ind = 0;
    for(key in regis){
        append += "<div id='other" + key + "'><table><tr><td style='width: 300px;'>"
        + regis[key]['first'] + ' ' + regis[key]['last'] + ' - ' + regis[key]['email']
        + "</td><td><a href='javascript:delRegistrant(" + key + ")'>remove</a></td><td style='width: 167px;'>";
        
        if(ind+1 >= parseInt(placesFree)){
            append += "add in the waiting list";
        }
        append += "</td></tr></table></div>";
        ind++;
    }
    $('#othernames').append(append);
    $('#othernames').slideDown("slow");
}
function addRecipient(){
    if($('#aditional_email').attr('value') == '' || !isEmail('aditional_email')){
        $('#addEmailError').html('Please enter a valid Email');
        $('#addEmailError').slideToggle("slow");
        setTimeout("$('#addEmailError').slideToggle(1000)", 2500);
    }
    else{
        $('#addEmailError').html('');
        var email;
        email = $('#aditional_email').attr('value');
        append = "<div id='email" + numEmails + "' class='ocult'><table><tr><td>" + email
        + "</td><td><a href='javascript:delRecipient(" + numEmails + ")'>remove</a></td>" +
        "</td></tr></table></div>";
        $('#otheremails').append(append);
        emails[numEmails] = email;
        $('#email' + numEmails).slideDown("slow");
        clearFields('addemail');
        numEmails++;
        $('#send').attr('disabled', false);
    }
}
function delRecipient(id){
    delete emails[id];
    //regis[id] = null;
    $('#email' + id).slideUp();
    $('#email' + id).remove();
    if(arraySize(emails) == 0){
        $('#send').attr('disabled', true);
    }
}
/*
* Vacía los campos de la tabla con id table
* */
function clearFields(table){
    $('#' + table + " input[type='text']").each(function(){
        this.value = "";
    });
}
/*Cambia la visibilidad del los campos según el tipo de pago elegido*/
function selectPayType(sel){
    $('#paytext > *').each(function(){
        if(this.style.display == 'block')
            $(this).toggle();
    });
    var name = '#'+sel.value;
    $(name).toggle();
}
/*Cambia los campos habilitados segun la seleccion*/
function selRegisters(sel){
    if(sel.value == 'me'){
        $('#other_firstname').attr('disabled', 'disabled');
        $('#other_lastname').attr('disabled', 'disabled');
        $('#other_email').attr('disabled', 'disabled');
        $('#btAddReg').attr('disabled', 'disabled');
    }else{
        $('#other_firstname').attr('disabled', '');
        $('#other_lastname').attr('disabled', '');
        $('#other_email').attr('disabled', '');
        $('#btAddReg').attr('disabled', '');
    }
}
function saveRegistration(){
    var mensaje = dataVerify();
    createHidden();
    if(mensaje != ''){
        $('#billingError').html(mensaje);
    }
    else{
        $('form').submit();
    }
}

function dataVerify(){
    var mensaje = "Incorrect data: <br />";
    if($('#BillingInfoFirstName').attr('value') == ''){
        mensaje += "<div class='errorLine'>First Name</div>";
    }
    if($('#BillingInfoLastName').attr('value') == ''){
        mensaje += "<div class='errorLine'>Last Name</div>";
    }
    if($('#BillingInfoAddress').attr('value') == ''){
        mensaje += "<div class='errorLine'>Address</div>";
    }
    if($('#BillingInfoCity').attr('value') == ''){
        mensaje += "<div class='errorLine'>City</div>";
    }
    if($('#BillingInfoState').attr('value') == ''){
        mensaje += "<div class='errorLine'>State</div>";
    }
    if($('#BillingInfoZipcode').attr('value') == ''){
        mensaje += "<div class='errorLine'>Zip Code</div>";
    }
    if($('#BillingInfoPhone').attr('value') == ''){
        mensaje += "<div class='errorLine'>Phone</div>";
    }
    /*if($('#BillingInfoFax').attr('value') == ''){
        mensaje += "<div class='errorLine'>Fax</div>";
    }*/
    if(!$('#Porder').attr('checked')
       && !$('#Check').attr('checked')
       && !$('#Ccard').attr('checked') && $('#cost').html() != '0' && $('#placesFree').attr('value') > 0){
        mensaje += "<div class='errorLine'>Payment Type not selected</div>";
    }
    else if($('#Porder').attr('checked')
             && $('#BillingInfoPONumber').attr('value') == ''){
        mensaje += "<div class='errorLine'>PO Number</div>";
    }
    else if($('#Check').attr('checked')
             && $('#BillingInfoCheckNumber').attr('value') == ''){
        mensaje += "<div class='errorLine'>Check Number</div>";
    }
    if(mensaje == 'Incorrect data: <br />'){
        return '';
    }else{
        return mensaje;
    }
}
function createHidden(){
    var cant = arraySize(regis);
    if(cant > 0){
        for(key in regis){
            append += hidden('EventRegistration' + key + 'Firstname', regis[key]['first'], "data[EventRegistration][" + key + "][firstName]");
            append += hidden('EventRegistration' + key + 'Lastname', regis[key]['last'], "data[EventRegistration][" + key + "][lastName]");
            append += hidden('EventRegistration' + key + 'Email', regis[key]['email'], "data[EventRegistration][" + key + "][email]");
        }
        $('#othernames').append(append);
    }
}
function hidden(id, text, name){
    return "<input id='" + id + "' type='hidden' value='" + text + "' name='" + name + "'>";
}
function printArray() {
    for(key in regis){
        console.log(key);
        console.log(regis[key]['first']);
        console.log(regis[key]['last']);
        console.log(regis[key]['email']);
    }
}
function arraySize(array){
    var size = 0;
    for(key in array){
        size++;
    }
    return size;
}
function activeRegisterButton(){
    if(!$('#acceptconditions').attr('checked')){
        $('#register').attr('disabled', 'disabled');
    }
    else{
        $('#register').attr('disabled', '');
    }
}

function activeSubmitButton(){
    if(!$('#acceptphotosubmit').attr('checked')){
        $('#submitpayment').attr('disabled', 'disabled');
    }
    else{
        $('#submitpayment').attr('disabled', '');
    }
}

function isEmail(field) {
    var txt = $('#' + field).attr('value');
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
        return true;
    else
        return false;
}

function sendEmails(){
    window.onbeforeunload = null;
    var cant = arraySize(emails);
    if(cant > 0){
        for(key in emails){
            append += hidden('Email' + key, emails[key], "data[Email][" + key + "]");
        }
        $('#otheremails').append(append);
    }
    $('form').submit();
}

function showOthers(){
    $('#otherLocations').slideToggle("slow");
}
