/**
* EI
*/

var EI = {};

EI.Behaviours = {
    first : function() {},
    last : function() {},
    pages : {
        'music' : {
            'group' : function() {
                if($('#edit_mode').attr('checked') == true){
                    editableTextArea('.edit_bio');
                    editableImage('.edit_photo');
                    removeableItem('.remove_item');
                }
                $('#edit_mode').change(function(){
                    if($(this).attr('checked') == false){
                        uneditable('.edit_bio');
                        uneditable('.edit_photo');
                        unremoveableItem('.delete_link');
                        
                    }else{
                        editableImage('.edit_photo');
                        editableTextArea('.edit_bio');
                        removeableItem('.remove_item');
                        
                    }
                });
                
                $('.timestamp').prettyDate();
                
                $('#addSong').click(function(){
                    var next = $('.song_list').children().length + 1;
                    var songInput = '<li id="song-'+next+'" class="song" style="display:none">'
                                        +'<label for="title-'+next+'">Title</label>: '
                                        +'<input type="text" id="title-'+next+'" />'
                                        +'<input id="submit-'+next+'" type="submit" value="Add" />'
                                        +'<input id="cancel-'+next+'" type="button" value="Cancel" />'
                                    +'</li>';
                    $(this).text('Another?');
                    var path = updatePath('.song_list');
                    $('.song_list').append(songInput);
                    $('#song-'+next).slideDown('fast');
                    $('#title-'+next).bind('keypress', function(e){
                        if (e.which == 13 ){
                            var songData = $.trim($('#title-'+next).val());
                            if( songData != ''){
                                $.post(path, { value: songData },
                                  function(data){
                                    $('#song-'+next).html(data);
                                  }, "html");    
                            }else{
                                $('#song-'+next).effect("shake", { times: 1, distance: 10 }, 50,function(){$('#title-'+next).focus();});//.animate({opacity:1},100).children('#title-'+next).focus();
                            }
                        } 
                        if(e.keyCode == 27){
                              $('#song-'+next).slideUp('fast');	  
                        }

                    });
                    $('#submit-'+next).bind('click', function(){
                        var songData = $.trim($('#title-'+next).val());
                        if( songData != ''){
                            $.post(path, { value: songData },
                              function(data){
                                $('#song-'+next).html(data);
                              }, "html");    
                        }else{
                            $('#song-'+next).effect("shake", { times: 1, distance: 10 }, 50,function(){$('#title-'+next).focus();});
                        }

                    });
                    $('#cancel-'+next).bind('click', function(){
                        $('#song-'+next).slideUp('fast');
                    });

                    return false;
                });                    

                $('#addMember').click(function(){
                    var next = $('.member_list').children().length + 1;
                    var memberInput = '<li id="member-'+next+'" class="member grid_8 alpha omega" style="display:none">'
                                        +'<label for="member_name-'+next+'">Member Name</label>: '
                                        +'<input type="text" id="member_name-'+next+'" />'
                                        +'<input id="submit-'+next+'" type="submit" value="Add" />'
                                        +'<input id="cancel-'+next+'" type="button" value="Cancel" />'
                                    +'</li>';
                    $(this).text('Another?');
                    var path = updatePath('.member_list');
                    $('.member_list').append(memberInput);
                    $('#member-'+next).slideDown('fast');
                    $('#member_name-'+next).autocomplete('/users/fetch/',{
                        minChars:3,
                        autoFill: true
                    });
                    
                    $('#member_name-'+next).bind('keypress', function(e){
                        if (e.which == 13 ){
                            var memberData = $.trim($('#member_name-'+next).val());
                            if( memberData != ''){
                                $('.ac_results').fadeOut('fast');
                                $.post(path, { value: memberData },
                                  function(data){
                                    $('#member-'+next).replaceWith(data);
                                  }, "html");    
                            }else{
                                $('#member-'+next).effect("shake", { times: 1, distance: 10 }, 50,function(){$('#member_name-'+next).focus();});
                            }
                        } 
                        if(e.keyCode == 27){
                              $('#song-'+next).slideUp('fast');	  
                        }

                    });
                    $('#submit-'+next).bind('click', function(){
                        var memberData = $.trim($('#member_name-'+next).val());
                        
                        if( memberData != ''){
                            $.post(path, { value: memberData },
                              function(data){
                                 $('#member-'+next).replaceWith(data);
                              }, "html");    
                        }else{
                            $('#member-'+next).effect("shake", { times: 1, distance: 10 }, 50,function(){$('#member_name-'+next).focus();});
                        }

                    });
                    $('#cancel-'+next).bind('click', function(){
                        $('#member-'+next).slideUp('fast');
                    });

                    return false;
                });
                
                $('#comment').each(function(){
                    textareaLimited($(this));
                });
                                
                $('#comment_form').submit(function() {
                    var comment = $.trim($('#comment').val());
                    var time = new Date();
                    if(comment != ''){
                        $('#comment_form :submit').attr('disabled','disabled');
                        $.post( $(this).attr('action'),
                            {'comment': comment},
                            function(data){
                                $('#add_comment').slideUp('fast');
                                $('#comment_list').prepend(data);
                                $('#'+id).slideDown('fast');
                                $('#'+id+' .timestamp').prettyDate();
                            },
                            'html');
                    }else{
                        $(this).effect("shake", { times: 1, distance: 10 }, 50,function(){$('#comment').focus();});
                    }
                    return false;
                });

            },

            'song' : function() { EI.Behaviours.run('music','group'); }
        },
        'dashboard' : {
        },
        'group' : {
            'edit' : function(){
                var urlCounter = $('.url').length-1;
            	$('#insertUrl').click(function(){
            		var nextId = urlCounter+1;
            		$('#urlFields-'+urlCounter).clone().attr('id','urlFields-'+nextId).insertAfter('#urlFields-'+urlCounter).children('#insertUrl').remove();
                    $('#urlFields-'+nextId+' label').each(function(){
                       $(this).attr('for', $(this).attr('for').replace(urlCounter,nextId));
                    });
                    $('#urlFields-'+nextId+' input').each(function(){
                       $(this).attr('id', $(this).attr('id').replace(urlCounter,nextId));
                       $(this).attr('name', $(this).attr('name').replace(urlCounter,nextId));
                    });
                    

            		$('#url_'+nextId+'_url').val('');
            		$('#url_'+nextId+'_title').val('');

            		if(urlCounter == 0){
            			$('#url_'+nextId+'_url').after("<a href='#' id='removeurl-"+ nextId+"' class='remove field_control'>Remove this</a>");
            		}else{
            		    $('#urlFields-'+nextId+' a.remove').attr('id','removeurl-'+nextId);
            		}
            		
            		$('#removeurl-'+nextId).click(function(){
                        $(this).parent().fadeOut('fast');
                        $(this).parent().remove();
                        urlCounter--;
                        if(urlCounter == 0){
                            $('#removeurl-'+urlCounter).remove();
                        }
                    	return false;
            		});
            		urlCounter++;
            		return false;
            	});

            	$('.remove').click(function(){
            	    $(this).parent().fadeOut('fast');
            	    $(this).parent().remove();
                    urlCounter--;
                    if(urlCounter == 0){
                        $('#removeurl-'+urlCounter).remove();
                    }
                	return false;
        		});
                $('textarea').autogrow();
            },
            'add'    : function(){ EI.Behaviours.run('group','edit'); },
            'update' : function(){ EI.Behaviours.run('group','edit'); },
            'create' : function(){ EI.Behaviours.run('group','edit'); }
            
        }
    },
    run : function(cntl, actn){
      EI.Behaviours.pages[cntl][actn].apply();
    }
}

