﻿


function confPost() {
    return confirm("هل انت متأكد من ترحيل هذا القيد؟");
}
function confFiscalPeriod() {
    return confirm("هل انت متأكد من تغيير حالة هذه الفترة المالية؟");
}
function confFiscalYear() {
    var conf = confirm("هل انت متأكد من إغلاق هذه السنة المالية؟");
    if (conf) conf = confirm("رسالة تنبيهية للمرة الثانية , هل انت متأكد من إغلاق هذه السنة المالية؟");
    return conf;
}

function confLeaveRule() {
    var conf = confirm("هل انت متأكد من حفظ هذه القاعدة ؟, سيتم اعادة احتساب أرصدة الاجازة من بعد تاريخ التفعيل طبقا للتغيرات الجديدة");
    if (conf) conf = confirm("رسالة تنبيهية للمرة الثانية , هل انت متأكد من هذا الاجراء؟");
    return conf;
}

function confChangeHiringData() {
    var conf = confirm("هل انت متأكد من الاجراء ؟");
    if (conf) conf = confirm("رسالة تنبيهية للمرة الثانية , هل انت متأكد من الاجراء ؟");
    return conf;
}




function confDelete() {
    return confirm(_confDelete);
}
function confDeleteFile() {
    return confirm(_confDeleteFile);
}




var inProgress = false;
function InitialJqueryUi() {
    $(document).ready(function () {
        try {

            $('.uiButton').button({ ampm: true });
            $.datepicker.setDefaults($.datepicker.regional[_culture]);
            $.timepicker.setDefaults($.datepicker.regional[_culture]);
            $(".datepicker").datepicker({ changeYear: true, showButtonPanel: true, selectOtherMonths: true });
            $('.datetimepicker').datetimepicker({ ampm: false });
            $('.timepicker').timepicker({ ampm: false });
            $('.monthpicker').datepicker({
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                dateFormat: 'mm/yy',
                onSelect: function (dateText, inst) { alert(dateText); },
                //                onClose: function (dateText, inst) {
                //                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                //                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                //                    $(this).datepicker('setDate', new Date(year, month, 1));
                //                },
                beforeShow: function (input, inst) {
                    if ((datestr = $(this).val()).length > 0) {
                        var myAR = datestr.split('/');
                        year = myAR[1];

                        month = parseInt(myAR[0]) - 1;
                        $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                        $(this).datepicker('setDate', new Date(year, month, 1));
                    }
                }
            });
            $(".monthpicker").focus(function () {
                var txtObject = $(this);
                $('.ui-datepicker-close').bind("click", function () {
                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    txtObject.datepicker('setDate', new Date(year, month, 1));
                });
                $(".ui-datepicker-calendar").hide();
                $("#ui-datepicker-div").position({
                    my: "center top",
                    at: "center bottom",
                    of: $(this)
                });
            });

            $(".accordion").accordion({
                animated: false,
                create: function (event, ui) {
                    var index = GetHashValue(this.id);
                    if (index) {
                        $(this).accordion("activate", parseInt(index));
                    }
                }
                ,
                change: function (event, ui) {
                    AppendHashValue(this.id, jQuery(this).find("> h3").index(ui.newHeader[0]));
                }

            }

            );

            $(".tabs").tabs(
            {
                //fx: { opacity: 'toggle' },

                create: function (event, ui) {

                    var index = GetHashValue(this.id);
                    if (index) {
                        $(this).tabs("select", parseInt(index));
                    }
                }
                ,
                select: function (event, ui) {

                    AppendHashValue(this.id, ui.index);
                }
            }
            );

        } catch (e) { }

    });
}


var textboxes;


function checkForEnter(event) {
    if (event.keyCode == 13) {
        currentBoxNumber = textboxes.index(this);
        if (textboxes[currentBoxNumber + 1] != null) {
            nextBox = textboxes[currentBoxNumber + 1]
            nextBox.focus();
            nextBox.select();
            event.preventDefault();
            return false;
        }
    }
}

