/*
     $Revision$
     $Id$

     File:        FcltJquery.js
     Description: Generieke functies die bij jquery wordt gebruikt.
     Parameters:
     Context:     Bestand wordt gelijktijdig geinclude met jquery.js in Shared/header.inc (Requires plugin)
     Note:

*/

// Let op: afterAction wordt alleen uitgevoerd als json.success gezet
function FcltCallbackAndThen(afterAction)
{
    return function (json, textStatus)
    {
        if (json.message) alert(json.message);
        if (json.warning) alert(json.warning);
        if (json.toaster) $.toast({ text: json.toaster, icon: "success", position : 'top-center'});
        json.message = null;
        json.warning = null;
        json.toaster = null;
        if (json.success)
        {
            if (afterAction) afterAction(json);
        }
    }
};

function FcltCallbackAndThenAlways(afterAction)
{
    return function (json, textStatus)
    {
        if (json.message) alert(json.message);
        if (json.warning) alert(json.warning);
        if (json.toaster) $.toast({ text: json.toaster, icon: "success", position : 'top-center'});
        json.message = null;
        json.warning = null;
        json.toaster = null;
        if (afterAction) afterAction(json);
    }
};

var FcltCallback = FcltCallbackAndThen(null);


var FcltCallbackRefresh = FcltCallbackAndThen(function ()
    {
      FcltMgr.reload();
    });

var FcltCallbackClose = FcltCallbackAndThen(function (json)
    {
      json.close = true;
      FcltMgr.closeDetail(window, json);
    });

var FcltCallbackDirtyLine = FcltCallbackAndThen(function (json)
    {
      // Bestaat json.key uit 1 of meerdere keys?
      if (json.key.indexOf(",") >= 0)
      {
        var key = json.key.split(",");
        for (var i = 0; i < key.length; i++)
        {
          $("#row" + key[i]).addClass('dirty');
        }
      }
      else
        $("#row" + json.key).addClass('dirty');
    });

// Roep met Ajax syncroon(!) een asp bestand aan en lever de JSON data op.
function FcltSyncgetJSON(url, data)
{
  var globalData;
  jQuery.ajax({ type: "GET",
                url: url,
                async: false,
                data: data,
                dataType: "json",
                success: function (data, textStatus) { globalData = data; globalData.textStatus = textStatus; }
              });
  if (globalData && globalData.warning)
    alert(globalData.warning);
  if (globalData && globalData.error)
    alert(globalData.error);
  if (globalData && globalData.toaster)
    $.toast({ text: globalData.toaster, icon: "success", position : 'top-center'});;
  return globalData;
}

// Handig, komt heel veel voor
function gen_cancel()
{
    FcltMgr.closeDetail(window, { cancel: true } );
}

// TODO Alleen als Logging aan?
$.ajaxSetup(
    {"error":function(XMLHttpRequest,textStatus, errorThrown)
        {
            if (XMLHttpRequest.responseText.match(/^FCLTFriendly:/)) // Friendly tekst uit shared/500_error.asp
            {
                alert(XMLHttpRequest.responseText.substring(13));
            }
            else if (XMLHttpRequest.responseText.match(/^FCLTExpired:/)) // Expired tekst uit common.inc
            {
                if (FcltMgr.getData('expired'))
                    FcltMgr.getData('expired')();
                else
                    alert(XMLHttpRequest.responseText.substring(12));
            }
            else
            {
                alert("JQuery Ajax Error: " + textStatus
                    + "\n" + XMLHttpRequest.status + ": " + XMLHttpRequest.statusText
                    + (errorThrown && errorThrown != XMLHttpRequest.statusText? "\n" + errorThrown:"")
                    + "\n\n" + this.type + " " + this.url
                    + "\n\n" + new Date().toLocaleString());
            }
        }
    });

// Experiment:
// Ctrl+W sluit onze eigen tabjes ipv browser tabjes?
// TODO: eigenlijk via FcltMgr._pageManager._closeTab(this)? Of juist niet?
// Je kunt nu ook je portal tabje sluiten. Is niet de bedoeling
//$(window).keydown(function(event)
//{
//     if (FcltMgr && event.ctrlKey && event.keyCode == 87) //  ctrl+W
//     {
//         FcltMgr.closeDetail();
//         event.preventDefault(); // Niet de *browser* tab
//     }
// });

// FIX FSN#22060 charset encoding probleem met $.getJSON en Ajax
// Mochten we ooit op utf8 overstappen dan kan dit er waarschijnlijk uit.
// http://forum.jquery.com/topic/serialize-problem-with-latin-1-iso-8859-1-and-solution
var myEncode = function (s)
{
    return unescape(encodeURIComponent(escape(s))).replace(/\+/g, "%2B");
}
jQuery.extend({
    param: function( a ) {
        var s = [];
        // If an array was passed in, assume that it is an array
        // of form elements
        if ( a.constructor == Array || a.jquery ){
            // Serialize the form elements
            jQuery.each( a, function(){
                s.push(myEncode(this.name) + "=" + myEncode(this.value));
            });
        }
        // Otherwise, assume that it's an object of key/value pairs
        else{
            // Serialize the key/values
            for ( var j in a )
                // If the value is an array then the key names need to be repeated
                if ( a[j] && a[j].constructor == Array )
                    jQuery.each( a[j], function(){
                        s.push(myEncode(j) + "=" + myEncode(this));
                    });
                else
                    s.push(myEncode(j) + "=" + myEncode(a[j]));
        }
        // Return the resulting serialization
        return s.join("&").replace(/ /g, "+");
    },

    serialize: function() {
        return this.param(this.serializeArray());
    }
});

