$(document).ready(function(){
    
    $("#nav a[href='" + location.href.replace(/popular(\/.+)?/, "") + "']").addClass('nav_selected');
    $("#nav a[href='" + location.href.replace(site.url+"/", "") + "']").addClass('nav_selected');
    $("#nav a[href='" + location.href + "']").addClass('nav_selected');
    
    $("#usersNav a[href='" + location.href.replace(/users(\/.+)?/, "") + "']").addClass('selectedAlph');
    $("#usersNav a[href='" + location.href.replace(site.url+"/", "") + "']").addClass('selectedAlph');
    $("#usersNav a[href='" + location.href + "']").addClass('selectedAlph');
    
    $("a.anchor").click(function (){
        $('input[name="'+$(this).attr('target')+'"]').focus();
        return false;
    })
    
    //validation - Submit Haiku - Form Elements
    if($('#submit_haiku')){
        $('#submit_haiku').validate({
            rules : {
                haikuLine1 : "required",
                haikuLine2 : "required",
                haikuLine3 : "required",
                authorID : {
                    required : true,
                    min : 1
                },
                haikuTag1 : {
                    required : true
                }
                
            },
            messages : {
                haikuLine1 : {
                    required : "*"
                },
                haikuLine2 : {
                    required : "*"
                },
                haikuLine3 : {
                    required : "*"
                },
                authorID : {
                    required : "*",
                    min : "Select an Author"
                },
                haikuTag1 : {
                    required : "Up to three tags. No space or Special Characters!"
                },
                'agreement[]' : {
                    required : "*"
                }
            },
            // the errorPlacement has to take the table layout into account
            errorPlacement: function(error, element) {
                if ( element.is(":checkbox") )
                    error.appendTo ( element.parent().next() );
                else
                    error.appendTo( element.parent().next() );
            }
        });
        
        $("#authorID").change(function () {
            $("#authorID option:selected").each(function () {
                var str = $(this).text();
                if(str == "Me"){
                    $('#agreement_container').css("display", "block");
                    $('#agreement').attr("class", "required");
                    //$('#author_status').html("");
                }else{
                    $('#agreement_container').fadeOut("slow");
                    $('#agreement').removeAttr("class");
                }
            });
        })
        .trigger('change');
    }
    
    //validation - Signup - Form Elements
    if($('#signup_forms')){
        $('#signup_form').validate({
            rules : {
                userUserName : {
                    required : true,
                    minlength : 4,
                    maxlength : 16
                },
                userEmail : {
                    required : true,
                    email : true
                },
                profilePicture : {
                    accept: "jpg|gif|png"
                },
                userBio : {
                    maxlength : 200
                },
                userPassword : {
                    required : true,
                    minlength : 4
                },
                userPasswordRetype : {
                    required : true,
                    minlength : 4,
                    equalTo : "#userPassword"
                },
                "userBirthday[Month]" : {
                    required : true,
                },
                "userBirthday[Day]" : {
                    required : true,
                },
                "userBirthday[Year]" : {
                    required : true,
                },
                captcha_code : {
                    required : true,
                    minlength : 4
                },
                userLocation : {
                    required : true
                }
            },
            messages : {
                userUserName : {
                    required : "*",
                    minlength : "4 to 16 Characters",
                    maxlength : "Maximum 16 Characters"
                },
                userEmail : {
                    required : "*",
                    email : "Invalid format"
                },
                profilePicture : {
                    accept: "jpg, gif or png"
                },
                userPassword : {
                    required : "*",
                    minlength : "Atleast 4 characters"
                },
                userPasswordRetype : {
                    required : "*",
                    minlength : "Atleast 4 characters",
                    equalTo : "Retype correctly!"
                },
                "userBirthday[Month]" : {
                    required : ""
                },
                "userBirthday[Day]" : {
                    required : ""
                },
                "userBirthday[Year]" : {
                    required : ""
                },
                captcha_code : {
                    required : "",
                    minlength : "",
                },
                userLocation : {
                    required : "*"
                }
            },
            errorPlacement: function(error, element) {
                if ( element.is(":checkbox") )
                    error.appendTo ( element.parent().next() );
                else
                    error.appendTo( element.parent() );
            }
        });
        
    }
    
    //validation - Account - Form Elements
    if($('#account_form')){
        $('#account_form').validate({
            rules : {
                userUserName : {
                    required : true,
                    minlength : 4,
                    maxlength : 16
                },
                userEmail : {
                    required : true,
                    email : true
                },
                profilePicture : {
                    accept: "jpg|gif|png"
                },
                userBio : {
                    maxlength : 200
                },
                userPassword : {
                    minlength : 4
                },
                userPasswordRetype : {
                    minlength : 4,
                },
                "userBirthday[Month]" : {
                    required : true,
                },
                "userBirthday[Day]" : {
                    required : true,
                },
                "userBirthday[Year]" : {
                    required : true,
                },
                userLocation : {
                    required : true
                }
            },
            messages : {
                userUserName : {
                    required : "*",
                    minlength : "4 to 16 Characters",
                    maxlength : "Maximum 16 Characters"
                },
                userEmail : {
                    required : "*",
                    email : "Invalid format"
                },
                profilePicture : {
                    accept: "jpg, gif or png"
                },
                userPassword : {
                    required : "*",
                    minlength : "Atleast 4 characters"
                },
                userPasswordRetype : {
                    required : "*",
                    minlength : "Atleast 4 characters",
                    equalTo : "Retype correctly!"
                },
                "userBirthday[Month]" : {
                    required : ""
                },
                "userBirthday[Day]" : {
                    required : ""
                },
                "userBirthday[Year]" : {
                    required : ""
                },
                captcha_code : {
                    required : "",
                    minlength : "",
                },
                userLocation : {
                    required : "*"
                }
            },
            errorPlacement: function(error, element) {
                if ( element.is(":checkbox") )
                    error.appendTo ( element.parent().next() );
                else
                    error.appendTo( element.parent() );
            }
        });
        
    }
    //validation - Comment - Form Elements
    if($('form[id="haiku_comment"]')){
        $('form[id="haiku_comment"]').validate({
            rules : {
                commentDescription : {
                    required : true,
                    minlength : 2,
                    maxlength : 512
                }
            },
            messages : {
                commentDescription : {
                    required : "*",
                    minlength : "Atleast 2 characters",
                    maxlength : "Up to 512 characters"
                }
            },
            // the errorPlacement has to take the table layout into account
            errorPlacement: function(error, element) {
                if ( element.is(":checkbox") )
                    error.appendTo ( element.parent().next() );
                else
                    error.appendTo( element.parent() );
            }
        });
    }
    //validation - RecoverPassword - Form Elements
    if($('form[id="recoverpass"]')){
        $('form[id="recoverpass"]').validate({
            rules : {
                userEmail : {
                    required : true,
                    email : true
                },
                "userBirthday[Month]" : {
                    required : true,
                },
                "userBirthday[Day]" : {
                    required : true,
                },
                "userBirthday[Year]" : {
                    required : true,
                }
            },
            messages : {
                userEmail : {
                    required : "*",
                    email : "Invalid Email format!"
                },
                "userBirthday[Month]" : {
                    required : ""
                },
                "userBirthday[Day]" : {
                    required : ""
                },
                "userBirthday[Year]" : {
                    required : ""
                }
            },
            // the errorPlacement has to take the table layout into account
            errorPlacement: function(error, element) {
                if ( element.is(":checkbox") )
                    error.appendTo ( element.parent().next() );
                else
                    error.appendTo( element.parent() );
            }
        });
    }
    //validation - Contact - Form Elements
    if($('form[id="contact_form"]')){
        $('form[id="contact_form"]').validate({
            rules : {
                messageSubject : {
                    required : true,
                    minlength : 2,
                    maxlength : 127
                },
                messageText : {
                    required : true,
                    minlength : 2,
                    maxlength : 511
                },
                messageSenderName : {
                    required : true,
                    minlength : 2,
                    maxlength : 127
                },
                messageSenderEmail : {
                    required : true,
                    email : true
                }
            },
            messages : {
                messageSubject : {
                    required : "*",
                    minlength : "*",
                    maxlength : "Maximum 127 character"
                },
                messageText : {
                    required : "*",
                    minlength : "*",
                    maxlength : "Maximum 511 character"
                },
                messageSenderName : {
                    required : "*",
                    minlength : "*",
                    maxlength : "Maximum 127 character"
                },
                messageSenderEmail : {
                    required : "*",
                    email : "Invalid format!"
                }
            },
            // the errorPlacement has to take the table layout into account
            errorPlacement: function(error, element) {
                if ( element.is(":checkbox") )
                    error.appendTo ( element.parent().next() );
                else
                    error.appendTo( element.parent() );
            }
        });
    }
    //Validation and others - Search
    function clearText(obj){
        
        var text = $(obj).val();
        if(text == "Search Haiku..."){
            $(obj).val("");
            $(obj).removeClass('silver');
        }
        else if(text == ""){
            $(obj).val("Search Haiku...");
            $('#s_error').css("display", "none");
            $(obj).addClass('silver');
        }
        else{
            $(obj).removeClass('silver');
        }
    }
    function checkText(obj) {
        $(obj).keyup(function() {
            if($(obj).val() !== "Search Haiku..."){
                $(obj).removeClass("silver");
                var length = $(obj).val().length;
                if(length <= 4){
                    $('#s_error').css("display", "block");
                }
                else if(length >= 5){
                    $('#s_error').css("display", "none");
                }
            }
        })
    }
    $('#tr_search input[name="keywords"]').bind("click blur", function() {
        clearText(this);
        checkText(this);
    })
    $('#tr_search input[name="action"]').click(function() {
        var button = $('#tr_search input[name="keywords"]')
        var texts = button.val();
        if(texts == "Search Haiku..."){
            button.focus();
            clearText(button);
            checkText(button);
            return false;
        }
        //debugger;
    })
    
    
    //update save value
    $('div[class="score"]').livequery('update_score', function(){
        var score = $(this);
        var hID = $(this).attr('haikuid');
        $.get(site.url+"/_rpc.html", {type : 'json', c : 'Haiku', k : hID, a : 'countPreference'}, function(data){
            $(score).html(data.result);
        }, 'json');
    });
    //Save Haiku
    $('a[class="savehaiku"]').click(function() {
        var savel = $(this);
        var haikuid = $(this).parent().attr('haikuid');
        $.get($(this).attr('href'), function(data) {
            var result = $(data);
            var info = $('div.message', result).text();
            var suc = new RegExp("success");
            var rem = new RegExp("removed");
            if(suc.exec(info)){
                $(savel).parent().prev().trigger('update_score');
                savel.parent().html("Saved");
                //debugger;
            }
            else if(rem.exec(info)){
                savel.parent().parent().parent().parent().parent().next().fadeOut("slow");
                savel.parent().parent().parent().parent().parent().fadeOut("slow");
            }
            else{
                /*$('div.info a#log_in').livequery('click', function() {
                    $.get(this.href, null, function(data) {
                        var result = $('#body_left', data).html();
                        $(info).dialog('close');
                        var login = $(result).dialog();
                    });
                    return false;
                });
                var info = */
                $('div.message', result).dialog({
                    title : $('div.message h4', result).remove().text(),
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog('close');
                        }
                    }
                });
                
                
            }
            //debugger;
        });
        return false;
    })
    
    //remove user support
    $('a[class="removeuser"]').click(function() {
        var remusr = $(this);
        var userid = $(this).attr('userid');
        $.get($(this).attr('href'), function(data) {
            var result = $(data);
            var info = $('div.message', result).text();
            var rem = new RegExp("Removed");
            if(rem.exec(info)){
                //$('table[userid="'+userid+'"]').fadeOut("slow");
                //remusr.parent().parent().parent().parent().parent().next().fadeOut("slow");
                //remusr.parent().parent().parent().parent().parent().fadeOut("slow");
                $.get(location.href, null, function(data) {
                    $('#body_left').replaceWith($('#body_left', data));
                    $('#body_right_nav').replaceWith($('#body_right_nav', data));
                });
            }
            else{
                $('div.message', result).dialog({
                    title : $('div.message h4', result).remove().text(),
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog('close');
                        }
                    }
                });
            }
            //debugger;
        });
        return false;
    })
    
    
    //support link update
    $('a[class="supportuser"]').livequery("supportuser", function() {
        var support = $(this);
        $.get($(this).attr('href'), function(data) {
            var result = $(data);
            var info = $('div.message', result).text();
            var sup = new RegExp("supported");
            var rem = new RegExp("Removed");
            if(sup.exec(info)){
                $.get(location.href, null, function(data) {
                    $('#body_left').replaceWith($('#body_left', data));
                    $('#body_right_nav').replaceWith($('#body_right_nav', data));
                });
            }
            else if(rem.exec(info)){
                $.get(location.href, null, function(data) {
                    $('#body_left').replaceWith($('#body_left', data));
                    $('#body_right_nav').replaceWith($('#body_right_nav', data));
                });
            }
            else{
                $('div.message', result).dialog({
                    title : $('div.message h4', result).remove().text(),
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog('close');
                        }
                    }
                });
            }
        });
    })
    $('a[class="supportuser"]').livequery("click", function() {
        //alert();
        $(this).trigger('supportuser');
        return false;
    });
    
});