function initializeApp() {

   
    InitialJqueryUi();
    $(document).ready(function () {

        // get only input tags with class data-entry
        textboxes = $('input[type="text"],input[type="number"],input[type="date"],select,input[type="radio"],input[type="checkbox"]');
        // now we check to see which browser is being used
        if ($.browser.mozilla) {
            $(textboxes).keypress(checkForEnter);
        } else {
            $(textboxes).keydown(checkForEnter);
        }
        $(textboxes).focus(function () { this.select(); })
        //  AdjustPageHeight();

        try {
            $("#AjaxDialog").dialog(
            {
                autoOpen: false,
                show: "blind",
                hide: "explode",
                width: 750,
                modal: true
            }
        );
        } catch (e) { }
        $(document).mousemove(function (e) { $('#indicator').css('top', e.pageY + 20).css('left', e.pageX + 10); });
        try {
            var sideHeight = parseInt($('.menuContainer ul').css("height").replace('px', ''));
            var mainHeight = parseInt($('.contentMain').css("height").replace('px', ''));
            if (sideHeight > mainHeight) {
                $('.contentMain').css("min-height", sideHeight - 5);
            }
            else
                $('.menuContainer ul').css("height", mainHeight);
        } catch (ex) { }


        var contentHeight = $('.content').height();
        var htmlHeight = $('html').height();
        var windowHeight = $(window).height();
        if (windowHeight > htmlHeight) {
            $('.content').css("min-height", contentHeight + windowHeight - htmlHeight);
            //$('.content').height('auto');
        }

    });
}
function GetHashValue(key) {
    var ar = location.hash.split(";");
    for (var i = 0; i < ar.length; i++) {
        var kv = ar[i].split("=");
        if (kv && kv.length > 0) {
            if (kv[0].toLowerCase() == key.toLowerCase())
                return kv[1];

        }
    }
    return null;
}

function AppendHashValue(key, value) {

    var oldVal = GetHashValue(key);
    if (oldVal) {
        location.hash = location.hash.toLowerCase().replace(";" + key.toLowerCase() + "=" + oldVal.toLowerCase(), ";" + key.toLowerCase() + "=" + value.toString().toLowerCase())
    }
    else {
        location.hash = location.hash.toLowerCase() + ";" + key.toLowerCase() + "=" + value.toString().toLowerCase();
    }
}

initializeApp();


function nodeclick(element, keyVal) {
    if ($(element).attr("src").indexOf('plus.png') > -1) {
        $("." + keyVal).show();
        $(element).attr("src", "/_Content/Themes/blue/images/common/minus.png");
    } else {
        $("." + keyVal).hide();
        $(element).attr("src", "/_Content/Themes/images/common/plus.png");
    }


}
function treeNodeclick(element, keyVal) {
    if ($(element).attr("src").indexOf('plus.png') > -1) {
        $("#" + keyVal).show();
        $(element).attr("src", "/_Content/Themes/blue/images/common/minus.png");
    } else {
        $("#" + keyVal).hide();
        $(element).attr("src", "/_Content/Themes/blue/images/common/plus.png");
    }


}
//AutoComplete Method (when user Select item change value of an id hiddenfield to item value)
function GetAutoComplete(elementID, elementPropertyName, KeyPropertyName, url, changeFunction, getParametersFunction,explodeActionName) {

    $(function () {

        var element = $('#' + elementID);



        var filter;


        element.autocomplete({
       
            source: function (request, response) {
                filter = request.term;



                var newUrl = url;
                if (getParametersFunction)
                    newUrl = getParametersFunction(elementID, url);
                else
                    newUrl = newUrl + request.term;

                $.ajax
                        ({
                            url: newUrl,
                            dataType: 'json',
                            success: function (data) { response(data); }
                        });
            },
            minLength: 0
                    ,
            delay: 1000
                  ,
            focus: function (event, ui) {


                return false;
            }
                 ,

            select: function (event, ui) {
                $(this).val(ui.item.Value);
                var idField = $('#' + $(this).attr('id').replace(elementPropertyName, KeyPropertyName));
                idField.val(ui.item.Key);
                // alert(hiddenID);
                return false;
            }
                    , search: function (event, ui) {
                        var current = $(this);
                        var idField = $('#' + current.attr('id').replace(elementPropertyName, KeyPropertyName));
                        idField.val('');

                    }
                    , change: function (event, ui) {


                        var idField = $('#' + $(this).attr('id').replace(elementPropertyName, KeyPropertyName));
                        if (idField.val() == '')
                            $(this).val('');
                        if (explodeActionName != null && explodeActionName != "") {

                            if (ui.item.ExplodeType) {
                                $("#PMData").val(ui.item.ExplodeType + "," + ui.item.Key);
                                
                                SubmitForm(this, explodeActionName, false);
                            }
                        }
                        if (changeFunction)
                            changeFunction(elementID, ui.item);
                        return false;

                    }
        }).data('autocomplete')._renderItem = function (ul, item) {
            if (filter == '' || filter == null) {
                return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a>' + item.Value + '</a>')
				.appendTo(ul);
            }
            else {
                return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a>' + item.Value.replace(new RegExp('(' + filter + ')', 'gi'), "<span style='color:#DDBA15'>$1</span>") + '</a>')
				.appendTo(ul);
            }

        };
    });

}

