/*****************************************************
**  MANHUNT Registration Javascript Library
**  Author: Zachary Segal
**  Version: 1.0
**  copyright MANHUNT 2008
*****************************************************/

jQuery(document).ready(function(){
    // bind the bottom-nav buttons to modals
    jQuery('#privLink2').click(function(ev) {
        jQuery.ajax({
            url: jQuery('span#ppTxtU').text(),
            success: function(html){
              var allHtml = jQuery('#ppHeader').html() + html;
              modalOpenContent(allHtml, true, 'modalWindow ppolMod');
            }
        });
        return false;
    });
});

function checkUserName() {
    var username = jQuery('#username').val();
    
    url = url_for('register/ajaxUserAvailable');
    jQuery.get(url, {name:username}, function(data) {
        jQuery('#nameCheck').html(data);
    });
}

function checkEmail() {
    var url = url_for('register/ajaxEmailAvailable');
    var email = jQuery('#email').val();
    jQuery.get(url, {email:email}, function(data) {
        if (data != 'okay') {
            jQuery('#emailCheck').parent().parent().show();
            jQuery('#emailCheck').html(data);
        }
        else {
            jQuery('#emailCheck').parent().parent().hide();
            jQuery('#emailCheck').html('');
        }
    });
}



function closeTOS() {
    jQuery('input').attr('disabled',false);
    jQuery('textarea').attr('disabled',false);
    jQuery('#backgroundUploader').css('display','block');
    
    jQuery('#agreement').fadeOut();
}



/**
* put the uploaded image in the preview box for registration
*/
function showRegPicture(filepath) {
    
    jQuery('#userIcon').html('');
    jQuery('#userIcon').css('backgroundColor', '#081C3E');
    jQuery('#userIcon').css('backgroundImage', 'url('+filepath+')');
    jQuery('#userIcon').css('backgroundPosition', 'center center');
    jQuery('#userIcon').css('backgroundRepeat', 'no-repeat');
    
    slideImageUpload('uploadPic')
    
    var challenge = jQuery('#challenge').val();
    if (challenge == undefined) {
        jQuery('#signUpButton').focus();
    } else {
        jQuery('#challenge').focus();
    }
}





/**
* makes the black pop up window appear with a fade effect
*/
function togglePopUp(window_name) {
    var dis = jQuery('#username').attr('disabled');
    if (dis == true) {
        return false;
    }
       
    var window = document.getElementById(window_name);
//  alert(window.style.display);
    
    if(window.style.display == "block") {
        //hide window
        jQuery(window).fadeOut("slow");
    }
    else {
        //show window
        jQuery(window).fadeIn("slow", function() {
            jQuery(window).fadeTo("slow", 0.9);
        });
    }
    
}




/**
* slide up and down the image uploader panel for reg page 1 
*/
function slideImageUpload(window_name) {
    
    var uploadWin = document.getElementById(window_name);
    
    if (clickable == false) {
        return false;
    }
    clickable = false;
    
    if(uploadWin.style.height == "120px") {
        // hide window
        jQuery(uploadWin).animate({height:20},{
            step: function(now) {
                jQuery(this).css('top',(now * -1) + 20);
            },
            duration: 500,
            complete: function() {
                clickable = true;
            }
        });
    }
    else {
        // show window
        jQuery(uploadWin).animate({height:120},{
            step: function(now) {
                jQuery(this).css('top',(now * -1) + 20);
            },
            duration: 500,
            complete: function() {
                clickable = true;
            }
        });
        
        try {
            var frame = document.getElementById('backgroundUploader').contentWindow.document;
            frame.getElementById('imageSelector').focus();
        }
        catch (e) {
            // do nothing
        }
    }
}





/**
* places a profile suggestion text into the profile text field
*/
function placeSuggestion(obj) {
    
    var message = jQuery(obj).children().eq(1).html();
    var textBox = document.getElementById("body");
    
    var cleanedMessage = message.replace(/&nbsp;/g," ");

    jQuery(textBox).val(cleanedMessage);
    countCharacters(textBox);
    
    jQuery(obj).parent().fadeOut("slow");
}





