﻿function ResolveUrl(relativeUrl) {
    try {
        if (relativeUrl.indexOf("~/") == 0) {
            return appPath + relativeUrl.substr(2);
        } else {
            return relativeUrl;
        }
    }
    catch (ex) { return relativeUrl; }
}
String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str)
};
String.prototype.endsWith = function(str) {
    return (this.match(str + "$") == str) 
};
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
};
String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
};
String.prototype.toProperCase = function() {
    return this.toLowerCase().replace(/^(.)|\s(.)/g,
      function($1) { return $1.toUpperCase(); });
};

function weembo_FormatPhone(num) {
    //if contains alpha characters, do nothing to it
    var regex = new RegExp(/[a-zA-Z]/);
    var match = regex.exec(num);

    if (match == null) {
        var num2 = num.replace(/\D/gi, "");

        if (num2.length == 10) {
            return "(" + num2.substr(0, 3) + ") " + num2.substr(3, 3) + "-" + num2.substr(6, 4);
        }
        else if (num.length == 11) {
            return "(" + num2.substr(0, 4) + ") " + num2.substr(4, 3) + "-" + num2.substr(7, 4);
        }
    }
    return num;
}
function weembo_FormatCurrency(num) {
    if (!isNaN(parseFloat(num.replace("$","")))) {
        num = num.replace("$","").replace(/,/gi, "");
        return weembo_toDollarString("$" + parseFloat(num).toFixed(2));
    }
    return num;
}
function weembo_toDollarString(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}
function weembo_FormatPercent(num) {
    if (!isNaN(parseFloat(num))) {
        return parseFloat(num)+" %";
    }
    return num;
}
function weembo_confirmDelete(inputName) {
    if (inputName == null) inputName = "name";
    var name = $(".weembo input[name='" + inputName + "']").val();
    if (name == null) name = "this"
    return confirm("Are you sure you want to delete "+name+"?");
}
function weembo_NumbersOnly(e) {
    if (weembo_IsNavKey(e)) {return true; }
    if (e.shiftKey) {return false; }
    if ((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105)) {
        return true;
    }
    return false;
}
function weembo_IsNavKey(e) {
    if (e.which >= 35 && e.which <= 40) {
        return true;
    }
    if (e.which == 16 || e.which == 8 || e.which == 0 || e.which == 46) {
        return true;
    }
}
function weembo_InitializeUI(parentEl) {
    $(".weembo .fg-button:not(.ui-state-disabled)", parentEl)
		.hover(
			function() {
			    $(this).addClass("ui-state-hover");
			},
			function() {
			    $(this).removeClass("ui-state-hover");
			}
		)
		.mousedown(function() {
		    $(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
		    if ($(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')) { $(this).removeClass("ui-state-active"); }
		    else { $(this).addClass("ui-state-active"); }
		})
		.mouseup(function() {
		    if (!$(this).is('.fg-button-toggleable'/*, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button'*/)) {
		        $(this).removeClass("ui-state-active");
		    }
		});

	$(".weembo .im-upload").each(function() {
	    var td = $(this);
	    var hdnAction = td.find("input.im-upload-action");
	    var aDel = td.find("a.im-upload-button-delete");
	    var aAdd = td.find("a.im-upload-button-add");
	    var aCancel = td.find("a.im-upload-button-cancel");
	    var hasFile = td.find(".im-upload-cur").length == 1;
	    aDel.click(function() {
	        hdnAction.val("delete");
	        aCancel.show();
	        aDel.hide();
	        aAdd.hide();
	        td.find(".im-upload-cur-text").hide();
	        td.find(".im-upload-cur-del").show();
	    });
	    aCancel.click(function() {
	        hdnAction.val("");
	        aCancel.hide();
	        if (hasFile) {
	            td.find(".im-upload-cur").show();
	            td.find(".im-upload-cur-text").show();
	            td.find(".im-upload-cur-del").hide();
	            td.find(".im-upload-new").hide();
	            aDel.show();
	            aAdd.show();
	        }
	        else {
	            td.find(".im-upload-cur").show();
	            td.find(".im-upload-cur-text").show();
	        }
	    });
	    aAdd.click(function() {
	        hdnAction.val("add");
	        aCancel.show();
	        aDel.hide();
	        aAdd.hide();
	        td.find(".im-upload-new").show();
	        td.find(".im-upload-cur").hide();
	    });
	});

	//Bind date picker fields
	$(".weembo input.datepicker", parentEl).datepicker({
	    showOn: 'button',
	    buttonImage: ResolveUrl('~/Content/Weembo/images/icons/20/calendar.png'),
	    buttonImageOnly: true
	    //,onSelect: function(a, b) { $("#aspnetForm").validate().element(b.input); }
	});

	//Bind phone fields
	$(".weembo input.phone", parentEl).blur(function() {
	    this.value = weembo_FormatPhone(this.value);
	    //$("#aspnetForm").validate().element(this);
	});

	//Bind currency fields
	$(".weembo input.currency", parentEl).blur(function() {
	    this.value = weembo_FormatCurrency(this.value);
	    //$("#aspnetForm").validate().element(this);
	});

	//Bind percent fields
	$(".weembo input.percent", parentEl).blur(function() {
	    this.value = weembo_FormatPercent(this.value);
	    //$("#aspnetForm").validate().element(this);
	});

	//Bind url fields
	$(".weembo input.url", parentEl).blur(function() {
	    if (this.value.indexOf(":") == -1) {
	        if (this.value.split(".").length == 2) {
	            this.value = "http://www." + this.value;
	            //$("#aspnetForm").validate().element(this);
	        } else if (this.value.split(".").length == 3) {
	            this.value = "http://" + this.value;
	            //$("#aspnetForm").validate().element(this);
	        }
	    }
	});

	if ($(".weembo input.time", parentEl).length > 0) {
	    $(".weembo input.time", parentEl).Watermark("12:00 AM");
	}
	if ($(".weembo input.address-street1", parentEl).length > 0) {
	    $(".weembo input.address-street1", parentEl).Watermark("Street");
	    $(".weembo input.address-street2", parentEl).Watermark("Street Line 2");
	    $(".weembo input.address-city", parentEl).Watermark("City");
	    $(".weembo input.address-state", parentEl).Watermark("State");
	    $(".weembo input.address-zip", parentEl).Watermark("Zip");
	}
	$(".weembo table.expandable", parentEl).each(function() { weembo_MakeExpandableTable(this); });

	$(".weembo form", parentEl).each(function() {

	    var form = $(this);
	    form.validate({
	        ignore: ".novalidatehidden:hidden",
	        errorContainer: $("div.errors", form),
	        errorLabelContainer: $("div.errors div", form),
	        errorClass: "ui-state-error",
	        event: "blur",
	        onkeyup: false,
	        onsubmit: true,
	        onblur: true,
	        focusCleanup: false
	    });

	    $("a.submit, input:submit, button:submit", form).click(function() {
	        $.Watermark.HideAll();

	        var valid = form.valid();
	        if (!valid) {
	            $.Watermark.ShowAll();
	            return false;
	        }
	        else {
	            form.submit();
	        }
	    });

	});
	$(".weembo .initialFocus", parentEl).focus();
	//$("select").selectmenu({style:"dropdown"});
}
$(function() {
    weembo_InitializeUI(document);
    $(".weembo #mainMenu li.ui-state-default")
		.hover(
			function() {
			    $(this).addClass("ui-state-hover");
			},
			function() {
			    $(this).removeClass("ui-state-hover");
			}
		);
});
function weembo_MakeExpandableTable(table, afterAdd, afterRemove) {
    table = $(table);
    var addBtn = $("a#" + table.attr("id") + "-add");
    var checkAndHide = function() {
        if (table.find("tbody tr").length == 1) //table is now empty
        {
            table.hide(); //hide it
            table.parent(".ui-jqgrid").hide();
        }
    }
    checkAndHide();

    var rem = function() {
        checkAndHide();
        $(this).parents("tr:first").remove();

        if (afterRemove) afterRemove();
    }
    table.find("a.remove").click(rem);
    
    var template = table.find("tr.template").remove();
    addBtn.click(function() {
        table.show();
        table.parent(".ui-jqgrid").show();
        
        var newTr = template.clone();
        newTr.appendTo(table).removeClass("template").show();
        newTr.find("a.remove").click(rem);

        var firstFocusable = newTr.find("a,frame,iframe,label,input,select,textarea,button").filter(":visible").filter(":enabled")[0];
        if (firstFocusable != null) $(firstFocusable).focus();
        weembo_InitializeUI(newTr);
        if (afterAdd) afterAdd();
    });
}

{ //extend jQuery.fn.fmatter
    var oldfmatter = $.fn.fmatter;

    $.fn.fmatter = function(formatType, cellval, opts, rwd, act) {
        opts = $.extend({}, $.jgrid.formatter, opts);
        return weembo_fireFormatter(formatType, cellval, opts, rwd, act);
    };

    $.fn.fmatter.unformat = oldfmatter.unformat;

    $.fn.fmatter.bool = function(cellval, opts, act) {
        if (cellval) {
            return '<img src="'+ResolveUrl("~/Content/Weembo/images/icons/16/check.png")+'" />';
        }
        else {
            return '&nbsp;';
        }
    };

    function weembo_fireFormatter(formatType, cellval, opts, rwd, act) {
        formatType = formatType.toLowerCase();
        var v = cellval;
        switch (formatType) {
            case 'link': v = oldfmatter.link(cellval, opts); break;
            case 'showlink': v = oldfmatter.showlink(cellval, opts); break;
            case 'email': v = oldfmatter.email(cellval, opts); break;
            case 'currency': v = oldfmatter.currency(cellval, opts); break;
            case 'date': v = oldfmatter.date(cellval, opts, act); break;
            case 'number': v = oldfmatter.number(cellval, opts); break;
            case 'integer': v = oldfmatter.integer(cellval, opts); break;
            case 'checkbox': v = oldfmatter.checkbox(cellval, opts); break;
            case 'select': v = oldfmatter.select(cellval, opts, act); break;
            
            case 'bool': v = $.fn.fmatter.bool(cellval, opts, act); break;
        }
        return v;
    };
}



