﻿/// For Intellisense
/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="jquery-ui-1.7.2.custom.js" />
/// <reference path="MicrosoftAjax.debug.js" />
/// <reference path="MicrosoftAjaxTemplates.debug.js" />
/// <reference path="MicrosoftMvcAjax.debug.js" />
/// <reference path="Navitopia.jQuery.js" />
/// <reference path="NavitopiaRepository.js" />
/// <reference path="NavitopiaCrud.js" />
/// <reference path="Navitopia.js" />

//**********************************************//
// Thanks to http://www.rgagnon.com/howto.html *//
// for the regular expressions.                *//
//**********************************************//

// jQuery extensions
jQuery.fn.extend({
    createCallback: function(method) {
        var _this = this.get(0);

        if ("function" != typeof (method))
            throw "createCallback requires a function parameter";

        return function() {
            method.apply(_this, arguments);
        }
    },

    fillTemplate: function(templateId, data) {
        var template;

        clearErrors();

        template = getTemplate(templateId);
        template.instantiateIn(this.empty().get(0), data);
        if (data.valueOf().StartAddress != null) {
            if (templateId == "editTemplate" && data.valueOf().EndAddress.length <= 1)
                $("#detailactions").hide();
            if (templateId == "editTemplate") {
                $('#StartDate').datepick({ showOn: 'both', buttonImageOnly: true,
                    buttonImage: '/Content/images/cal.gif'
                });
                $('#EndDate').datepick({ showOn: 'both', buttonImageOnly: true,
                    buttonImage: '/Content/images/cal.gif'
                });
                $('#StartTime').timeEntry({ ampmPrefix: ' ', spinnerImage: '/Content/Images/spinnerGreen.png',
                    spinnerSize: [20, 20, 0], spinnerBigSize: [40, 40, 0]
                });
                $('#EndTime').timeEntry({ ampmPrefix: ' ', spinnerImage: '/Content/Images/spinnerGreen.png',
                    spinnerSize: [20, 20, 0], spinnerBigSize: [40, 40, 0]
                });
                if (!IsEvent)
                    $('#Recurring').hide();
                else
                    $('#Recurring').tooltip();
                $('#IsDriver').tooltip();
                $('#FBFriends').tooltip();
            }
        }
        this.hookWatermarks();

        return this;
    },

    format: function(formatString) {
        $(this).each(function() {
            var className = $(this).attr("class");
            var value;
            var isDecClass, isIntClass, isMoneyClass, useText = false;

            if ("undefined" == typeof ($(this).attr("value"))) {
                useText = true;
                value = $.trim($(this).text());
            } else value = $.trim($(this).val());

            isDecClass = isIntClass = isMoneyClass = false;

            if (-1 != className.indexOf("datetime")) {
                value = new Date(Date.parse(value));
                if (isNaN(value)) return;

                if (value.getFullYear() < 1970)
                    value.setFullYear(value.getFullYear() + 100);

                if (!formatString) formatString = $.dateTimeFormat;

                if (formatString)
                    value = String.format("{0:" + formatString + "}", value);
            } else if ((isMoneyClass = (-1 != className.indexOf("money"))) ||
				(isDecClass = (-1 != className.indexOf("decimal"))) ||
				(isIntClass = (-1 != className.indexOf("integer")))) {

                var regExp = /-?[0-9]+\.*[0-9]{0,2}$/;

                value = $.removeCurrency(value);

                if (regExp.test(value)) {
                    if (isMoneyClass) {
                        regExp = /^-/;

                        if (regExp.test(value))
                            value = '(' + value.replace(regExp, '') + ')';
                    }

                    if (!$.isNumber(value)) value = 0;

                    if (isIntClass) value = Math.floor(value);
                    else {
                        value = (Math.round(value * 100)) / 100;
                        value = (value == Math.floor(value) ? value + ".00" :
							((value * 10 == Math.floor(value * 10)) ? value + "0" : value));
                    }

                    value = $.insertCommas(value);
                    if (isMoneyClass) value = '$' + value;
                }
            } else return;

            if (useText) $(this).text(value);
            else $(this).val(value);
        });

        return $(this);
    },

    getFormValues: function() {
        var data = {};

        $("input", this).not(":checkbox").not(":radio").add("select", this).add("textarea", this).each(
			function() {
			    if ($(this).attr("id")) {
			        var thisClasses = $(this).attr("class");
			        var regExp = /(decimal)|(integer)|(money)/;

			        var value = $.trim($(this).val());

			        if (regExp.test(thisClasses)) {
			            value = $.removeCurrency(value);
			        }

			        data[$(this).attr("id")] = value;
			    }
			}
		);

        $("input:checkbox", this).each(
			function() {
			    if ($(this).attr("id")) data[$(this).attr("id")] = $(this).attr("checked");
			}
		);

        $("input:radio", this).each(
			function() {
			    if ($(this).attr("name") && $(this).attr("checked"))
			        data[$(this).attr("name")] = $(this).val();
			}
		);

        return data;
    },

    getRights: function() {
        var allowRights = 0, denyRights = 0;

        $("input:checked[class*='allow']", this).each(
			function() { allowRights += parseInt($(this).val(), 10); });

        $("input:checked[class*='deny']", this).each(
			function() { denyRights += parseInt($(this).val(), 10); });

        return { allowRights: allowRights, denyRights: denyRights };
    },

    hookWatermarks: function() {
        $(".watermark", this).each(
			function() {
			    $(this)
					.focus(function() {
					    if ($(this).oldval() == $(this).attr("watermark"))
					        $(this).removeClass("wmactive").oldval("");
					})
					.blur(function() {
					    if ($.trim($(this).oldval()) == "")
					        $(this).addClass("wmactive").oldval($(this).attr("watermark"));
					});
			}
		);

        return this;
    },

    isParentOf: function(child) {
        return -1 != $.inArray($(child)[0], $("*", this));
    },

    oldval: jQuery.fn.val,

    setRights: function(allowRights, denyRights) {
        $(".allow" + rightsCRUD, this)
			.attr("checked", (allowRights & rightsCRUD) == rightsCRUD);
        $(".allow" + rightsSeeCalendar, this)
			.attr("checked", (allowRights & rightsSeeCalendar) == rightsSeeCalendar);
        $(".allow" + rightsSeeDetails, this)
			.attr("checked", (allowRights & rightsSeeDetails) == rightsSeeDetails);
        $(".allow" + rightsSeeParticipants, this)
			.attr("checked", (allowRights & rightsSeeParticipants) == rightsSeeParticipants);

        $(".deny" + rightsCRUD, this)
			.attr("checked", (denyRights & rightsCRUD) == rightsCRUD);
        $(".deny" + rightsSeeCalendar, this)
			.attr("checked", (denyRights & rightsSeeCalendar) == rightsSeeCalendar);
        $(".deny" + rightsSeeDetails, this)
			.attr("checked", (denyRights & rightsSeeDetails) == rightsSeeDetails);
        $(".deny" + rightsSeeParticipants, this)
			.attr("checked", (denyRights & rightsSeeParticipants) == rightsSeeParticipants);

        return this;
    },

    val: function(value) {
        if (0 == arguments.length) {
            if ($(this).hasClass("watermark") &&
				$(this).oldval() == $(this).attr("watermark"))
                return "";
            else return $(this).oldval();
        } else return $(this).oldval(value);
    },

    // Validates a form by checking the value of each input
    // element against its "regex" attribute, if it has one.
    validateForm: function(messageElm) {
        var validated = true;

        clearErrors();

        $("input", this).each(
			function() {
			    var regex = $(this).attr("regex");
			    if (regex) {
			        if (-1 == $(this).val().search(regex)) {
			            showError($(this).attr("error"), this);
			            validated = false;
			            return false;
			        }
			    }
			}
		);

        return validated;
    }
});