function GetAutoComplete_Search(elementID, actionUrl, newUrl) {

    $(function () {
        var filter;
        $('#' + elementID).autocomplete({
        delay: 1000,
            source: function (request, response) {
                filter = request.term;
                var newUrl = actionUrl + request.term;

                $.ajax
                        ({
                            url: newUrl,
                            dataType: 'json',
                            success: function (data) { response(data); }
                        });
            },
            minLength: 0
                    ,
            delay: 0
                  ,
            focus: function (event, ui) {
                $(this).val(ui.item.Value); return false;
            },
            select: function (event, ui) {
                $(this).val(ui.item.Value);
                var queryString = "";
                
                if(location.href.lastIndexOf('?')>0)
                queryString=location.href.replace(location.href.substring(location.href.lastIndexOf('?') , 0),"");
               
                
                location.href = newUrl + "/" + ui.item.Key+queryString;
                return false;
            }
                    , search: function (event, ui) {


                    }
                    , change: function (event, ui) {


                    }
        }).data('autocomplete')._renderItem = function (ul, item) {
            if (filter == '' || filter == null) {
                return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a>' + item.Value + '</a>')
				.appendTo(ul);
            }
            else {
                return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a>' + item.Value.replace(new RegExp('(' + filter + ')', 'gi'), "<span style='color:#DDBA15'>$1</span>") + '</a>')
				.appendTo(ul);
            }
        };
    });
}



