﻿//sort select options list alphabetically(by descr aka .text)
$.fn.sort_select_box = function() {
    var my_options = $("#" + this.attr('id') + ' option');
    my_options.sort(function(a, b) {
        if (a.text > b.text) return 1;
        else if (a.text < b.text) return -1;
        else return 0
    })
    this.empty().append(my_options);
}

//centre element midscreen
$.fn.centre = function(bx, by) {
    if (bx == undefined || bx == null)
        bx = true;

    if (by == undefined || by == null)
        by = true;

    var _div_to_center = this;
    if (_div_to_center.parents(".blockUI").length)
        _div_to_center = _div_to_center.parents(".blockUI");

    _div_to_center.css({ "position": "absolute" });

    var _osHeightCenter = _div_to_center.attr("offsetHeight");
    var _osHeightScreen = _getScreenHeight();
    var _distanceTop = parseInt((_osHeightScreen / 2) - (_osHeightCenter / 2) + (getScrollXY()[1]));
    if (_distanceTop < 0) {
        _distanceTop = 0;
    }

    var _osWidthCenter = _div_to_center.attr("offsetWidth");
    var _osWidthScreen = _getScreenWidth();
    var left = parseInt((_osWidthScreen / 2) - (_osWidthCenter / 2) + (getScrollXY()[0]));
    if (!$.browser.msie)
        left -= 10;//seems like taking off the padding???
    if (bx)
        _div_to_center.css({ "left": left });

    if (by)
        _div_to_center.css({ "top": _distanceTop });
}


$.fn.updategrid = function() {
    if (this.length) {
        var grid = this.data('tGrid');
        if (grid != null && grid != undefined)
            grid.rebind();
    }
}

var close_title = "Klik om te sluiten";
//iframe module version
$.fn.openpopup = function(src, pw, ph) {
    //start init section-->
    //self reference for enclosed functions
    var _this = this;
    _this.hide();
    $("*").css("cursor", "wait");
    addContent();

    //    initCancel();
    //    initCloseOnOverlayClick();
    //<--end of init section

    function addContent() {
        if (src != undefined) {
            var w = "880px";
            var wi = "870";
            var h = "450";
            if (pw != undefined) {
                w = pw + "px";
                wi = pw - 10; //take of popup padding
            }
            if (ph != undefined)
                h = ph;
            //functionality to allow multiple popupforms
            _this.html('');
            _this.append(
                '<iframe id="popframe" src="' + src + '" frameborder="0"' +
                        ' scrolling="auto" width="' + wi + '" height="' + h + '"' + 
                        'style="min-height:300px;"' +
                        ' />');
            //_this.append('<div class="seper" />');
            //            $('#popframe').one('load', (function() {
            //                _this.show();
            //                $.blockUI(
            //                {
            //                    message: _this, //_this as content
            //                    onUnblock: function() { $("#popup").html(''); },
            //                    css: { width: w }
            //                });

            //                //always recentre
            //                setTimeout(function() {
            //                    var hp = parseInt(h) + 40;
            //                    initDatePickers();
            //                    initCancel();
            //                    initCloseOnOverlayClick();
            //                    _this.parents(".blockPage").css({ height: hp + "px" });
            //                    _this.parents(".blockPage").centre();
            //                    //_this.centre();
            //                }, 15);
            //            }));
            $('#popframe').one('load', (function() {
                _this.show();
                $("*").css("cursor", "");
                $.blockUI();
                initDatePickers();
                initCancel();
                initCloseOnOverlayClick();
                $(".blockPage").hide();
                //always recentre
                _this.centre();
            }));
        }
    }

    function initCloseOnOverlayClick() {
        //close on overlay click
        $('.blockOverlay').attr('title', close_title).click(function() {
            _this.closepopup();
        });

    }

    function initCancel() {
        //close on cancel
        _this.append('<input type="submit" value="Sluiten" class="cancelpopup" />');
        _this.find(".cancelpopup").attr('title', close_title).click(function(e) {
            _this.closepopup();
            return false;
        });
    }
}

$.fn.ajaxifyForm = function() {
    
    var curform = this;
    if(this.get(0).tagName.toLowerCase() != "form")
        curform = this.find("form:first");

    if (curform.length) {
        var cfid = curform.attr("id");
        //onsuccessfunction
        var osf = curform.find(".osf:first");
        var bosf = false;

        if (osf.length) {
            osf = osf.val();
            osf = new Function(osf);
            bosf = true;
        }
        var options = {
            target: '#popup' + nof_open_popups,
            //beforeSubmit: showRequest,
            success: function() {
                if (bosf) {
                    osf();
                }
            }
        };
        $('#' + cfid).ajaxForm(options);
    }
}

$.fn.closepopup = function(msg) {
    $.unblockUI();
    this.hide();
    if (msg != undefined) {
        $.growlUI(null, msg, 4000);
    }
}

$.fn.period_selector = function() {
    var ermsg = period_error;
    var _this = this;
    var dfrom = this.find(".dfrom");
    var dtill = this.find(".dtill");

    if (bindIfNotBound(dfrom, "change")) {
        dfrom.change(function() {
            testPeriod();
        });
    }
    if (bindIfNotBound(dtill, "change")) {
        dtill.change(function() {
            testPeriod();
        });
    }

    function testPeriod() {
        if (dfrom.val() != "" && dtill.val() != "") {
            var startDate = setDateValue(dfrom.val());
            var endDate = setDateValue(dtill.val());
            var v = _this.find(".period-validator");
            v.hide();
            if (endDate <= startDate) {
                v.text(ermsg);
                v.addClass("field-validation-error");
                v.show();
            }
        }
    }

    function setDateValue(d) {
        var ard = d.split("-");
        var day = ard[0];
        var m = ard[1];
        var y = ard[1];
        return new Date(y + "/" + m + "/" + day);
    }
}

//for grid delete buttons
$.fn.delitify = function(_useconfirm, confirmmessage, callback) {
    var cf = deletebtn_confirm;
    if (confirmmessage != undefined && confirmmessage != null)
        cf = confirmmessage;
    var useconfirm = true;
    if (_useconfirm != undefined)
        useconfirm = _useconfirm
    var godelete = false;
    if (!useconfirm)
        godelete = true;

    var gridid = this.attr("id");
    this.find(".griddeletebtn").click(function() {
        if (useconfirm)
            godelete = confirm(cf);
        if (godelete) {
            $.delete_("/Intern/Delete/" + $(this).attr("id"), function(data) {
                if (data.success) {
                    $("#" + gridid).updategrid();
                    if (callback != undefined && callback != null)
                        eval(callback);
                }
                $.growlUI(null, data.message);
            });
        }
    }).attr("title", deletebtn_title);
}

