/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var dayNames = ['Lunedi','Martedi','Mercoledi','Giovedi','Venerdi','Sabato','Domenica'];

function load(url, params) {

    $('#content').append('<div id="progress"><img src="/img/mobile/ajax-loader.gif"><br>Loading...</div>');

    $(window).unbind('scroll');

    if( params ) {
        $('#content').load(url, params);
    } else {
        $('#content').load(url);
    }
}

$().ready(function(){
    $.ajaxSetup({        
        complete: function(xhr, status) {

            var obj = jQuery.parseJSON(xhr.responseText);
            var handler = typeof this.id == 'undefined' ? '#content' : this;

            if( obj ) {
                if( obj.success === false && obj.message) {
                    $(handler).ef_dialog('ERRORE: ' + obj.message, {type: 'error', autohide: false});
                } else if( obj.success === true && obj.message ) {
                    $(handler).ef_dialog(obj.message);
                }
            }

        }

    });

    $('#content').ajaxError(function(e, xhr, settings, exception){

        if( xhr.status == 401 ) {
            document.location = '/';
            return;
        }
    });
});

$.fn.ef_inputHint = function(value) {
    return this.each(function() {

        _onblur(this, value);

        $(this).blur(function() {
            _onblur(this, value);
        });

        $(this).focus(function() {
            _onfocus(this, value);
        });

    }    
)}

$.fn.ef_inputHintBG = function(value) {
    return this.each(function() {

        _onblurBG(this, value);

        $(this).blur(function() {
            _onblurBG(this, value);
        });

        $(this).focus(function() {
            _onfocusBG(this, value);
        });

    }
)}

$.fn.autosave = function(url, data) {
    return this.each(function() {

        var local_timeout = 0;
        var handler = this;

        var objects = this.tagName == 'INPUT' ? $(this) : $('input[type="text"],textarea', this);
        var default_values = {};

        update_default_values();

        objects.addClass('inactive');

        objects.keyup(function() {

            if( local_timeout ) {
                clearTimeout(local_timeout);
            }

            if( $(this).val() != default_values[ $(this).attr('name') ] ) {
                $(this).removeClass('inactive');
            }

            local_timeout = setTimeout(function() {

                var inactive_counter = 0;
                $.each(objects, function() { inactive_counter += $(this).hasClass('inactive') ? 1 : 0  });

                if( inactive_counter == objects.length ) {
                    return false;
                }

                $('<div id="autosave_loader" class="autosave_loader"><img src="/img/ajax-loader3.gif" /></div>').insertAfter(handler);
                var offset = $(handler).offset();
                
                offset.left += $(handler).width() - 10;
                offset.top += 6;
                
                $('#autosave_loader').offset( offset );

                var post_data = typeof data == 'undefined' ? {} : data;

                $.each(objects, function(index, value) {
                    post_data[ $(this).attr('name') ] = $(this).val();
                });
                
                $.ajax({
                   'url' : url,
                   'data' :  post_data,
                   'type' : 'POST',
                   'dataType' : 'json',
                   'success' : function(data) {
                       $(handler).next().remove();
                       objects.addClass('inactive');
                       
                       update_default_values();
                   }
                });
                
            }, 2000);
        });

        function update_default_values() {
            $.each(objects, function() { default_values[ $(this).attr('name') ] = $(this).attr('value');  });
        }

    });
}

$.fn.check_email_existance = function(verification_key) {
    return this.each(function() {

        var local_timeout = 0;
        var last_verified_email = '';

        $(this).keyup(function(event) {

            var handler = this;

            if( local_timeout ) {
                clearTimeout(local_timeout);
            }

            if( last_verified_email != $(this).val() ) {
                $('#email_checker_icon').remove();
            }
            
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

            if( reg.test( $(this).val() ) && last_verified_email != $(this).val() ) {

                local_timeout = setTimeout(function() {
                    
                    $.ajax({
                        'url': '/centers/check_email_existance/' + verification_key,
                        'data': { email: $(handler).val() },
                        'type': 'POST',
                        'dataType' : 'json',
                        'success' : function(data) {

                            if( !$('#email_checker_icon').length ) {
                                $('<img src="" class="input-icon" id="email_checker_icon" style="display: inline;" />').insertAfter(handler);
                            }

                            $('#email_checker_icon').attr('src', data.exists ? '/img/icon_disabled.png' : '/img/icon_enabled.png');

                            last_verified_email = $(handler).val();
                        }
                    });

                }, 1000);
            }
           
        })

    })
}