function SortGrid(newColumn, SortFieldID) {
    var element = $("#" + SortFieldID);
    var sortAr = element.val().split(" ");
    var newSort = newColumn;

    if (sortAr.length == 1 || sortAr[1] == "desc")
        newSort = newSort + " asc";
    else
        newSort = newSort + " desc";
    element.val(newSort);
}
function SubmitForm(element, ActionName, causeValidation) {
    var form = $(element).closest("form");
    //DIsable for telerik bashs
    //  form.validate().cancelSubmit = !causeValidation;
    //var valid = form.valid();
    //  if (causeValidation && valid || !causeValidation) {
    var hidAction = form.find("#ActionName");
    if (hidAction) {
        hidAction.val(ActionName);

        form.submit();
        return true;

    }
    else {
        alert("you forgot to add action hidden field");

    }
    //   }

}
function SubmitFormBySelector(formSelector, ActionName, causeValidation) {
    var form = $(formSelector);
    //DIsable for telerik bashs
    //  form.validate().cancelSubmit = !causeValidation;
    //var valid = form.valid();
    //  if (causeValidation && valid || !causeValidation) {
    var hidAction = form.find("#ActionName");
    if (hidAction) {
        hidAction.val(ActionName);
        form.submit();
        return true;

    }
    else {
        alert("you forgot to add action hidden field");

    }
    //   }

}
function ChangeValue(FieldID, newValue) {
    $("#" + FieldID).val(newValue);
}
function SaveTinyMceData() {
    try {
        tinyMCE.triggerSave(true, true);
    } catch (e) {

    }
}
function InitializeTinyMceEditor(id, theme) {
    try {
        tinyMCE.init({
            // General options
            mode: 'exact',
            elements: id,
            theme: theme,
            plugins: "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,preview,media,print,contextmenu,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
            // Theme options
            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,code,|,forecolor,backcolor",
            theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,

            // Example content CSS (should be your site CSS)
            content_css: "css/content.css",

            // Drop lists for link/image/media/template dialogs
            template_external_list_url: "lists/template_list.js",
            external_link_list_url: "lists/link_list.js",
            external_image_list_url: "lists/image_list.js",
            media_external_list_url: "lists/media_list.js",

            // Style formats
            style_formats: [
			{ title: 'Bold text', inline: 'b' },
			{ title: 'Red text', inline: 'span', styles: { color: '#ff0000'} },
			{ title: 'Red header', block: 'h1', styles: { color: '#ff0000'} },
			{ title: 'Example 1', inline: 'span', classes: 'example1' },
			{ title: 'Example 2', inline: 'span', classes: 'example2' },
			{ title: 'Table styles' },
			{ title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
		],

            // Replace values for the template plugin
            template_replace_values: {
                username: "Some User",
                staffid: "991234"
            }
        });
    } catch (e) {

    }

}


//========================================Ajax Dialod============================

function LoadDialogGetId(actionUrl, idField, getParametersFunction) {

    var idVal = $('#' + idField).val();
    if (idVal != '' && idVal != '00000000-0000-0000-0000-000000000000') {

        var newUrl = actionUrl;
        if (getParametersFunction)
            newUrl = getParametersFunction(idField, actionUrl);
        else
            newUrl = newUrl + '/' + idVal;

        LoadDialog(newUrl);
    }
}
function LoadDialog(actionUrl) {


    if (!inProgress) {
        inProgress = true;
        $("#indicator").show();
        $.ajax({
            url: actionUrl,
            type: 'get',
            dataType: "html",
            error: function (error) { alert(error); },
            success: function (result) {
                $('#AjaxDialog').html(result);
                $("#indicator").hide();
                inProgress = false;
                $('#AjaxDialog')
                .dialog
                (



                { buttons: [
    {
        text: _ok,
        click: function () { $(this).dialog("close"); }
    },
     {
         text: _gotopage,
         click: function () { location.href = actionUrl; }
     }
]
                }

                )
                .dialog("open");
            }
        });
    }
}
function LoadDialogNoButtons(actionUrl) {


    if (!inProgress) {
        inProgress = true;
        $("#indicator").show();
        $.ajax({
            url: actionUrl,
            type: 'get',
            dataType: "html",
            error: function (error) { alert(error); },
            success: function (result) {
                $('#AjaxDialog').html(result);
                $("#indicator").hide();
                inProgress = false;
                $('#AjaxDialog').dialog("open");

                initializeApp();
            }
        });
    }
}
function CloseDialog() {
    $('#AjaxDialog').dialog('close');
}


function LoadIframeDialogGetId(actionUrl, idField, getParametersFunction,saveScript) {

    var newUrl = actionUrl;
    if (idField != null && idField != '') {
        var idVal = $('#' + idField).val();
        if (idVal != '' && idVal != '00000000-0000-0000-0000-000000000000') {

            if (getParametersFunction)
                newUrl = getParametersFunction(idField, actionUrl);
            else
                newUrl = newUrl + '/' + idVal;

        }
    }
    LoadIframeDialog(newUrl,saveScript);

}
function LoadIframeDialog(actionUrl,saveScript) {

    if (actionUrl.indexOf('?') > -1)
    {
        actionUrl = actionUrl + "&iframe=1";
       
    }
    else
     {   
     
        actionUrl = actionUrl + "?iframe=1"

     }

    if (saveScript != null && saveScript != 'undefined' && saveScript!='')
       actionUrl=actionUrl+ "&saveScript="+saveScript;

    $("#IFrameDialog iframe").attr("src", actionUrl);
    $("#IFrameDialog iframe").css('width', 1024);
    $("#IFrameDialog iframe").css('height', 500);
   
    $('#IFrameDialog')
                .dialog
                (



                {
                    width: 'auto',
                    height: 'auto',
                    modal: true,
                    resizeStop : function (event, ui) {

                        $("#IFrameDialog iframe").css('width', Number($("#IFrameDialog").css('width').replace('px',''))-10);
                        $("#IFrameDialog iframe").css('height', Number($("#IFrameDialog").css('height').replace('px', '')) - 10);
                    
                    }

                }

                )
                .dialog("open");
}
function CloseIframeDialog() {

    $('#IFrameDialog').dialog('close');
    $("#IFrameDialog iframe").attr("src", "");
}
//==============================================================================
function getNowTimeString() {
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var hour = currentTime.getHours();
    var minut = currentTime.getMinutes();
    return month + "/" + day + "/" + year + " " + hour + ":" + minut;

}
