///////////////////////////////////////////////////
// NOTE make sure this is included BEFORE any other
// soversa javascript libs
///////////////////////////////////////////////////

$(document).ready(function(){

    // Turn all the headings to Gotham
    Cufon.replace('h1, h2, h3, h4, h5, h6', {
        autoDetect: true,
        hover: { autoDetect: true }
    });

    // Hookup the placeholder attribute for Firefox & Internet Explorer
    $('input[placeholder]').each(function(index, input){
	    $(input).val($(input).attr('placeholder')).focusAndBlur($(input).attr('placeholder'));
    });
    
    // Activate the help text in the first name textbox
    $('input#firstName').focus(function(event){
        if ($(this).val() == 'First Name'){
            $(this).val('');
        }
    });

    $('input#firstName').blur(function(event){
        if ($(this).val() == ''){
            $(this).val('First Name');
        }
    });

    // Activate the help text in the last name textbox
    $('input#lastName').focus(function(event){
        if ($(this).val() == 'Last Name'){
            $(this).val('');
        }
    });

    $('input#lastName').blur(function(event){
        if ($(this).val() == ''){
            $(this).val('Last Name');
        }
    });

    // Runs when the user enters the full name field
    $("input#fullname").focus(function(event){
        if ($(this).val() == 'Full Name'){
            $(this).val('');
        }
    });

    // Runs when the user leaves the full name field
    $("input#fullname").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('Full Name');
        }
    });

    // Runs when the user enters the email field
    $("input#email").focus(function(event){
        if ($(this).val() == 'Email'){
            $(this).val('');
        }
    });

    // Runs when the user leaves the last name field
    $("input#email").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('Email');
        }
    });

    $("input#street").focus(function(event){
        if ($(this).val() == 'Street'){
            $(this).val('');
        }
    });

    $("input#street").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('Street');
        }
    });

    $("input#city").focus(function(event){
        if ($(this).val() == 'City'){
            $(this).val('');
        }
    });

    $("input#city").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('City');
        }
    });

    $("input#state").focus(function(event){
        if ($(this).val() == 'State/Province'){
            $(this).val('');
        }
    });

    $("input#state").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('State/Province');
        }
    });

    $("input#zip").focus(function(event){
        if ($(this).val() == 'Zip/Postal Code'){
            $(this).val('');
        }
    });

    $("input#zip").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('Zip/Postal Code');
        }
    });

    // TODO FIX THIS, for now this value must sync up with view
    $("input#userid").focus(function(event){
        if ($(this).val() == 'Email or Mobile phone number'){
            $(this).val('');
        }
    });

    // TODO FIX THIS, for now this value must sync up with view
    $("input#userid").blur(function(event){
        if ($(this).val() == ''){
            $(this).val('Email or Mobile phone number');
        }
    });



});

///////////////////////////////////////////////////
// NOTE THESE ARE GLOBAL FUNCTIONS - THESE MUST
// EXIST OUTSIDE OF THE JQUERY READY BLOCK
///////////////////////////////////////////////////

function is_empty_string(val) {
    return !(val.replace(/\s/g,"") == "")
}

// simple regex email validation
function is_valid_email(val) {
    re = '^([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$';
    return val.match(re);
}

/*
    original mobile regex found at regexlib.com, author, Igor Kravtsov, http://regexlib.com/REDetails.aspx?regexp_id=58
    modified and fixed by dj, added optional leading 1, and not allowing a 1 to start the NPAA area code
 */
function is_valid_sms(val) {
    re = '^\\+?([1]( |-|\\.)?)?(\\(?[2-9][0-9]{2}\\)?|[2-9][0-9]{2})( |-|\\.)?([0-9]{3}( |-|\\.)?[0-9]{4}|[0-9]{7})$';
    return eradicate_spaces(val).match(re);
}

function normalize_sms(val) {
    var only_nums = /[^0-9]/g;
    var no_leading_one = /^1/;

    return val.replace(only_nums, '').replace(no_leading_one, '');
}

function normalize_userid(val) {
    if (is_valid_sms(val)) {
        return normalize_sms(val);
    }

    return val;
}

function pretty_print_sms(val) {
    var v = normalize_sms(val);
    if (v.length == 10) {
        return v.substr(0, 3) + "-" + v.substr(3, 3) + "-" + v.substr(6, 4);
    } else { return "None"; }
}

function is_valid_userid(val) {
    return (is_valid_email(val) || is_valid_sms(val));
}

function is_valid_password(val) {
    // TODO check for strength here too? or leave up to devise?
    return val.length >= 6;
}

function trim_fullname(val) {
    var lot_o_space = /\s+/g;
    var leading_trailing_space = /^\s*|\s*$/g;
    return val.replace(lot_o_space, ' ').replace(leading_trailing_space, '');
}

function eradicate_spaces(val) {
    var lot_o_space = /\s+/g;
    return val.replace(lot_o_space, '');
}

function is_valid_name(val) {
    if (val == 'Full Name') return false;

    var newval = trim_fullname(val);
    if (newval.indexOf(" ") == -1) return false;

    // check for empty space
    return is_empty_string(newval);
}

function is_missing_fullname(val) {
    if (val.first_name == null | val.last_name == null) {
        return true;
    } else return false;
}

function get_full_name(val) {
    if (!is_missing_fullname(val)) {
        return val.first_name + " " + val.last_name;
    } else return "Full Name";
}

/*
 Parse a string that represents the fullname of a person and return an array
 for each element of the name.
 */
function parseName(fullName) {
    var first_and_last = [];
    var space_loc = fullName.indexOf(" ");

    if (space_loc != -1) {
        first_and_last[0] = fullName.substring(0, space_loc);
        first_and_last[1] = fullName.substring(space_loc+1);
    } else {
        // if there's only element, save it to the last name
        first_and_last[0] = "";
        first_and_last[1] = fullName;
    }
    return first_and_last;
}

// JQUERY HELPERS -----------------------------------------
jQuery.fn.focusAndBlur = function(phrase){
    $(this).focus(function(){
        if ($(this).val() == phrase) $(this).val('');
    });

    $(this).blur(function(){
        if ($(this).val() == '') $(this).val(phrase);
    });
};

jQuery.fn.flashNoticeInfo = function(phrase){
    $(this).removeClass('hide');
    $(this).html("<span class='icon'>Success!</span>" + phrase);
};

jQuery.fn.flashNoticeInfoWithFadeOut = function(phrase, fadeout){
    $(this).flashNoticeInfo(phrase);

    if (fadeout) {
        $(this).fadeOut(fadeout);
        setTimeout(function() { $(this).addClass('hide'); } , fadeout);
    }
};

// GOOGLE MAPS HELPER CLASS -----------------------------------------
GMaps = {

    addMarkerForAddress: function(address){
        var myLatlng;
        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({ 'address': address, 'partialmatch': true }, function(response){
            var closest = response[0].geometry.location;
            myLatlng = new google.maps.LatLng(closest.b, closest.c);

            var map = new google.maps.Map(document.getElementById('map'), {
                backgroundColor: '#99b3cc',
                zoom: 14,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: false
            });

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: "Our Nearest Location"
            });
        });
    }

};
