var ui = {
    // -=Functions that attach jquery or plugins to DOM elements=- //
    attach : {},
    // -=Functions that attach ui.attach.*() to pages=- //
    page : {},
    // -=Google map-related ui methods=- //
    gm : {},
    // -=All DOM elements manipulated by javascript referenced here=- //
    elements : {}
};

// -=Shortcut to ui.elements!=- //
e = ui.elements = {
    // -=Links (<a>) that shall run ajax requests =- //
    ajax_link                : "a.ajax",
    // -=Forms <form> that shall run ajax requests=- //
    ajax_form                : "form.ajax",
    add_comment              : '#add_comment',
    comment                  : '.comment',
    logo_wrapper             : '.main_logo_wrapper',
    logo                     : '#logo',
    global_message_wrapper   : '#top_content',
    global_message           : '#global_message',
    message_wrapper          : '.message_wrapper',
    be_editable              : '.be_editable',
    city2airline_header      : '#city2airline .header_middle',
    city2airline             : '#city2airline .data'
}





// -=Manual ajax requests=- //
ui.ajax = function(type, data) {

    // -=Types listing=- //
    var types = {

    }

    if (type == 'city2airline') {
        id = data;
        newurl = s.webroot+'airlines/city/'+id
        $('.city2airline_header').html('Loading...');
        $('.city2airline').fadeOut(300);
    }

    if (type == 'route2airline') {
        id1 = data.id1;
        id2 = data.id2;
        newurl = s.webroot+'airlines/citypair/'+id1+'/'+id2;
        $(e.city2airline_header).html('Loading...');
        $(e.city2airline).fadeOut(300);
    }

    if (type == 'welcome') {
        newurl = s.webroot+'visitors/welcome/';
    }

    if (type == 'login') {
        newurl = s.webroot+'login';
    }

    if (type == 'logout') {
        newurl = s.webroot+'logout';
    }

    if (type == 'registration') {
        newurl = s.webroot+'registration';
    }


    $.ajax({
        type     : "GET",
        url      : newurl,
        dataType : "json",
        success  : function(data, status) { ajax.handle  (data, status); }
    });

}





/**
 * ui.page = {}
 * Methods that apply appropriate ui.attach.*() functions depending on current page
 *
**/
// -=Other pages (login, register, contact=- //
ui.page.standard = function( context ) {

    ui.attach.ajax        ('body');
    ui.attach.search      ('body');
    ui.attach.smartfields ('body');


}

// -=Home page=- //
ui.page.home = function() {
console.group('ui.page.home()');


    ui.attach.ajax        ('body');
    ui.attach.search      ('body');
    ui.attach.smartfields ('body');

    ui.attach.tabs        ('#airlines');
    ui.attach.tabs        ('#browse_airlines');
    ui.attach.cycles      ('body');
    // ui.attach.search_hl('body');

    if (s.gm) {
        ui.gm.pop_cities();
    }

console.groupEnd('ui.page.home()');
}


// -=Airline view page=- //
ui.page.airline = function() {

    ui.attach.ajax        ('body');
    ui.attach.search      ('body');
    ui.attach.smartfields ('body');

    ui.attach.tabs          ('body');
    ui.attach.pager         ('body');
    ui.attach.comments_tabs ('body');
    ui.attach.editables     ('body');
    ui.attach.anchors_scroll('body');
    ui.attach.starratings   ('body');
    $('.comments .comments_set:eq(0)').show();

    if (s.gm) {
        page = s.page;
        airline_code = page.replace('airline\.view\.','');
        ui.gm.pop_routemap(airline_code);
    }

}





/**
 * ui.attach = {}
 * Collection of methods that apply jquery or plugins to DOM
 *
**/

ui.attach.ajax = function( context ) {
console.group("ui.attach.ajax("+context+")");

    $(context).find(e.ajax_link).ajaxlink();
    $(context).find(e.ajax_form).ajaxform();

console.groupEnd("ui.attach.ajax("+context+")");
}






ui.attach.starratings = function ( context ) {
console.group("ui.attach.starratings("+context+")");

    $('input[@type=radio].star').rating();

console.groupEnd("ui.attach.starratings("+context+")");
}



ui.attach.search = function( context ) {
console.group("ui.attach.search("+context+")");

    form = $('#airline_search_form');

    $(context).find('.airline_search').each( function(i) {
        var url = s.webroot+"search";
        $(this).suggest(
            url,
            { onSelect: function() { $(form).submit() } }
        );
    });

console.groupEnd("ui.attach.search("+context+")");
}





ui.attach.smartfields = function(context) {
console.group("ui.attach.smartfields("+context+")");

    $(context).find('.smartfield, .be_smartfield').smartfield();

console.groupEnd("ui.attach.smartfields("+context+")");
}





