﻿/// <reference path="jquery-1.3.2.js"/>

(function($) {
    jQuery.fn.extend({
        initDataForm: function(options) {
            var defaults = {};
            options = $.extend(defaults, options);

            return this.each(function() {
                var $dataform = $(this);
                $('<div class="olFilm"></div>').appendTo($dataform.hasClass('.addoverlay') ? $dataform : $('div.addoverlay', $dataform));
                //Something like this should be inside the overlay div: <img src="/Overlay/img/ajax-loader_indicator_big_redmond.gif"/>
                $('.selectforupdate', $dataform).focus(function() {
                    recordHandler.fieldGotFocus(this);
                })
            .blur(function() {
                recordHandler.fieldLostFocus(this);
            });
            $('.formsubmit',$dataform).click(function() {
				recordHandler.fieldGotFocus(this); //Only allows postback buttons that are "inside" the record to postback
				submitCurrentForm(this);
				return false;
			});
				$('input.onload', $dataform).each(function() {
                    try {
                        var options = JSON.parse($(this).val());
                        if (options.eval) {
                            if (options.javascript) {
                                eval(options.javascript);
                            }
                        }
                        else {
                            serverConnector.loadHtml(options, options.sendcontext);
                        }
                    }
                    catch (e) {
                        $.log(e);
                    }
                });
                //$("input.datefield", $dataform).datepicker({ dateFormat: 'dd.mm.yy' });
                $("input.integerpositiv", $dataform).keyup(function(event) {
                    if (this.value !== this.value.replace(/[^0-9., ]/g, ''))
                        this.value = this.value.replace(/[^0-9., ]/g, ''); //leaving only digits example: this.value.replace(/\D/g,'');
                });
                $("input.integerpositiv", $dataform).focus(function(event) {
                    $(this).select();
                });
                $('input.attach', $dataform).each(function() {
                    var options = {};
                    try {
                        options = JSON.parse($(this).val());
                        if (typeof options.buffer == "undefined")
                            return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    var hashValue = attachedHash.keyExists(options.buffer) ? attachedHash.getItem(options.buffer) : [];
                    hashValue.push(options);
                    attachedHash.setItem(options.buffer, hashValue);
                });
                $('input.autosuggest', $dataform).each(function() {
                    var options = {};
                    try {
                        options = $.extend({ classname: "CwWPGenerator",
                            methodname: "execute",
                            param: "",
                            citkeylookup: false,
						    selectfirst : true,
                            width: 500,
                            scroll: false,
                            scrollheight: 350,
                            delay: 200,
                            webpartid: '',
							field_1: '',
							field_2: '',
							field_3: '',
							field_4: '',
							cachelength: 10,
							limit: 100
                        }, JSON.parse($(this).val()));
                        //if (typeof options.webpartid == "undefined")
                        //   return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    var context = recordHandler.serialized();
                    var contextproviders = '';
                    var recid = '';
                    if (context != null && context['contextproviders'] != null) {
                        contextproviders = context['contextproviders'];
                    }
                    if (context != null && context['recid'] != null) {
                        recid = context['recid'];
                    }
                    var extraParams = 
					{
                        contextproviders: function() {
                            if (recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context['contextproviders'] != null) {
                                    return context['contextproviders'];
                                }
                            }
                            return '';
                        },
                        recid: function() {
                            if (recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context['recid'] != null) {
                                    return context['recid'];
                                }
                            }
                            return '';
                        },
                        tableid: function() {
                            if (recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context['tableid'] != null) {
                                    return context['tableid'];
                                }
                            }
                            return '';
                        },
						field_1: function() {
                            if (options.field_1 && recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context[options.field_1] != null) {
                                    return context[options.field_1];
                                }
                            }
                            return '';
                        },
						field_2: function() {
                            if (options.field_2 && recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context[options.field_2] != null) {
                                    return context[options.field_2];
                                }
                            }
                            return '';
                        },
						field_3: function() {
                            if (options.field_3 && recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context[options.field_3] != null) {
                                    return context[options.field_3];
                                }
                            }
                            return '';
                        },
						field_4: function() {
                            if (options.field_4 && recordHandler) {
                                var context = recordHandler.serialized();
                                if (context != null && context[options.field_4] != null) {
                                    return context[options.field_4];
                                }
                            }
                            return '';
                        }
                    };
                    $(options.selector).autocomplete("/ajaxpages/AjaxGet.aspx?classname=" + options.classname +
                                                        "&methodname=" + options.methodname +
                                                        (options.webpartid ? "&webpartid=" + options.webpartid : '') +
                                                        "&param=" + options.param,
                                                        { width: options.width,
                                                            extraParams: extraParams,
                                                            scroll: options.scroll,
                                                            scrollHeight: options.scrollheight,
															cacheLength: options.cachelength,
															max: options.limit,
                                                            citKeyLookup: options.citkeylookup,
                                                            delay: options.delay
                                                        });
                });

                /*
                // Shallow copy
                var newObject = jQuery.extend({}, oldObject);
                // Deep copy
                var newObject = jQuery.extend(true, {}, oldObject);
                http://stackoverflow.com/questions/122102/what-is-the-most-efficent-way-to-clone-a-javascript-object
                */
                $('.contextprovider[id]', $dataform).each(function() {
                    contextProviders.push(this.id);
                });
                /*$('input.fieldlookup', $dataform).each(function() {
                var owner = $(this);
                owner.after('<span class="icon lookup"/>');
                var icon = owner.next();
                icon.bind('click', function() {
                owner.addClass('clicked');
                });
                });*/
                $('input.clicked,input.fieldlookup,input.formsubmit', $dataform).each(function() {
                    var options = {};
                    var $this = $(this);
                    try {
                        options = JSON.parse($(this).val());
                        if (typeof options.selector == "undefined")
                            return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    if ($this.hasClass('fieldlookup')) {
                        var newSelector = options.selector.substring(1, options.selector.length) + 'lookup';
                        $(options.selector, $dataform).each(function() {
                            //if (this.disabled)
                            //   return;

                            var owner = $(this);
                            owner.after('<span class="icon lookup ' + newSelector + '"/>');
                        });
                        options.selector = '.' + newSelector;
                    }
                    $(options.selector, $dataform).click(function() {
                        var element = this;
						recordHandler.fieldGotFocus(element)
                        var localOptions = { confirmboxshow: false, confirmboxtitle: 'Confirm action', confirmboxtext: 'Confirm action', returnvalue: false };
                        $.extend(localOptions, options);

                        function doAction() {
                            if($this.hasClass('formsubmit')){
                                return submitCurrentForm(element);
                            } 
                            serverConnector.post(localOptions, true);
                        }

                        if (options.confirmboxshow) {
                            function dialogCancel() {
                                $(this).dialog("close");
                                $(this).dialog("destroy");
                            }
                            function dialogOk() {
                                $(this).dialog("close");
                                $(this).dialog("destroy");
                                doAction();
                            }
                            $('<div id="ConfirmDialog" title="' + localOptions.confirmboxtitle + '" style="display: none;">' + localOptions.confirmboxtext + '</div>')
                                .dialog({ modal: true, buttons: { "Cancel": dialogCancel, "Ok": dialogOk} });
                            return localOptions.returnvalue;
                        }
                        doAction();
                        return localOptions.returnvalue;
                    });
                });
				/*
				$('input.formsubmit', $dataform).each(function() {
                    var options = {};
                    var $this = $(this);
                    try {
                        options = JSON.parse($(this).val());
                        if (typeof options.selector == "undefined")
                            return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    $(options.selector, $dataform).click(function() {
                        var element = this;
						recordHandler.fieldGotFocus(this)
                        var localOptions = { confirmboxshow: false, confirmboxtitle: 'Confirm action', confirmboxtext: 'Confirm action', returnvalue: true };
                        $.extend(localOptions, options);

                        if (localOptions.confirmboxshow) {
                            function dialogCancel() {
                                $(this).dialog("close");
                                $(this).dialog("destroy");
                            }
                            function dialogOk() {
                                $(this).dialog("close");
                                $(this).dialog("destroy");
                                submitCurrentForm(element);
                            }
                            $('<div id="ConfirmDialog" title="' + localOptions.confirmboxtitle + '" style="display: none;">' + localOptions.confirmboxtext + '</div>')
                                .dialog({ modal: true, buttons: { "Cancel": dialogCancel, "Ok": dialogOk} });
                            return localOptions.returnvalue;
                        }
                        submitCurrentForm(element);
                        return localOptions.returnvalue;
                    });
                });*/
                $('input.onenterkey', $dataform).each(function() {
                    var options = {};
                    try {
                        options = JSON.parse($(this).val());
                        if (typeof options.selector == "undefined")
                            return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    $(options.selector, $dataform).bind('keydown', 'return', function(event) {
                        var localOptions = {}; // = {confirmboxshow:false,confirmboxtitle:'Confirm action',confirmboxtext:'Confirm action'};         
                        $.extend(localOptions, options);

                        serverConnector.post(localOptions, true);
                        return false;
                    });
                });
                $('input.onselectionchange', $dataform).each(function() {
                    var options = {};
                    try {
                        options = JSON.parse($(this).val());
                        if (typeof options.selector == "undefined")
                            return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    $(options.selector, $dataform).change(function() {
                        var localOptions = {};
                        $.extend(localOptions, options);

                        serverConnector.post(localOptions, true);
                        return false;
                    });
                });
                /*if (!debug)
                $(this).remove();*/
                /*$('input.datefield').blur(function(){
                checkDate(this);
                //alert("Invalid date format");//TODO Labels
                });*/
                $('input.fieldlostfocus', $dataform).each(function() {
                    var options = { onmodifiedonly: true };
                    try {
                        options = $.extend(options, JSON.parse($(this).val()));
                        if (typeof options.selector == "undefined")
                            return;

                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    var timeouthandle;
                    if (options.onmodifiedonly && $(options.selector).length == 1 && jQuery.nodeName($(options.selector)[0], 'input')) {
                        $(options.selector, $dataform).focus(function() {
                            /*$.log('focus',timeouthandle);
                            if(timeouthandle){
                            clearTimeout(timeouthandle);
                            return;
                            }*/
                            origHash.setItem(this.id, this.value);
                        });
                    }
                    $(options.selector, $dataform).blur(function() {
                        var localOptions = options;
                        if (localOptions.onmodifiedonly && this.id && jQuery.nodeName($('#' + this.id)[0], 'input')) {
                            if (origHash.keyExists(this.id) && origHash.getItem(this.id) == this.value)
                                return;
                            else
                                origHash.setItem(this.id, this.value);
                        }
                        function post() {
                            serverConnector.post(localOptions, true)

                        }
                        timeouthandle = setTimeout(post, 250);
                        //$.log('blur',timeouthandle);
                        return;
                    });
                    if (!debug)
                        $(this).remove();
                });
                $('a.ajaxsortlink', $dataform).click(function() {
                    var options = {
                        url: this.href,
                        loadinto: $dataform.parents('div:first')[0].id ? '#' + $dataform.parents('div:first')[0].id : '',
                        cursor: 'wait',
                        pureurl: true
                    };
                    var sendContext = false;
                    if (options.url.indexOf('webpartid', 0) == -1) {
                        var webpartdiv = $('.webpartid', $dataform);
                        if (!webpartdiv.length)
                            return false;

                        options.pureurl = false;
                        options.webpartid = webpartdiv[0].id;
                        options.url = options.url.replace(/AjaxUpdate/i, "AjaxGet");
                        sendContext = true;
                    }
                    if (options.url && options.loadinto) {
                        serverConnector.loadHtml(options, sendContext);
                    }
                    return false;
                });
                $('input.clientclicked', $dataform).each(function() {
                    var options = { override: false,sendcontext:false,command:'' };
                    try {
                        options = $.extend(options, JSON.parse($(this).val()));
                        if (typeof options.selector == "undefined")
                            return;
                    }
                    catch (e) {
                        $.log(e);
                        return; //Return is same as continue, return false is the same as break
                    }
                    $(options.selector, $dataform).click(function() {
                        var element = this;
						recordHandler.fieldGotFocus(element);
						var command = options.command.split(' ');
                        if (!command.length)
                            return true;

                        switch (command[0]) {
							case 'reloadpage':
                                window.location = window.location;
                                break;
							case 'toggle':
                                $(options.applyto).toggle(command.length > 1 ? command[1] : 0);
                                break;
                            case 'show':
                                $(options.applyto).show(command.length > 1 ? command[1] : 0);
                                break;
                            case 'hide':
                                var param1 = command.length > 1 ? command[1] : 0;
                                $(options.applyto).hide(param1);
                                break;
                            case 'get':
                                try {
                                    serverConnector.loadHtml(options,options.sendcontext);
                                }
                                catch (e) {
                                    $.log(e);
                                }
                                break;
                            case 'href':
                                window.location.href = command[1];
                                break;
                        }
                        return !options.override;
                    });
                    if (!debug)
                        $(this).remove();
                });
                $('.save', $dataform).click(function() {
                    return saveRecord();
                    /*if($('.saveline', recordHandler.currentRecord).length)
                    $('.saveline', recordHandler.currentRecord).click();
                    else
                    recordHandler.save(false);
                    return true;*/
                });
                $('table.datagrid tbody tr:odd', $dataform).addClass('odd');
                $('table.datagrid tbody tr:even', $dataform).addClass('even');
                $('tr.datarecord', $dataform).click(function() {
                    if (recordHandler.currentRecord == this)
                        return true;

                    if (this.id) {
                        recordHandler.fieldGotFocus(this);
                        $("#" + this.id + " select,input:first").focus().select();
                    }

                    return true;
                });
                $('table.datagrid input.lastinp', $dataform).bind('keydown', 'tab', function(event) {
                    var row = $(this).parents("tr:first");
                    if ($(this).val() && !$(this).hasClass('skipnavigation') && row.length && row.hasClass('newrecord')) {
                        if (($(this).hasClass('integerpositiv') || $(this).hasClass('integer') || $(this).hasClass('integernegative')) && !parseInt($(this).val()))
                            return true;
                        $('.saveline', row).click();
                    }
                    return true;
                });
                $('table.datagrid input.field', $dataform).bind('keyup', 'down', function(event) {
                    var row = $(this).parents("tr:first");
                    if (event.keyCode == KEY.DOWN && !$(this).hasClass('skipnavigation') && row.length && row.hasClass('newrecord') && $(this).val()) {
                        $('.saveline', row).click();
                        return false;
                    }
                });

                $('table.datagrid input.field', $dataform).bind('keydown', function(event) {
                    var cell = $(this).parent("td");
                    var row = $(cell).parent("tr");
                    switch (event.keyCode) {
                        case KEY.UP:
                            var prevRow = $(row).prev('tr');
                            if (prevRow.length > 0 && row[0].sectionRowIndex > prevRow[0].sectionRowIndex) {
                                var prevCell = $(prevRow).children()[cell[0].cellIndex];
                                var inp = $(prevCell).find('input');
                            }
                            break;
                        case KEY.DOWN:
                            var nextRow = $(row).next('tr.datarecord');
                            if (nextRow.length > 0 && row[0].sectionRowIndex < nextRow[0].sectionRowIndex) {
                                var nextCell = $(nextRow).children()[cell[0].cellIndex];
                                var inp = $(nextCell).find('input');
                            }
                            break;
                    }
                    /*function selectText(){
                    $(inp).select();
                    } */
                    if (inp && inp.length) {
                        $(this).blur();
                        $(inp).focus();
                        $(inp).select();
                        //setTimeout(selectText,25);
                    }
                    /*else if(event.keyCode == KEY.DOWN && !$(this).hasClass('skipnavigation') && row.length && row.hasClass('newrecord') && $(this).val()){
                    $('.saveline',row).click();
                    return false;
                    }*/
                });
                $('.firstfocus:first', $dataform).focus().select();
                $('.forcefocus:first', $dataform).focus().select();
            });
        },
        initProdMenu: function() {
            return $("a.submenu", this).click(function() {
                $this = $(this);
                if ($this.hasClass('follow'))
                    return true;
                if ($(this).next('ul.visible').length > 0) {
                    $(this).next('ul.visible').removeClass('visible').slideUp(100);
                }
                else {                              //TODO Parent/Master class:first instead
                    if ($(this).parent('li').parent('#prodnav').length > 0) {
                        $('ul.visible', $this).removeClass('visible').slideUp(100);
                    }
                    $(this).next('ul').addClass('visible').slideDown(100);
                }
                return false;
            });
        },

        cwload: function(url, params, callback, cacheresult) {
            var loadFromCache = function(res, status) {
                // If successful, inject the HTML into all the matched elements
                if (status == "success" || status == "notmodified") {
                    $('*', self).unautocomplete();
                    $('*', self).unbind();
                    $('*', self).removeData('events');
                    self.empty();
                    self.html(res);
                    if (callback)
                        callback(res, status);
                }
            }
            if (cacheresult && pageCache.keyExists(url + JSON.stringify(params))) {
                var self = this;
                loadFromCache(pageCache.getItem(url + JSON.stringify(params)), 'success');
            }
            else {
                this.load(url + (!cacheresult && !params ? "&timestamp=" + +new Date() : ''), params, callback);
            }
            return this;
        }
    })
})(jQuery);
jQuery.extend({
    cwPost: function(async, url, data, callback, type) {
        ///	<summary>
        ///		Loads a remote page using an HTTP POST request.
        ///	</summary>
        ///	<param name="url" type="String">The URL of the HTML page to load.</param>
        ///	<param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
        ///	<param name="callback" optional="true" type="Function">The function called when the AJAX request is complete.  It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param>
        ///	<param name="type" optional="true" type="String">Type of data to be returned to callback function.  Valid valiues are xml, html, script, json, text, _default.</param>
        ///	<returns type="XMLHttpRequest" />

        if (jQuery.isFunction(data)) {
            callback = data;
            data = {};
        }

        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            dataType: type,
            async: async
        });
    },
    nodeName: function(elem, name) {
        if (elem === undefined) {
            return false;
        }
        return elem.nodeName && (elem.nodeName.toUpperCase() == name.toUpperCase() || elem.nodeName.toLowerCase() == name.toLowerCase());
    }
});
jQuery.log = function(m0, m1, m2, m3, m4, m6, m7, m8, m9) {
   if (!debug)
      return;
   if (window.console) {
      try {
         console.debug(m0, typeof m1 == "undefined" ? '' : m1,
                          typeof m2 == "undefined" ? '' : m2,
                          typeof m3 == "undefined" ? '' : m3,
                          typeof m4 == "undefined" ? '' : m4,
                          typeof m5 == "undefined" ? '' : m5,
                          typeof m6 == "undefined" ? '' : m6,
                          typeof m7 == "undefined" ? '' : m7,
                          typeof m8 == "undefined" ? '' : m8,
                          typeof m9 == "undefined" ? '' : m9);
      } catch (e) { console.log('Error when writing to log'); }
   } else if (alerts) {
      alert(m0);
   }
};