$.fn.ef_dialog = function(msg, params) {
    return this.each(function() {
        params = typeof params == 'undefined' ? {} : params;
        params['handler'] = this;
        dialog(msg, params);
    }
)}


$.fn.password_strength = function() {
    return this.each(function() {

        $('<img src="/img/icon_success_orange.png" class="password-strength-icon"/>').insertAfter(this);

        $(this).keyup(function() {
            if( passwordStrength($(this).val()) ) {
                $(this).next().attr('src', '/img/icon_enabled.png');
            } else {
                $(this).next().attr('src', '/img/icon_success_orange.png');
            }

            if( $(this).val().length ) {
                $(this).next().show();
            } else {
                $(this).next().hide();
            }
        });
        
    }
)}

$.fn.watch_changes = function(callback_onStateChange) {
    return this.each(function() {

        var default_val = $(this).val();

        $(this).addClass('inactive');

        $(this).bind('keyup change', function(event) {

            var state_changed = event.type == 'change' ? true : false;

            if( state_changed || default_val != $(this).val() ) {
                if( $(this).hasClass('inactive') ) {
                    $(this).removeClass('inactive');
                    state_changed = true;
                }
            }
//             else {
//                if( !$(this).hasClass('inactive') ) {
//                    $(this).addClass('inactive');
//                    state_changed = true;
//                }
//            }

            if( state_changed && typeof callback_onStateChange != 'undefined' ) {
                callback_onStateChange(this);
            }
        });

    });
}

$.fn.form_submit = function(url, afterSend, beforeSend) {

    return this.each(function() {

        var processing = false;        
        var form = this;
        var inputs_count = $('input[type="text"],text,select,input[type="password"],input[type="radio"]', form).length;
        
        $('input.strength', this).password_strength();

        $('input[type="text"],text,select,input[type="password"],input[type="radio"]', this).watch_changes(function() {

            if( $('.inactive', form).length == inputs_count ) {
                $('.submit', form).addClass('disabled');
            } else {
                $('.submit', form).removeClass('disabled');
            }
        });
        
        $('.submit', this).click(function() {

            if( processing || $(this).hasClass('disabled') ) {
                return false;
            }

            var error = false;

            $(form).find('input,select').each(function() {
                if( $(this).hasClass('required') && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder') ) ) {
                    $(this).addClass('error');                    
                    error = true;
                } else {
                    $(this).removeClass('error');
                }
            });

            if( !error ) {

                if( typeof beforeSend != 'undefined' ) {
                    beforeSend();
                }

                processing = true;                

                $.ajax({
                    'type': 'POST',
                    'url': url,
                    'dataType': 'json',
                    'data': $(form).find('input,select,input[type="hidden"]').serialize(),
                    success: function(data) {

                        processing = false;

                        if( typeof afterSend != 'undefined' )  {
                            afterSend(data);
                        }
                    },
                    complete: function(jqXHR, textStatus) {
                        processing = false;                        
                    }
                });
                
            }
            
        });

    }
    
)};

function getDate() {
    var d = new Date();

    localTime = d.getTime();

    localOffset = d.getTimezoneOffset() * 60000;
    utc = localTime + localOffset;
    offset = 1;
    
    return new Date(utc + (3600000*offset));
}

function _onfocus(handler, value, class_name) {

    if( !class_name ) class_name = 'inactive';

    if( handler.value == value) {
        handler.value = '';        
    }
    $(handler).removeClass(class_name);

}

function _onblur(handler, value, class_name) {

    if( !class_name ) class_name = 'inactive';

    if( handler.value == '') {
        handler.value = value;        
        $(handler).addClass(class_name);
    } else {
        $(handler).removeClass(class_name);
    }

}

/* FUNCTIONS used on www.easyfields.com for Login and Password Fields */
function _onfocusBG(handler, value, class_name) {

    if( !class_name ) class_name = 'inactive';
    
    $(handler).css('background', 'white');    
    $(handler).removeClass(class_name);

}