ui.attach.comments_tabs = function( context ) {
console.group("ui.attach.comments_tabs("+context+")");

    $('#latest-comments', context).bind('click',function() {
        $('#greatest-comments').removeClass('ui-tabs-selected').addClass('ui-tabs-disabled');
        $(this).addClass('ui-tabs-selected');
        $('.comments .comments_set:visible').fadeOut(500);
        return false;
    })

    $('#greatest-comments', context).bind('click',function() {
        $('#latest-comments').removeClass('ui-tabs-selected').addClass('ui-tabs-disabled');
        $(this).addClass('ui-tabs-selected');
        $('.comments .comments_set:visible').fadeOut(500);
        return false;
    })


console.groupEnd("ui.attach.comments_tabs("+context+")");
}




ui.attach.editables = function() {

    var element = ".be_editable_area";

    var options = {
         editable_element : '.be_editable',
         editable_control : '.be_editor',
         input_class      : 'editable',
         type             : 'textarea',
         cancel           : 'Cancel',
         submit           : 'Done',
         indicator        : "<p>Saving...</p>",
         // height           : '200px',
         callfront : function( old_settings, proceed ) {

            new_settings = old_settings || {};

            jQuery.ajax({
                'url'      : s.webroot + 'prepare_correction',
                'type'     : 'post',
                'data'     : { 'text' : new_settings.text || '' },
                'processData' : true,
                'success'  : function( data, status ) {
                    new_settings.text = data;
                    proceed( new_settings );
                },
                'error' : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.warn('Couldn\'t prepare text for editing');
                    // this; // the options for this ajax request
                }
            });
         },
         callback : function(data) {
            ajax.handle(data);
            // $(element).find(options.editable_element).html(data.data.content);
         }
    }

      $(element).each( function() {
            $(this).find(e.be_editable).wrap('<div class="be_editable_wrapper"></div>');
            $(this).editable( s.webroot+'correction', options );
      });




}





ui.attach.anchors_scroll = function ( context ) {

context = context || 'body';

// -=ScrollTo=- //
$(context).find('a[href^=#]:not([href=#])').not('.be_tab_control').click( function() {
    var x = $(this.hash);
    if( x.length ) {
    $('html').animate( { scrollTop: x.offset().top - 300 }, 1500 );
    // location.hash = this.hash;
    return false;
    }
});


}




ui.attach.tabs = function(context) {
console.group("ui.attach.tabs("+context+")");



    $('ul.be_tabs',context).tabs( { fx: { opacity: 'toggle' } } );

    /*
    $('ul.be_tabs',context).each( function(i) {
        wrapper = $(this).parent();
        heights = [];
        $('.tab-content',context).each( function(y) {
            console.warn('height: ' +$(this).height() );
            heights.push( $(this).height() );
        })
        max_height = Math.max.apply(null, heights);
        console.warn('Max height: ' +max_height);
        $('.tab-content:eq(0)',context).parent().height((max_height+55)+'px');
    });
    */

console.groupEnd("ui.attach.tabs("+context+")");
}




ui.attach.pager = function(context) {
console.group("ui.attach.pager("+context+")");

if ($('.comment',context).length < 1) return;

    // -=Auto-height hehe=- //
    heights = [];
    $('.comments_set').each( function(y) {
        console.warn('height: ' +$(this).height() );
        heights.push( $(this).height() );
    })
    max_height = Math.max.apply(null, heights);
    console.warn('Max height: ' +max_height);
    $('.comments_set').height((max_height)+'px');
    $('.comments').height((max_height+30)+'px');


    // -=Hide all but 1st=- //
    $('.comments_set:gt(0)').hide();



    $('#be_comments_pager').html('');
    $('#be_comments_pager').pagination( $('.comment').length, {
		items_per_page: 3,
		callback: ui.pager_callback,
		next_text : 'More',
        prev_text : 'Less',
        link_to   : window.location.href.replace('#','')+'/comments/page/__id__'
	});

console.groupEnd("ui.attach.pager("+context+")");
}




ui.pager_callback = function(new_page_id) {

    if (s.ajax) {
        $('.comments_set:visible').fadeOut(300,function() {
            $('.comments_set_'+new_page_id).fadeIn(300);
        })
        return false;
    } else {
        $('.comments_set:visible').fadeOut(300,function() {
            $('.comments_set_'+new_page_id).fadeIn(300);
        })
        return false;
    }

}



ui.attach.cycles = function(context) {

    $('.fading', context).cycle( {
        fx          : 'fade',
        speed       : 1000,
        timeout     : 8000,
        pause:   1
    } );

}



ui.attach.search_hl = function(context) {

    el = $('#subheader_search');

    $(el).bind('focus.hl', function () {
        $(el).addClass('focused');
    });

    $(el).bind('blur.hl', function () {
        $(el).removeClass('focused');
    })

}

