$(document).ready(function()
{
    /*allow password inputs with default values*/
    //toggle input default vals
    jQuery('input.toggle').toggleVal();

    //password input w default value
    jQuery('.pass-clear').show();
    jQuery('.pass').hide();

    //select hidden field onfocus
    jQuery('.pass-clear').focus(function()
    {
        jQuery(this).hide();
        jQuery(this).next().show().focus();
    });

    //go back to default value onblur
    jQuery('.pass').blur(function()
    {
        if(jQuery(this).val() == '')
        {
            jQuery(this).prev().show();
            jQuery(this).hide();
        }
    });

    // Show the wiki-Ico when mouse is out the wrapper:
    $("#content").hover(
      function () {
        $("#background_wiki_link").fadeOut();
      },
      function () {
        $("#background_wiki_link").fadeIn();
      }
    );
    
    //Switch interface language
    //Switch learn language
    jQuery('#interface_lang, #target_lang').change(function()
    {
      // this.form.submit();
      var redirto = $("option:selected",this).val();
      document.location.href = redirto;
    });
    
    // We'll encapsulate our .qtip() call in your .live() handler method
    $('[title]').live('mouseover', function(event) {
        //bind tips to title tags
        mylingo.ui.tooltip.show($(this), null, event);
    });
    
            //store current url on a cookie
        $('a.facebook.login, a.facebook.signup').click(function() {
            
            $.ajax({
                dataType: 'json',
                url: '/facebook/log',
                type: 'post'
            });

            $.cookie('previous_url', window.location.pathname, {path: '/',domain:'.mylingo.org'} );
        });
    
    //background link open in modal
    $('#background_wiki_link').click(function(){
        mylingo.ui.modal.open(this, {
            content: {
                text: '<iframe src="' + $(this).attr('href') + '" style="width:100%;height:100%;"></iframe>',
                title: {
                    text: 'Wikipedia',
                    button: 'Close'
                }
            },
            style: {
                classes: 'ui-tooltip ui-tooltip-shadow ui-tooltip-modal ui-tooltip-iframe'
            }
        });
        
        return false;
    });
});

//mylingo core object
mylingo = {};

mylingo.bookmark = {
    add: function(options) {

        $.ajax({
            url: options.url,
            dataType: 'json',
            type: 'post',
            success: function(data) {
                if(data.status == 'success')
                {
                    if(options.callback)
                    options.callback(data);
                }
            }
        });

        return false;
    }
}

mylingo.openInviter = {
    load: function(){
        $('#invite_menu.tabs').tabs({
            selected: -1,
            select: function(event, ui)
            {
                //hide errors
                $('.ui-tooltip-red').qtip('destroy');
                
                //let's manually set the active state,
                //since we are emulating a tabs system here.
                $('#invite_menu .ui-tabs-nav li').removeClass('ui-tabs-selected ui-state-active');

                var selector = $(ui.tab).attr('href').replace('#','');

                switch(selector)
                {
                    case 'all':
                        $("#invite_friends_form tbody tr:first").show();
                        $('#openInviter_provider').val('');
                    break;
                    default:
                        $("#invite_friends_form tbody tr:first").hide();
                        $('#openInviter_provider').val(selector);
                    break;
                }

                $(ui.tab).parent().addClass('ui-tabs-selected ui-state-active');

                return false;
            }
        });

        //default selected tab
        $('#invite_menu.tabs').tabs('select', '#hotmail');
        
        mylingo.form.validate($('#invite_friends_form'));
    }
};

// user interface object
mylingo.ui = {};

// Users autocomplete
//http://loopj.com/jquery-tokeninput/
mylingo.ui = {
        //Checkboxes
    checkboxes: 
    {
        checkAll: function(id, flag)
        {
            $("form#" + id + " input[type='checkbox']").attr('checked', flag);
        }
    }
};

//Tooltips
mylingo.ui.tooltip = {
    show: function(obj, newoptions, event)
    {
        var defaults = {
            overwrite: false,
            style: {
                classes: 'ui-tooltip-shadow ui-tooltip',
                tip: true 
            },
            position: { 
                viewport: $(window),
                my: 'top center',
                at: 'bottom center'
            },
            show: {
                event: event.type,
                ready: true
            }
        };
        
        var options = $.extend(defaults, newoptions);
        
        obj.qtip(options, event);
    },
    clear: function()
    {
        //hide all previous tips
        $('.qtip.ui-tooltip').qtip('hide');
    }
}