function _onblurBG(handler, value, class_name) {

    if( !class_name ) class_name = 'inactive';

    if( handler.value == '') {
        $(handler).css('background', 'white url(' + value + ') no-repeat 7px 6px');
        $(handler).addClass(class_name);
    } else {
        $(handler).removeClass(class_name);
    }

}
/*END*/

var calendar_sport_id = 0;

function calendar_select_sport(sport_id) {
    calendar_sport_id = sport_id;
    load('/reservation/calendar/' + sport_id);
}


function update_time_line_position(start_schedule, end_schedule) {
    var now = new Date();

    var hours = now.getHours();
    var minutes = now.getMinutes();

    var height = $('.right_bottom_panel').height();

    local_end_schedule = end_schedule + 60;

    var top = height * (hours * 60 + minutes - start_schedule) / ( local_end_schedule - start_schedule );

    if( top > height ) { top = height - 6; }
    if( top < 0 ) { top = 6; }

    $('#time_line').css('top', top + 'px');

    setTimeout(function() { update_time_line_position(start_schedule, end_schedule); }, 60000);
}

function calendar_today_click() {
    load_calendar(0);
}

function calendar_on_select(dateText, inst) {
    var dt = new Date(dateText);
    load_calendar(dt.getTime()/1000);
}

var calendar_client_id = 0;

/*
 * params { sport_id, time, client_id }
 */
function show_calendar(sport_id, client_id) {

    calendar_client_id = client_id ? client_id : 0;

    load('/reservation/calendar/' + sport_id, {'client_id': calendar_client_id});
}

function load_calendar(time) {
    $('#content').load('/reservation/calendar/' + calendar_sport_id + '/' + time, {'client_id': calendar_client_id});
}

function next_calendar(current_week) {
    w = current_week + 3600 * 24 * 7;
    $('#content').load('/reservation/calendar/' + calendar_sport_id + '/' + w, {'client_id': calendar_client_id});
}

function previous_calendar(current_week) {
    w = current_week - 3600 * 24 * 7;
    $('#content').load('/reservation/calendar/' + calendar_sport_id + '/' + w, {'client_id': calendar_client_id});
}

var frame_handler_call = null;

function hide_reservation_dialog() {
    $('#sport_reservation_dialog').parent().fadeOut(600);
    $('#calendar').fadeTo('slow', 1);
}

/*
 * client_id and use_credit are optional
 */
function sport_reservation_dialog(handler, day, time) {

    if( !$(handler).hasClass('available') ) {
        return false;
    }

    $.post('/reservation/choose_field/' + calendar_sport_id, {'day_time':day, 'time':time, 'client_id':calendar_client_id}, function(html) {
        frame_handler_call = handler;
        $('<div class="new-reservation popup-dialog"><img src="/img/btn_red_delete.png" class="close_dialog_btn" onclick="hide_reservation_dialog();" />' + html + '</div>').prependTo('#content');
        
        $('#calendar').fadeTo('slow', 0.25);

    });
}

function reserve_field(callback) {

    var selector = '#last_name,#first_name';

    if( typeof ADMIN == 'undefined') {
        selector += ',#phone,#email';
    }

    var ret = false;

    $(selector).each(function() {
        if( $(this).val() == '' ) {
            $(this).parent().addClass('field_required');
            ret = true;
        } else {
            $(this).parent().removeClass('field_required');
        }
    });

    if( ret ) {
        return false;
    }

    $.ajax({
       'url' : '/reservation/reserve',
       'type' : 'POST',
       'data': $('#sport_reservation_dialog').find('input[value!="0"]').serialize() + '&client_id=' + calendar_client_id,
       'dataType' : 'json',
       'success' : function(data) {
            if( data.success ) {

                if( typeof callback == 'undefined' ) {

                    $(frame_handler_call).find('.fields_count').children('img:first').remove();

                    if( !$(frame_handler_call).find('.fields_count').children('img').size() ) {
                        $(frame_handler_call).removeClass('available');
                        $(frame_handler_call).addClass('occupied');
                    }

                    hide_reservation_dialog();

                    show_reserve_confirmation_dialog(data.id);

                    if( calendar_client_id ) {
                        $('#credits_amount').html(parseInt($('#credits_amount').html()) - 1);

                        if( $('#credits_amount').html() == "0" ) {
                            load('/subscriptions/view');
                        }
                    }
                } else {
                    callback(data);
                }

            } else if( data.blocked ) {
                $('#content').ef_dialog('', {type: 'account_blocked', autohide: true, color: 'red', interval: 5000});
            }
       }
    });

}

