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

function load(url, params) {

    if( !params ) params = {};

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

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

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

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

            if( obj.success === false ) {
                $(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 = base;
            return;
        }


        /*$.ajax({
           'url' : base + 'errors/transport',
           'global' : false,
           'type' : 'POST',
           'data' : {   'data[Error][request_url]': settings.url,
                        'data[Error][request_type]': settings.type,
                        'data[Error][request_data]': settings.data,
                        'data[Error][response_status]': xhr.status,
                        'data[Error][response_text]': xhr.responseText},
           'dataType' : 'json'
        });*/


    });
});

$.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_dialog = function(msg, params) {
    return this.each(function() {
        params = typeof params == 'undefined' ? {} : params;
        params['handler'] = this;
        dialog(msg, params);
    }
)}


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);
    }

}

var calendar_sport_id = 0;

function calendar_select_sport(sport_id) {
    calendar_sport_id = sport_id;
    load(webroot + '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);
}

function load_calendar(time) {
    $('#content').load(webroot + 'reservation/calendar/' + calendar_sport_id + '/' + time);
}

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

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

var frame_handler_call = null;

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

function sport_reservation_dialog(handler, day, time) {

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

    $('#sport_reservation_dialog').load(webroot + 'reservation/choose_field/' + calendar_sport_id, {'day_time':day, 'time':time}, function() {

        frame_handler_call = handler;

        var offset = $(handler).offset();

        $('#sport_reservation_dialog').fadeIn(600);
        //$('#sport_reservation_dialog').offset({top: offset.top + 20});

        document.getElementById('sport_reservation_dialog').style.left = '250px';
        document.getElementById('sport_reservation_dialog').style.top = '15px';

        $('#calendar').fadeTo('slow', 0.25);

    });
}

function reserve_field() {

    $.ajax({
       'url' : webroot + 'reservation/reserve',
       'type' : 'POST',
       'data': $('#sport_reservation_dialog').find('input[value!="0"]').serialize(),
       'dataType' : 'json',
       'success' : function(data) {
            if( data.success ) {
                $(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);
            }
       }
    });

}

function show_reserve_confirmation_dialog(reservation_id) {

    $('#confirm_reservation_popup').load(webroot + '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') {
        $('#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() );
    $('#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();
        }, 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;
}