//Modals
//http://craigsworks.com/projects/qtip2/demos/#modal
mylingo.ui.modal = {
   open: function(obj, newoptions) {
       
        var defaultoptions = {
            overwrite: true,
            position: {
                my: 'center',
                at: 'center',
                target: $(window)
            },
            show: {
                event: false,
                solo: true,
                ready: true,
                modal: true
            },
            hide: false,
            style: {
                classes: 'ui-tooltip-shadow ui-tooltip ui-tooltip-modal'
            }
        };
       
        var options = $.extend(defaultoptions, newoptions);
       
        $(obj).qtip(options);
   }
};

//Points
mylingo.points = {
    add: function(val) {
        $('.points.mine .value').fadeOut(function() {
            var prevVal = parseInt($(this).html());
            var newVal = prevVal + val;
            
            $(this).html(parseInt(newVal)).fadeIn();
        });
    },
    subtract: function(val) {
        $('.points.mine .value').fadeOut(function(){
            var prevVal = parseInt($(this).html());
            var newVal = prevVal - val;
            
            if(newVal<0)
            var newVal = 0;
            
            $(this).html(parseInt(newVal)).fadeIn();
        });
    }
};

//Form core object
mylingo.form = {};

//Form validation
//http://bassistance.de/jquery-plugins/jquery-plugin-validation/
//and qtip2
mylingo.form = {
    validate: function(form, newoptions)
    {        
        var defaults = 
        {
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorClass: 'invalid',
            validClass: 'valid',
            errorPlacement: function(error, element)
            {
                // Set positioning based on the elements position in the form
                var elem = $(element),
                corners = ['left center', 'right center'],
                flipIt = elem.parents('span.right').length > 0;

                // Check we have a valid error message
                if(!error.is(':empty')) {
                    // Apply the tooltip only if it isn't valid
                    elem.filter(':not(.valid)').qtip({
                        overwrite: true,
                        content: error,
                        position: 
                        {
                            my: corners[ flipIt ? 0 : 1 ],
                            at: corners[ flipIt ? 1 : 0 ],
                            viewport: elem,
                            container: elem.parent()
                        },
                        show: {
                            event: false,
                            ready: true
                        },
                        hide: false,
                        style: {
                            classes: 'ui-tooltip-shadow ui-tooltip-red',
                            tip: true 
                        }
                    })

                    // If we have a tooltip on this element already, just update its content
                    .qtip('option', 'content.text', error);
                }

                // If the error is empty, remove the qTip
                else {
                    elem.qtip('destroy');
                }
            },
            success: $.noop // Odd workaround for errorPlacement not firing!
        };

        var options = $.extend(defaults, newoptions);

        form.validate(options);
    }
};

page = new Array();

//Ajax scroll paginate
mylingo.paginate = {
    execute: function(options) 
    {
        //default settings
        var defaults = {
            page: 2,
            limit: 10,
            scrollPixels: 500,
            scrollTime: 800,
            identifier: 'paginator'
        };

        var options = $.extend(defaults, options);

        if(options.cookieName)
        {
            if(!$.cookie(options.cookieName))
            $.cookie(options.cookieName, options.page, { path: '/' })
        }

        //add the activate class and change the message
        options.link.parent().addClass('activate');
        
        var linkValue = options.link.text();
        
        options.link.text('Загрузка...');

        if(!page[options.identifier])
        page[options.identifier] = options.page;
        
        //begin the ajax attempt
        $.ajax({
            url: options.url,
            data: {
                page: page[options.identifier],
                limit: options.limit
            },
            dataType: 'json',
            type: 'get',
            cache: false,
            success: function(data) 
            {
                //reset the message
                options.link.text(linkValue);

                switch(data.status)
                {
                    case 'success':
                        $(options.lastElem).after(data.response);

                        //scroll down
                        $.scrollTo('+='+options.scrollPixels+'px', options.scrollTime, {axis:'y'} );

                        //increment the current status
                        page[options.identifier] += 1;
                    break;
                    case 'nomore':
                        options.link.parent().text('Nothing else to show.');
                    break;
                }

            },
            //complete event
            complete: function() {
                //remove the spinner
                options.link.parent().removeClass('activate');
            }
        });
    }
};

//strip_tags
jQuery.fn.stripTags = function() {return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );};