function show_reserve_confirmation_dialog(reservation_id) {

    $('#confirm_reservation_popup').load('/reservation/confirm_popup/' + reservation_id, function() {
            $(this).fadeIn(600);
    });
}

function hide_confirm_reservation_popup() {
    $('#confirm_reservation_popup').fadeOut(600);
}


var dialog_handler = null;

function dialog(text, params) {

    if( !params ) params = {};

    type = params['type'] ? params['type'] : 'success';
    autohide = (typeof params['autohide'] == 'undefined') ?  1 : params['autohide'];
    dialog_handler = params['handler'] ? params['handler'] : document.getElementById('content');

    if( params['onconfirm'] ) { onconfirm = params['onconfirm']; }

    if( type == 'delete' || type == 'error' || params['color'] == 'red') {
        $('#message div:first-child').addClass('red');
    } else {
        $('#message div:first-child').removeClass('red');
    }

    $('#content_overlay').show();
    $('#content_overlay').css({"height" : $('#content').height() });

    $(dialog_handler).fadeTo(0, 0.25);
    $('#message').show();

    $('#dialog_message').html( $('#message_' + type).html() );
    
    if( params['content'] || text ) {
        $('#dialog_text').html( (params['content'] ? $('#' + params['content']).html() : text) );
    }

    var offset = $(dialog_handler).offset();
    //70px - menu height
    var top = $(dialog_handler).height() * 0.3 + offset.top;
    var left = offset.left;
    $('#message > div').css({"top" : top, "left" : left });
    $('#message > div').css({"width" : $(dialog_handler).width()});

    if( autohide ) {
        setTimeout(function() {
           hide_dialog();
        }, params['interval'] ? params['interval'] : 2000);
    }
}

function hide_dialog() {
    $('#content_overlay').hide();
    $(dialog_handler).fadeTo(400, 1);

    $('#message').hide();
}

var onconfirm = null;

function dialog_on_confirm() {
    if( onconfirm ) {
        onconfirm();
        hide_dialog();
    }

    onconfirm = null;
}

function show_element_loader(obj) {
    obj.children(':visible').fadeTo(300, 0.25);
    obj.append('<img src="/img/ajax-loader2.gif" id="loader" class="loader" />');
}

function remove_element_loader(obj) {
    obj.children(':visible').fadeTo(0, 1);
    obj.find('#loader').remove();
}


function preload(images) {

    for(var index in images) {
        var heavyImage = new Image();
        heavyImage.src = images[ index ];
    }

}

function select_field(handler, sports_field_id) {

    $(handler).parent().children().removeClass('selected');
    $(handler).addClass('selected');

    $('#sports_field_id').val(sports_field_id);
    $('#sport_field_name').html( $(handler).find('.field_name').html() );

    if( typeof facebook_user_profile != 'undefined' && facebook_user_profile ) {
        $('#last_name').val( facebook_user_profile.last_name );
        $('#first_name').val( facebook_user_profile.first_name );
        $('#email').val( facebook_user_profile.email );
        $('#phone').val( facebook_user_profile.phone );
    }
}


function passwordStrength(password) {
    
    var desc = new Array();

    desc[0] = "Very Weak";
    desc[1] = "Weak";
    desc[2] = "Better";
    desc[3] = "Medium";
    desc[4] = "Strong";
    desc[5] = "Strongest";

    var score   = 0;

    //if password bigger than 6 give 1 point
    if (password.length > 6) score++;

    //if password has both lower and uppercase characters give 1 point
    if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;

    //if password has at least one number give 1 point
    if (password.match(/\d+/)) score++;

    //if password has at least one special caracther give 1 point
    if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;

    //if password bigger than 12 give another 1 point
    if (password.length > 12) score++;


    return score < 3 ? false : true;
}


function check_window_size() {
    if( $(window).height() < $(document).height() ) {
        $('#footer_arrow').show();
    } else {
        $('#footer_arrow').hide();
    }
}