// Voormalig jquery.autogrow-textarea.js
(function($) {

    /*
     * Auto-growing textareas; technique ripped from Facebook
     * JGL: modified shadow width ook goed doen als textarea (nog) invisible
     * JGL: modified with delayedUpdate
     */
    $.fn.autogrow = function(options) {

        this.filter('textarea').each(function() {

            var $this       = $(this),
                minHeight   = $this.height(),
                self        = this;

            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      Math.max(0,$(this).width() - parseInt($this.css('paddingLeft')) - parseInt($this.css('paddingRight'))),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);

            var delayedUpdate = function() {
                if (self.timerID) clearTimeout(self.timerID);
                self.timerID = setTimeout( function () { update.apply(self) }, 250);
            }

            var update = function() {

                if (self.timerID) clearTimeout(self.timerID);
                var times = function(string, number) {
                    for (var i = 0, r = ''; i < number; i ++)
                    {
                        r += string;
                    }
                    return r;
                };

                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n$/, '<br/>&nbsp;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/ {2,}/g, function(space) { return times('&nbsp;', space.length -1) + ' ' });

                shadow.html(val);
                shadow.css("width", Math.max(0,$(this).width() - parseInt($this.css('paddingLeft')) - parseInt($this.css('paddingRight'))));
                var oldheight = parseInt($(this).css('height'));
                var newheight = Math.max(shadow.height() + 20, minHeight);
                if (oldheight != newheight)
                {
                    $(this).css('height', newheight);
                    FcltMgr.resized(window);
                }

                /* Experimentele max-lengte indicatie onder label
                var len = this.value.length;
                var maxlen = parseInt(this.getAttribute("maxlength"), 10)||4000;
                var $lbl = $("label[for="+ this.name +"]");
                $lbl.find("div").remove();
                if ($lbl.length && len > maxlen * (90/100))
                {
                    if (len > maxlen)
                        $lbl.append("<div style='color:red;font-size:0.9em;'>Te lang.<br>Maximum is {0}, huidig is {1}</div>".format(maxlen, len));
                    else
                        $lbl.append("<div style='color:blue;font-size:0.9em'>{1}/{0} karakters</div>".format(maxlen, len));
                }
                */
            }

            $(this).change(delayedUpdate).keyup(delayedUpdate).keydown(delayedUpdate).blur(update);

            update.apply(this);

        });

        return this;

    }

})(jQuery);

jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(select).find('option').each(function() {
      options.push(this);
    });
    $(select).data('options', options);
    $(textbox).bind('change keyup', function() {
      var options = $(select).empty().scrollTop(0).data('options');
      var search = $.trim($(this).val()).toUpperCase();

      $.each(options, function(i) {
        var option = options[i];
        if($(option).text().toUpperCase().indexOf(search) > -1) {
          $(select).append(option);
        }
      });
      if (selectSingleMatch === true &&
          $(select).children().length === 1) {
        $(select).children().get(0).selected = true;
        $(select).children().trigger("change");
      }
    });
  });
};

// Add a clickable  sign after a select element that when clicked
// toggles the multiple attribute on the select box
(function($){

  $( document ).on('click', '.multi_select_toggle', function(e){
      e.stopPropagation();
      var sel_id = $(this).attr("fcltfor");
      var selector = $('select#' + sel_id);
      if (selector.length && selector[0].className.match(/^ui-/))
        return; // Afblijven van jQuery calendar jaar listboxje
      var old = selector.attr('multiple');
      selector.attr('multiple', !old);
      selector.attr('size', old?1:Math.min(selector.find("option").length, 8));
      $(e.target).html(old?'&raquo;':'&laquo;');
      FcltMgr.resized();
  })

  $.fn.extend({
    multiSelectToggle : function(options){
                            //Settings list and the default values
                            var defaults = {
                                label: '&raquo;'
                            };

                            var options = $.extend(defaults, options);
                            return this.each(function() {
                                    var lbl = $("<span fcltfor='" + this.id + "' class='multi_select_toggle' />").html(options.label);
                                    var div = $('<div />').addClass('multitoggle'); // deze div schuiven we 20px naar links
                                    $(this).wrap(div);
                                    $(this).before(lbl);
                                });
                          }
  });
  $(function () {
    $('select[fcltmulti=1]').multiSelectToggle();
  });

})(jQuery);

if (window.fcltfilters)
{
    $(function ()
        {
             iface.stringToForm(window.fcltfilters, $('form[name=u2]')) ;
        });
}
