﻿// GLOBAL VARS
var ajaxReload = function() { };
var wymEditors = new Array();

var defaultModalWidth = 640;
var defaultModalHeight = 600;

jQuery.stringFormat = function(format, arguments) {
    var str = format;
    for (i = 0; i < arguments.length; i++) {
        while (str.indexOf('{' + i + '}') != -1) str = str.replace('{' + i + '}', arguments[i]);        
    }
    return str;
};

jQuery.startsWith = function(value, comparer) {
    return (comparer == value.substring(0, comparer.length));
}

jQuery.addMonth = function(d, month) {
    t = Date.parse(d);
    t.addMonths(month);
    var newString = t.toString("dd/MM/yyyy");
    return newString;
};

jQuery.updateForm = function(model) {
    for (var property in model) {
        var propertyValue = eval("model." + property);
        $("#" + property).val(propertyValue);
    }
};

jQuery.idle = function(time, callback) {
    setTimeout(callback, time);
};

jQuery.setWymEditor = function(editor) {
    wymEditors.push(editor);
};

jQuery.twoDecimals = function(num) {
    return Math.round(num * 100) / 100;
};

jQuery.updateWymEditor = function() {
    $.each(wymEditors, function() {
        this.update();
    });

    wymEditors = new Array();
};

jQuery.populateSelectbyKeyValue = function(selectId, data) {
    $.each(data, function() {
        var option = new Option(this.Value, this.Key);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
    });
};
jQuery.populateSelectbyIdName = function(selectId, data) {
    $.each(data, function() {
        var option = new Option(this.name, this.id);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
    });
};
jQuery.populateSelect = function(selectId, data) {
    $.each(data, function() {
        var option = new Option(this.text, this.value);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
    });
};

jQuery.showTooltip = function(wrapperDiv, trigger, width, height, title, text) {
    var pos = $(trigger).offset();
    var eWidth = $(trigger).outerWidth();
    var mWidth = $(trigger).outerWidth();
    var left = (pos.left + eWidth - mWidth) - width + "px";
    var top = (3 + pos.top) - height + "px";
    $("#" + wrapperDiv + " .tooltip").css({
        position: 'absolute',
        zIndex: 5000,
        left: left,
        top: top
    });
    $("#" + wrapperDiv + " .tooltipTitle").html(title);
    $("#" + wrapperDiv + " .tooltipText").html(text);
    $("#" + wrapperDiv + " .tooltip").stop().show('blind', '200');
}

jQuery.hideTooltip = function(wrapperDiv) {
    $("#" + wrapperDiv + " .tooltip").hide();
}

jQuery.encHTML = function(items) {
    return items.each(function() {
        var me = jQuery(this);
        var html = me.html();
        me.html(html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'));
    });
};

jQuery.decHTML = function(items) {
    return items.each(function() {
        var me = jQuery(this);
        var html = me.html();
        me.html(html.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
    });
};

jQuery.isEncHTML = function(str) {
    if (str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1)
        return true;
    else
        return false;
};

jQuery.decHTMLifEnc = function() {
    return this.each(function() {
        var me = jQuery(this);
        var html = me.html();
        if (jQuery.fn.isEncHTML(html))
            me.html(html.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
    });
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function() {
    $.nyroModalSettings({
        minWidth: defaultModalWidth,
        minHeight: defaultModalHeight,
        showLoading: true,
        endRemove: ajaxReload,
        showLoading: function(elts, settings, callback) {
            callback();
        },
        showContent: function(elts, settings, callback) {
            elts.contentWrapper
		.css({
		    width: settings.width + 'px',
		    height: settings.height + 'px',
		    marginTop: settings.marginTop + 'px',
		    marginLeft: settings.marginLeft + 'px'
		})
		.show();
            elts.loading.fadeOut(1, callback);
        },
        hideContent: function(elts, settings, callback) {
            elts.contentWrapper.hide();
            callback();
        }
    });

    $('.textEditor').wymeditor({
        toolsItems: [
                { 'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong' },
                { 'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis' },
                { 'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste' },
                { 'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo' },
                { 'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo' }
            ],
        boxHtml: "<div class='wym_box'>"
              + "<div class='wym_area_top'>"
              + WYMeditor.TOOLS
              + "</div>"
              + "<div class='wym_area_main'>"
              + WYMeditor.IFRAME
              + "</div>"
              + "</div>"
    });

    $('.htmlEditor').wymeditor({
        boxHtml: "<div class='wym_box'>"
              + "<div class='wym_area_top'>"
              + WYMeditor.TOOLS
              + "</div>"
              + "<div class='wym_area_main'>"
              + WYMeditor.HTML
              + WYMeditor.IFRAME
              + "</div>"
              + "</div>"
    });
});

$(function() {
    xOffset = 10;
    yOffset = 20;

    $(".ajaxCall").live("click", function(e) {
        e.preventDefault();
        $.get($(this).attr("href"), ajaxReload);
    });

    $(".yesNoAjaxCall").live("click", function(e) {
        e.preventDefault();
        var title = $(this).attr("title");
        if(title == null || title == "" || title==undefined)
            title = 'Are you sure?';
        if (confirm(title)) {
            $.get($(this).attr("href"), ajaxReload);
        }
    });

    $('.printButton').live("click", function() {
        window.print();
        return false;
    });

    $(".tooltip").live("mouseover", function(e) {
        this.t = this.title;
        this.title = "";
        $("body").append("<p id='tooltip'>" + this.t + "</p>");
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
    });

    $(".tooltip").live("mouseout", function(e) {
        this.title = this.t;
        $("#tooltip").remove();
    });

    $(".tooltip").live("mousemove", function(e) {
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
    });
});

jQuery.validateEmail = function(value) {
    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}