$(document).ready( function(){
    var cntl = $('#cntl').attr('class');
    var actn = $('#actn').attr('class').split(" ")[0];

    EI.Behaviours.first.call(this, cntl, actn);
    if(EI.Behaviours.pages[cntl] && EI.Behaviours.pages[cntl][actn])
        EI.Behaviours.pages[cntl][actn].apply();

    EI.Behaviours.last.call(this, cntl, actn);
});

function updatePath(e){
    if($(e).attr('id') != undefined){
        var params = $(e).attr('id').split(':');
        switch(params.length){
            case 2:
                var path = '/'+params[0]+'/update/'+params[1];
                break;
            case 3:
                var path = '/'+params[0]+'/song/'+params[1]+'/update/'+params[2];

        }
        
    }
    return path;    
}

function srcPath(e){
    if($(e).attr('id') != undefined){
        var params = $(e).attr('id').split(':');
        switch(params.length){
            case 2:
                var path = '/'+params[0]+'/'+params[1]+'/'+'txt';
                break;
            case 3:
                var path = '/'+params[0]+'/song/'+params[1]+'/'+params[2]+'/'+'txt';

        }
        
    }
    return path;    
}

function editableTextArea(e){
    if($(e).length>0){
        var pathToSrc = srcPath(e);
        $(e).editable(
            updatePath(e), { 
                loadurl   : pathToSrc,
                type      : 'autogrow',
                cancel    : 'Cancel',
                submit    : 'Save',
                indicator : '<img src="/images/spinner.gif">',
                tooltip   : 'Click to edit...',
                onblur    : 'ignore',
                autogrow : {
                    lineHeight : 12,
                    minHeight : 24
                },
                callback : function(value, settings) {
                    settings.data = p2nl(this);
                }
            }
        );
        indicateEditable(e);
    }
    
}

