jQuery(document).ready(function(){      
    
    var j = jQuery;
    
    j.validator.addMethod("validacionDestinatario", function(value, element, param) {
        var result = false;
        var idFriendVal = j("#friend_ids").val();
        var eMailFriendVal = j("#friend_email").val();
        var eMailRegExp = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        if (idFriendVal != "") {
            result = true;
        } else {
            if ((eMailFriendVal != "") && (eMailRegExp.test(eMailFriendVal))) {
                result = true;
            }
        }
        
        return result;

    }, "validacionDestinatario");    
    
    // validate signup form on keyup and submit
    j("#new-dedication-form").validate({
        rules: {
            dedicate_to_input: {
                required: true,
                validacionDestinatario : true
            },
            dedication_text: {
                maxlength: '100'
            }
        },
        onkeyup: false,
        onclick: false,
        onfocusout: false,
        ignore: [],
        messages: {
            dedicate_to_input: "Please choose one member name or enter a valid email"
        }
    });
    
    /*var onAutocompleteSelect = function(value, data) {
        j('#selection').html('<img src="\/global\/flags\/small\/' + data + '.png" alt="" \/> ' + value);
        alert(data);
    }*/

    var options = {
        minLength: 1,
        serviceUrl: ajaxurl,
        width: 300,
        delimiter: /(,|;)\s*/,
        onSelect: ia_on_autocomplete_select,
        deferRequestBy: 0, //miliseconds
        params: {
            action: 'bp_dedication_autocomplete_ajax_handler'
        },
        noCache: true //set to true, to disable caching
    };    
    
    j("#dedicate_to_input").autocomplete(options);
    
    j("#dedicate_to_input").change(function(){
        if(j('#dedicate_to_input').val() == '') {
            j('#friend_ids').val('');    
            j('#friend_email').val('');
            j('#dedicate_to_country').val('');
            j('#country_select').addClass('hidden');
        }
        
        if(j('#dedicate_to_input').val().indexOf('@', 0) != -1 && j('#dedicate_to_input').val().indexOf('.', 0) != -1) { 
            j('#friend_email').val(j('#dedicate_to_input').val());   
            j('#friend_ids').val(',-1');
            j('#country_select').removeClass('hidden');
        } else {
            j('#friend_email').val('');
            j('#friend_ids').val('');
            j('#dedicate_to_country').val('');
            j('#country_select').addClass('hidden');            
        }
    });
    
    j('#video_url').change(function(){
        // Check for empty input field
        if(j('#video_url').val() != ''){
            processVideoURL(j('#video_url').val());
        }
    });
    
    j('#video_url').keyup(function() { // works immediately when user press button inside of the input
        if( j('#video_url').val() != j('#video_url').data('val') ){ // check if value changed
            j('#video_url').data('val',  j('#video_url').val() ); // save new value
            j(this).change(); // simulate "change" event
        }
    });
    
    if (j('#video_url').val()) {
        j('#video_url').trigger('change');
    }
    
    j("#user-list li a.remove").live("click", function() {
        var friend_id = j(this).prop('id');

        friend_id = friend_id.split('-');
        friend_id = friend_id[1];

        j.post( ajaxurl, {
            action: 'bp_dedication_add_user_ajax_handler',
            'friend_action': 'remove',
            'cookie': encodeURIComponent(document.cookie),
            //'_wpnonce': j("input#_wpnonce_invite_uninvite_user").val(),
            'friend_id': friend_id
        },
        function(response)
        {
            friendIDs = j('#friend_ids').val().split(',');
            friendIDs.splice(j.inArray(friend_id, friendIDs),1);            
            j('#friend_ids').val(friendIDs.toString());
            
            j('#user-list li#uid-' + friend_id).remove();
        });

        return false;
    });    
    
});

function processVideoURL(url){
    var id;
    var imgurl = '';
    var j = jQuery;

    if ((url.indexOf('youtube.com') > -1) || (url.indexOf('youtu.be') > -1)) {
        imgurl = j.jYoutube(url);
        j('#thumbs').html(j('<img src="'+imgurl+'" />'));

        getYouTubeInfo(j('#video_url').val(),
            function(artist, song){
                j('#artist_name').val(artist);
                j('#song_name').val(song);

            });
        
    } else if (url.indexOf('vimeo.com') > -1) {
        if (url.match(/http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/)) {
            id = url.split('/')[3];
        } else if (url.match(/^vimeo.com\/channels\/[\d\w]+#[0-9]+/)) {
            id = url.split('#')[1];
        } else if (url.match(/vimeo.com\/groups\/[\d\w]+\/videos\/[0-9]+/)) {
            id = url.split('/')[6];
        } else {
            j('#thumbs').html('');
        }

        j.ajax({            
            url: 'http://vimeo.com/api/v2/video/' + id + '.json',
            dataType: 'jsonp',
            success: function(data) {
                imgurl = data[0].thumbnail_medium;
                j('#thumbs').html(j('<img src="'+imgurl+'" />'));
                
                var otitle = data[0].title;
                var ntitle = otitle.match('^(.*) - (.*)$');
                var song = (ntitle && (ntitle[2].length > 0 )) ? ntitle[2] : "";
                var artist = (ntitle && (ntitle[1].length > 0 )) ? ntitle[1] : otitle;
                j('#artist_name').val(artist);
                j('#song_name').val(song);
                
            }
        });
    } else {
        j('#thumbs').html('');
    }
    return imgurl;
}


function ia_on_autocomplete_select( value, data ) {
    var j = jQuery;
    var friendIDs;
	
    // Check the right checkbox
    //j('#invite-anyone-member-list input#f-' + data).prop('checked',true);
	
    //j('#dedicate_to_input').addClass('loading');

    j.post( ajaxurl, {
        action: 'bp_dedication_add_user_ajax_handler',
        'friend_action': 'add',
        'cookie': encodeURIComponent(document.cookie),
        //'_wpnonce': j("input#_wpnonce_invite_uninvite_user").val(),
        'friend_id': data
    },
    function(response)
    {        
        friendIDs = j('#friend_ids').val().split(',');
        friendIDs.push(data);
        j('#friend_ids').val(friendIDs.toString());

        /*j('#user-list').html('');
        j('#user-list').append(response);*/
        //j('#dedicate_to_input').removeClass('loading');
    });
		
    // Remove the value from the send-to-input box
    // j('#dedicate_to_input').val('');
}
    