jQuery.extend({
	dateTimeFormat: "MM/dd/yyyy hh:mm tt",

	imageDir: "/Content/images/",

	insertCommas: function(value){
		var regExp  = /(-?[0-9]+)([0-9]{3})/;

		value = new String(value); // In case we're passed a "number"
		while( regExp.test(value) ){
			value = value.replace(regExp, '$1,$2');
		}

		return value;
	},

	isInteger: function(value){
		var regExp  =  /(^-?\d\d*$)/;
		return regExp.test(value);
	},

	isNumber: function(value){
		var regExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
		return regExp.test(value);
	},

	removeCurrency: function(value){
		var regExp = /\(/;
		var minus = regExp.test(value) ? '-' : '';

		regExp = /\)|\(|[,]|\$/g;
		value = value.replace(regExp,'');

		return minus + value;
	}
});

// Extensions to javascript objects
String.prototype.left = function(len){
  if( len <= 0 ) return "";
  else if( len >= this.length ) return this;
  else return this.substr(0, len);
}

String.prototype.right = function(len){
  if( len <= 0 ) return "";
  else if( len >= this.length ) return this;
  else return this.substr(this.length - len, len);
}

// Set date picker defaults
var dateOptions = {
	buttonImage: $.imageDir + "cal.gif",
	buttonImageOnly: true, 
	buttonText: "Show calendar",
	closeText: "Close",
	dateFormat: "mm/dd/yy",
	showButtonPanel: true,
	showOn: "button"
};

$.datepicker.setDefaults(dateOptions);