function editableImage(e){
    if($(e).length>0){
    
        $(e).editable(
            updatePath(e), {
                indicator : '<img src="/images/spinner.gif">',
                type : 'ajaxupload',
                submit : 'Upload',
                cancel : 'Cancel',
                tooltip : "Click to upload..."
        });
        indicateEditable(e);
    }
}
function indicateEditable(e){
    $(e).effect("highlight", {}, 1000);

    $(e).bind('mouseenter',function(){
        
        $(e).animate({
              "backgroundColor": "#ff8"
            }, "fast");
        // $(e).css({'background':'#ff8'});
    }).bind('mouseleave',function(){
        $(e).animate({
              "backgroundColor": "#fff"
            }, "fast");
    });
}

function uneditable(e){
    $(e).unbind('click');
    $(e).unbind('mouseenter');
    $(e).unbind('mouseleave');
};

function removeableItem(e){
    $(e).effect("highlight", {}, 1000);
    
    if($(e).attr('id') != undefined){
        var params = $(e).parent().attr('id').split(':');
        var attr = params[1];
        
    }
    var deleteLink = "<a href='#' class='delete_link'>(remove)</a>";
    $(e).append(deleteLink);
    var path = updatePath($(e).parent());

    $('.delete_link').click(function(){
        var parent = $(this).parent();
        $.post(
            path, 
            { 
                'remove': $(parent).attr('id'),
                'value' : attr
            },
            function(data){
              if(data == true){
                  $(parent).fadeOut('fast');
                  $(parent).remove();
              }
            }, 
            "json"
        );
          
        return false;
    })
}

function unremoveableItem(e){
     $(e).remove();
}
function postSong(e){
    
}
function p2nl(e){
    text = $(e).html().replace(/<p>/g,'').replace(/<\/p>/g,'\n').replace(/<br \/>/g,'').replace(/<br>/g,'').replace(/^\s+|\s+$/g,"");
    return text;
}
function textareaLimited(e){
    var classes = $(e).attr('class').split(' ');
    classesTotal = classes.length;
    for (var i=0; i < classesTotal; i++) {
        if( classes[i].indexOf('maxlength') > -1 ){
            var max = classes[i].split(':')[1];
            var cur = 0;
            var charsLeft = max-cur;

            $(e).keyup(function(i) {
                cur = $(e).val().length;
                charsLeft = max-cur;
                $('#chars_left span').text(charsLeft);
                if(charsLeft < 0){
                    $('#chars_left span').css({
                        'color':'#f00',
                        'font-weight':'bold'
                    });
                }else{
                    $('#chars_left span').css({
                        'color':"#666",
                        'font-weight':'normal'
                    });
                }
            });
            $('#chars_left span').text(charsLeft);
            
            
        }
    };
    return charsLeft;
}


// 
// function createWMD(e) {
// 
//     /***** Make sure WMD has finished loading *****/
//     if (!Attacklab || !Attacklab.wmd) {
//         alert("WMD hasn't finished loading!");
//         return;
//     }
// 
//     // build the dom elements
//     // var form = document.getElementById("myForm");
//     var textarea = $( $(e)[0]['id'] ).children('textarea');
//     // textarea.style.width = "500px";
//     // textarea.value = "Hi.";
//     // form.appendChild(textarea);
//  wmd_options = {
//      // format sent to the server.  Use "Markdown" to return the markdown source.
//      output: "Markdown",
//      // toolbar buttons.  Undo and redo get appended automatically.
//      buttons: "bold italic | link blockquote code image | ol ul heading hr",
//  };
//     /***** build the editor and tell it to refresh the preview after commands *****/
//     var editor = new Attacklab.wmd.editor(textarea);
// 
//     // save everything so we can destroy it all later
//     instances.push({ta:textarea, ed:editor});
// }
// 
// function destoryWMD () {
//     var inst = instances.pop();
// 
//     if (inst) {
// 
//         /***** destroy the editor and preview manager *****/
//         inst.pm.destroy();
//         inst.ed.destroy();
//     
//         // remove the dom elements
//         inst.ta.parentNode.removeChild(inst.ta);
//         inst.div.parentNode.removeChild(inst.div);
// 
//     }
// }