/**
* set up the contextual help system on the first page of registration
*/
function setupMoveHelpArrow() {
    
        
    jQuery("#accountInfo").children().find(":input").focus( function() {
        
        //hide all the arrows
        jQuery(".arrow").css("display","none");
        jQuery("#helpHanger").css("display","none");
        
        //update the contextual help system
        switch(this.name) {
            case "username":    jQuery("#helpTitle").html(mhDictionary.registration.helpNameTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpNameBody);
                                jQuery(".arrow").eq(0).css("display","block");
                                break;
            case "password":
            case "password2":   jQuery("#helpTitle").html(mhDictionary.registration.helpPassTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpPassBody);
                                jQuery(".arrow").eq(1).css("display","block");
                                break;
            case "email":       jQuery("#helpTitle").html(mhDictionary.registration.helpEmailTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpEmailBody);
                                jQuery(".arrow").eq(2).css("display","block");
                                break;
            case "age":         
            case "age_check":   jQuery("#helpTitle").html(mhDictionary.registration.helpAgeTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpAgeBody);
                                jQuery(".arrow").eq(3).css("display","block");
                                break;
            case "zipFinder":
            case "location":    jQuery("#helpTitle").html(mhDictionary.registration.helpLocationTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpLocationBody);
                                jQuery(".arrow").eq(4).css("display","block");
                                break;
            case "headline":    jQuery("#helpTitle").html(mhDictionary.registration.helpHeadlineTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpHeadlineBody);
                                jQuery(".arrow").eq(5).css("display","block");
                                break;
            case "body":        jQuery("#helpTitle").html(mhDictionary.registration.helpBodyTitle);
                                jQuery("#helpText").html(mhDictionary.registration.helpBodyBody);
                                jQuery(".arrow").eq(6).css("display","block");
                                break;
                                
            case "userIcon":    var picBody = mhDictionary.registration.helpPicBody1;
                                picBody += "<br /><br />" + mhDictionary.registration.helpPicBody2;
                                jQuery("#helpTitle").html(mhDictionary.registration.helpPicTitle);
                                jQuery("#helpText").html(picBody);
                                //jQuery("#helpHanger").css("display","block");
                                jQuery(".arrow").eq(7).css("display","block");
                                break;
            
/*                                
            case "commit":      jQuery("#helpTitle").html("10. Create your new account");
                                jQuery("#helpText").html("Submit your new account settings to our database for verification of availability.");
                                break;
*/
            default:            alert('error'+this.name);
        }

        
    });
    
    //select the first input field, username
    document.getElementById("username").focus();
    
}




/**
 * validate the first registration page's form data and then fade in agreement window
 */
function validateRegPage1() {
    
    var username = jQuery('#username').val();
    
    var url = url_for("register/ajaxUserAvailable");
    jQuery.get(url, {name:username}, function(data) {
        jQuery('#nameCheck').html(data);
        validateData();
    });
}

