// global DoctorBase "namespace"
var DB = {
    uniformElementSelectors: "select, :input, textarea"
};

// code to get run on every page load
$(function () {
    DB.displayGlobalNotifs();
    $('span.rating').stars();
    DB.skinForms(
        $(DB.uniformElementSelectors).not('.star')
    );
});

// analogous to catalyst profile_action_uri
DB.profile_action_uri = function (path) {
    var base = DBGlobals.profile_base_url;
    if (! base) {
        return null;
    }

    return base + path;
};

// analogous to catalyst uri for
DB.uri_for = function (path) {
    var base = mw_base_url;
    if (! base) {
        return null;
    }

    return base + path;
};

// global DB event dispatch
// when we move to jquery 1.7, should use on()
DB.bind = function (type, handler) {
    $(document).bind(type, handler);
};
DB.trigger = function (type, extra) {
    $(document).triggerHandler(type, extra);
};

DB.getFBLoginStatus = function (cb) {
    var fb_disabled = DB.config.fb_reviews_disabled;
    if (! DB.fbLoginResponse && ! fb_disabled) {
        FB.getLoginStatus(function(response) {
            DB.fbLoginResponse = response;
            cb(DB.fbLoginResponse);
        });
    } else if (! fb_disabled && DB.fbLoginResponse) {
        cb(DB.fbLoginResponse);
    } else {
        cb({});
    }
};

// create recaptcha
DB.createRecaptcha = function (containerElement) {
  try {
    Recaptcha.create("6LchGAwAAAAAAIZsn8-Dt77dIwDtj0drcrkpbz30",
        containerElement, {
        theme: "white"
    });
  } catch (e) {}
};

// refresh the page's recaptcha object. needed if validation fails
DB.reloadRecaptcha = function () {
  try {
    Recaptcha.reload();
  } catch (e) {}
};

// display in-page notifications
DB.displayNotifications = function (notifs) {
    if (! notifs || ! notifs.length) return;

    // create notif div
    var notifDiv = $(document.createElement("div"));
    notifDiv.addClass("notifications");

    // add individual notifications
    for (var i = 0; i < notifs.length; i++) {
        var notif = $(document.createElement("div"));
        notif.addClass("notification");
        notif.text(notifs[i]);
        notifDiv.append(notif);
    }
    
    // add 'click to close' text
    var close_element = $(document.createElement('div'));
    close_element.attr('id', 'close_notifs_text');

    var close_text = $(document.createElement('p'));
    close_text.text('(click to make me disappear)');

    close_element.append(close_text);
    notifDiv.append(close_element);

    $(document.body).append(notifDiv);
    
    // show notification
    notifDiv.slideDown('400');
    
    // click to hide
    notifDiv.click(function(evt) {
        $(".notifications").fadeOut('1000');
        return false;
    });
};

// display outstanding notifications on page load
DB.displayGlobalNotifs = function () {
    if (DBGlobals.notifications) {
        DB.displayNotifications(DBGlobals.notifications);
    }
};

// apply skin to form elements.
// optional: pass in elements to skin
DB.skinForms = function (e) {
    $(".deferred").css("visibility", "visible");
//    $(e).uniform();
}

// update uniform skin (if possible)
DB.redraw = function (e) {
    if (! $.uniform || ! $.uniform.update)
        return;

    $.uniform.update(e);
};

// star rating display support
$.fn.stars = function() {
    $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range
        val = val > 5 ? 5 : (val < 0 ? 0 : val);
        // Calculate physical size
        var size = 16 * val;
        // Create stars holder
        var stars = $('<span class="stars"><span></span></span>');
        // Adjust yellow stars' width
        stars.find('span').width(size);
        // Replace the numerical value with stars
        $(this).replaceWith(stars);
    });
}

function checkEnter (e) {
    var characterCode;

    if (e && e.which) {
        characterCode = e.which;
    } else {
        characterCode = e.keyCode;
    }

    if (characterCode == Event.KEY_RETURN) {
        return true;
    } else {
        return false;
    }
}

DB.reloadProfileImage = function (img, size) {
    if (img.is(':visible')) {
        // if element is already showing, it should already have a src
        DB.reloadImage(img);
        return false;
    }

    var image_uri = DB.profile_action_uri('/settings/profile_image');
    if (size) image_uri = image_uri + '?size=' + size;

    $.ajax({
        type: 'GET',
        url: image_uri,
        success: function(res) {
            img.attr('src', image_uri);
            img.show();
            return false;
        }
    });

    return false;
};
    
DB.reloadImage = function (imgElement) {
    var obj = imgElement;
    var src = obj.attr('src');
    var pos = src.indexOf('?');
    var args;
    if (pos >= 0) {
        // get other args e.g. size
        args = src.substr(++pos);
        // get uri 
        src = src.substr(0, --pos);
    }
    var date = new Date();
    var string = src;
    // add '?'
    if ( ! string.match(/\?/g) ) string = string + '?';
    if (args) {
       // add args
       string = string + args + '&v=' + date.getTime();
    } else {
       // add a version string
       string = string + 'v=' + date.getTime();
    }
    // set src attr
    obj.attr('src', string);
    return false;
};

DB.getRandomColor = function () {
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
};

function confirmDelete(url) {
    if (confirm("Are you sure you want to delete this record?")) {
        document.location = url;
    }
}

// given a dr id, go to their blog
DB.goToDrBlog = function (drId) {
    try {
        drId = String(Number(drId));
    } catch (e) {}
    window.location.href = '/blog/dr-' + drId;
};

$.extend({
    selectStarRatingValue: function(el){    
    }
});