function validateData() {
    
    //pattern expressions for checking values
    var emailFormat = /^([^@\s<>]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;  ///^.+@.+\..{2,4}$/;
    var alphaNumeric = /[a-zA-Z0-9_]/;
    var numeric = /^[0-9]*$/;
    
    
    //create errors array and cursor
    var errors = new Array();
    var e = 0;
    
    
    //load up form fields into variables
    var form = jQuery('form');
    var screenName = form.find("#username").val();
    var password = form.find("#password").val();
    var password2 = form.find("#password2").val();
    var email = form.find("#email").val();
    var age = form.find("#age").val();
    var age_check = form.find("#age_check").attr('checked');
    var location = form.find("#acSelectedCity").val();
    var challenge = form.find('#challenge').val();
    
    // load profile headline and trim right and left white space
    var headline = jQuery.trim(form.find("#headline").val());
    form.find('#headline').val(headline);
    
    // load profile body text and trim right and left white space and recount character count
    var body = jQuery.trim(form.find("#body").val());
    form.find('#body').val(body);    
    countCharacters(jQuery('#body').get(0));
    
    
    //reset the error highlighting for all the input fields
    jQuery("form input").removeClass("errorHighlight");
    
    
    
    //check that the screen name was validated as available
    if (jQuery("#nameCheck img").attr("src").match("accept") == null) {
        errors[e] = mhDictionary.registration.needName;
        e++;
        jQuery("#username").addClass("errorHighlight");
    }
    
    
    
    
    //check that their is a password entered
    if (password == "" || password == null) {
        errors[e] = mhDictionary.registration.needPass;
        e++;
        jQuery("#password").addClass("errorHighlight");
        jQuery("#password2").addClass("errorHighlight");

    }
    else {
    
        //check that password doesn't contain illegal characters
        if (false) {
            errors[e] = "your password contains non-alphanumeric characters.";
            e++;
            jQuery("#password").addClass("errorHighlight");
            jQuery("#password2").addClass("errorHighlight");
        }
        else {
            
            //check that passwords are within length parameters
            if (password.length < 6) {
                errors[e] = mhDictionary.registration.passShort;
                e++;
                jQuery("#password").addClass("errorHighlight");
                jQuery("#password2").addClass("errorHighlight");
            }
            else {
                
                //check that both passwords match
                if (password != password2) {
                    errors[e] = mhDictionary.registration.passNoMatch;
                    e++;
                    jQuery("#password").addClass("errorHighlight");
                    jQuery("#password2").addClass("errorHighlight");

                }
                else {}
                
            }
        }
        
    }
    
    
    
    //check that their is an email entered
    if (email == "" || email == null) {
        errors[e] = mhDictionary.registration.needEmail;
        e++;
        jQuery("#email").addClass("errorHighlight");
    }
    else {
        //check that the email is formatted correctly
        if (emailFormat.test(email) == false) {
            errors[e] = mhDictionary.registration.badEmail;
            e++;
            jQuery("#email").addClass("errorHighlight");
        }
        
    }
    
    
    
    
    //check that their is an age entered
    if (age == "" || age == null) {
        errors[e] = mhDictionary.registration.needAge;
        e++;
        jQuery("#age").addClass("errorHighlight");

    }
    else {
        
        //check the age doesn't contain illegal characters
        if (numeric.test(age) == false) {
            errors[e] = mhDictionary.registration.nonNumericAge;
            e++;
            jQuery("#age").addClass("errorHighlight");

        }
        else {
        
            //check that age is within parameters
            if (parseInt(age) < 18) {
                errors[e] = mhDictionary.registration.tooYoung;
                e++;
                jQuery("#age").addClass("errorHighlight");

            }
            
            if (parseInt(age) > 99) {
                errors[e] = mhDictionary.registration.tooOld;
                e++;
                jQuery("#age").addClass("errorHighlight");

            }
            
        }
        
    }
    
    
    
    //check that age certification box is checked
    if (age_check != true) {
        errors[e] = mhDictionary.registration.needCertifyAge;
        e++;
        jQuery("#age_check").addClass("errorHighlight");

    }
    
    
    
    
    //check that there is a valid location selected
    if (location == "undefined" || location == null || location == "") {
        errors[e] = mhDictionary.registration.needLocation;
        e++;
        jQuery("#location").addClass("errorHighlight");

    }
    
    
    //check that headline is not empty
    if (headline.length < 1) {
        errors[e] = mhDictionary.registration.needHeadline;
        e++;
        jQuery("#headline").addClass("errorHighlight");

    }
    
    
    
    
    //check that body text of the profile is not empty
    if (body.length < 1) {
        errors[e] = mhDictionary.registration.needBody;
        e++;
        jQuery("#body").addClass("errorHighlight");

    }
    
    //check that body isn't longer then max value (shouldn't happen)
    if (body.length > 650) {
        errors[e] = mhDictionary.registration.bodyTooLong;
        e++;
        jQuery("#body").addClass("errorHighlight");

    }
    
    
    
    
    //check that an initial image has been uploaded
    if (document.cookie.match('regimg') == null) {
        if(jQuery('#userIcon').css('backgroundImage').match('jpg') == null) {
            errors[e] = mhDictionary.registration.needPhoto;
            e++;
            jQuery("#userIcon").addClass("errorHighlight");

        }
    }
    
    
    
    //check that an initial image has been uploaded
    if (challenge != undefined) {
        if (challenge.length == 0) {
            errors[e] = mhDictionary.registration.needChallenge;
            e++;
            jQuery("#challenge").addClass("errorHighlight");
        }
    }
    
    
    
    if (errors.length > 0) {
        var errorMessages = "";
        
        errorMessages += "<span class='error smText MHcorners'>";
        for (i=0; i<errors.length; i++) {
            errorMessages += "<li>" + errors[i] + "</li>";
        }
        errorMessages += "</span>";
        
        jQuery("#errorMessages").html(errorMessages);
        
        /*
        if (jQuery.browser.msie == false) {
            jQuery("#errorMessages span").corner("5px");
        }
        */
        
        return false;
    }
    else {
        jQuery('textarea').attr('disabled',true);
        jQuery('input').attr('disabled',true);
        jQuery('#backgroundUploader').css('display','none');
        
        jQuery("#errorMessages").html("");
        jQuery("#agreement").fadeIn();

    }
    
    
    
}

//_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*

/**
 * validate the first registration page's form data and then fade in agreement window
 */
function validateQuickRegPage() {

    var username = jQuery('#username').val();

    var url = url_for("register/ajaxUserAvailable");
    jQuery.get(url, {name:username}, function(data) {
        jQuery('#nameCheck').html(data);
        validateQuickRegData();
    });
}

function validateQuickRegData() {

    //pattern expressions for checking values
    var emailFormat = /^([^@\s<>]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;  ///^.+@.+\..{2,4}$/;
    var alphaNumeric = /[a-zA-Z0-9_]/;
    var numeric = /^[0-9]*$/;


    //create errors array and cursor
    var errors = new Array();
    var e = 0;


    //load up form fields into variables
    var form = jQuery('form');
    var screenName = form.find("#username").val();
    var password = form.find("#password").val();
    var password2 = form.find("#password2").val();
    var email = form.find("#email").val();
    var age = form.find("#age").val();
    var age_check = form.find("#age_check").attr('checked');
    var location = form.find("#acSelectedCity").val();
    var challenge = form.find('#challenge').val();


    //reset the error highlighting for all the input fields
    jQuery("form input").removeClass("errorHighlight");


    //check that the screen name was validated as available
    if (jQuery("#nameCheck img").attr("src").match("accept") == null) {
        errors[e] = mhDictionary.registration.needName;
        e++;
        jQuery("#username").addClass("errorHighlight");
    }




    //check that their is a password entered
    if (password == "" || password == null) {
        errors[e] = mhDictionary.registration.needPass;
        e++;
        jQuery("#password").addClass("errorHighlight");
        jQuery("#password2").addClass("errorHighlight");

    }
    else {

        //check that password doesn't contain illegal characters
        if (false) {
            errors[e] = "your password contains non-alphanumeric characters.";
            e++;
            jQuery("#password").addClass("errorHighlight");
            jQuery("#password2").addClass("errorHighlight");
        }
        else {

            //check that passwords are within length parameters
            if (password.length < 6) {
                errors[e] = mhDictionary.registration.passShort;
                e++;
                jQuery("#password").addClass("errorHighlight");
                jQuery("#password2").addClass("errorHighlight");
            }
            else {

                //check that both passwords match
                if (password != password2) {
                    errors[e] = mhDictionary.registration.passNoMatch;
                    e++;
                    jQuery("#password").addClass("errorHighlight");
                    jQuery("#password2").addClass("errorHighlight");

                }
                else {}

            }
        }

    }



    //check that their is an email entered
    if (email == "" || email == null) {
        errors[e] = mhDictionary.registration.needEmail;
        e++;
        jQuery("#email").addClass("errorHighlight");
    }
    else {
        //check that the email is formatted correctly
        if (emailFormat.test(email) == false) {
            errors[e] = mhDictionary.registration.badEmail;
            e++;
            jQuery("#email").addClass("errorHighlight");
        }

    }




    //check that their is an age entered
    if (age == "" || age == null) {
        errors[e] = mhDictionary.registration.needAge;
        e++;
        jQuery("#age").addClass("errorHighlight");

    }
    else {

        //check the age doesn't contain illegal characters
        if (numeric.test(age) == false) {
            errors[e] = mhDictionary.registration.nonNumericAge;
            e++;
            jQuery("#age").addClass("errorHighlight");

        }
        else {

            //check that age is within parameters
            if (parseInt(age) < 18) {
                errors[e] = mhDictionary.registration.tooYoung;
                e++;
                jQuery("#age").addClass("errorHighlight");

            }

            if (parseInt(age) > 99) {
                errors[e] = mhDictionary.registration.tooOld;
                e++;
                jQuery("#age").addClass("errorHighlight");

            }

        }

    }



    //check that age certification box is checked
    if (age_check != true) {
        errors[e] = mhDictionary.registration.needCertifyAge;
        e++;
        jQuery("#age_check").addClass("errorHighlight");

    }




    //check that there is a valid location selected
    if (location == "undefined" || location == null || location == "") {
        errors[e] = mhDictionary.registration.needLocation;
        e++;
        jQuery("#location").addClass("errorHighlight");

    }


    if (errors.length > 0) {
        var errorMessages = "";

        errorMessages += "<span class='error smText MHcorners'>";
        for (i=0; i<errors.length; i++) {
            errorMessages += "<li>" + errors[i] + "</li>";
        }
        errorMessages += "</span>";

        jQuery("#errorMessages").html(errorMessages);

        /*
        if (jQuery.browser.msie == false) {
            jQuery("#errorMessages span").corner("5px");
        }
        */

        return false;
    }
    else {
        jQuery('textarea').attr('disabled',true);
        jQuery('input').attr('disabled',true);
        jQuery('#backgroundUploader').css('display','none');

        jQuery("#errorMessages").html("");
        jQuery("#agreement").fadeIn();

    }

}


