var IE = /*@cc_on!@*/false;

var siteprefix = 'http://ernstdirksenfotografie.nl';

/**
 * Display JavaScript errors */
window.onerror=function(desc,page,line,chr){
  /*alert("JavaScript error occurred! \n"+"\nError description: \t"+desc+"\nPage address: \t"+page+"\nLine number: \t"+line);*/
  if(IE){ return true; }
}
/**/

function showMessage(message, stay){
  jQuery.showMessage(message, stay);
}

  /**#####
  * JQUERY
  ######*/
  jQuery(function($){
    $(document).ready(function(){

      $('#update_message').addClass('js_update_message').hide().live('keydown', function(e){
        if(e.which == 27/* = escapekey*/){
          $('#update_message').stop(true, true).fadeOut(100);
          return false;
        }
      });
      $.showMessage = function(message, stay){
        if(stay == null) stay = false;
        
        if(message != null){
          $('#update_message').html(message).find('[rel=closeMessage]').click(function(){
            $('#update_message').stop(true, true).fadeOut(100);
            return false;
          });
        }
        
        $('#update_message').stop(true, true).hide().fadeIn(500);
        
        if(stay == false){
          
          $('#update_message').fadeIn(500);
          $('#update_message').delay(5000).fadeOut(500);
          $('#update_message').bind({
            click: function(){
              $('#update_message').stop(true, true).fadeOut(100);
            },
            mouseenter: function(){
              $(this).stop(true, true).fadeIn(500);
            },
            mouseleave: function(){
              $(this).delay(1000).fadeOut(500);
            }
          });
          
        }else{
          var focus;
          $('#update_message').unbind();
          
          focus = $('#update_message').find('form :input:eq(0)');
          if(focus.size() > 0){
            focus.focus().select();
          }else{
            focus = $('#update_message').find('form input[type=submit]');
            if(focus.size() > 0){
              focus.focus().select();
            }
          }


        }
        
      }
      
      // delete module on page
      $('[rel=delete_position_item]').click(function(){
        showMessage(
          '<form action="'+$(this).attr('href')+'" method="POST">'+
          ' <div class="notice">'+
          '  <label for="delete_module_item_options">Module Verwijderen</label><br />'+
          '  <select id="delete_module_item_options" name="delete_module_item_options">'+
          '   <option value="one">Alleen deze module</option>'+
          '   <option value="multiple">Deze module ook verwijderen van andere pagina\'s</option>'+
          '   <option value="all">Alle soortgelijke modules van alle pagina\'s verwijderen</option>'+
          '  </select>'+
          '  <input type="submit" value="verwijderen">'+
          '  <a href="javascript:void(0)" rel="closeMessage">Annuleren</a>'+
          ' </div>'+
          '</form>',
        true);
        return false;
      });

      // // delete something on page
      // $('[rel=delete_item]').click(function(){
        // showMessage('<div class="notice">Verwijderen?<br /><a href="'+$(this).attr('href')+'">Ja</a> - <a href="javascript:void(0)" rel="closeMessage">Annuleren</a></div>', true);
        // return false;
      // });

      $(".iframe").colorbox({
        initialWidth:'100',
        width:'440',
        maxWidth:'99%',
        initialHeight:'100',
        maxHeight:'90%',
        iframe:false,
        arrowKey:false,
        overlayClose:false
      });
     
      $(".iframe_focus").colorbox({
        initialWidth:'100',
        width:'440',
        maxWidth:'99%',
        initialHeight:'100',
        maxHeight:'90%',
        iframe:false,
        arrowKey:false,
        overlayClose:false,
        onComplete:function(){
          document.forms[0].elements[0].focus();
        }
      });

      /* nog even fixen voor IE:
      $('form[action*="action="] input[type=submit]').live('click', function(){
        $(this).attr('disabled', true);
        $(this).parents('form[action*="action="]').submit();
        return false;
      });
      */
      
      /**
      * elRTE
      */
      elRTE.prototype.options.panels.txTinyPanel = [
        'bold', 'italic', 'underline', 'forecolor', 'justifyleft', 'justifyright',
        'justifycenter', 'justifyfull', 'formatblock', 'insertorderedlist', 'insertunorderedlist',
        'link', 'image', 'flash'
      ];
      elRTE.prototype.options.toolbars.txTinyToolbar = [
        'save', 'txTinyPanel', 'tables'
      ];

      $.initRTE = function(toolbar){
        $('textarea.editor[rel!=initialised]').attr('rel', 'initialised').elrte({
          height:   300,
          toolbar: (toolbar != null ? toolbar : 'maxi'),
          fmAllow:  true,
          fmOpen:   function(callback){
            $('<div id="myelfinder" />').elfinder({
              url : siteprefix+'/site/plugins/elfinder/connectors/php/connector.php',
              dialog : { width : 900, modal : true, title : 'Files' }, // open in dialog window
              closeOnEditorCallback : true, // close after file select
              editorCallback : callback     // pass callback to file manager
            });
          },
          styleWithCss: false,
          cssfiles: new Array(siteprefix+'/site/themes/ernst/includes/css/style.css'),
          lang: 'nl'
        });
      }
      
      // function stuck(name){
        // if(name == null || name == ''){
          // name = prompt('eerst je naam');
        // }else{
          // alert('hoi '+name);
        // }
        // stuck(name);
      // }
      // stuck();
      
      /**
      * jeditable 
      */
      $.initEditable = function(){
        
        $.editable.addInputType('elrte', {
          element:function(settings, original){
            var textarea = $('<textarea>');
            if (settings.rows) {
                textarea.attr('rows', settings.rows);
            } else {
                textarea.height(settings.height);
            }
            if (settings.cols) {
                textarea.attr('cols', settings.cols);
            } else {
                textarea.width(settings.width);
            }
            $(this).append(textarea);
            return(textarea);
          },
          plugin:function(settings, original){
            $('textarea', this).elrte({
              toolbar:  'maxi',
              height:   settings.height+50,
              fmAllow:  true,
              fmOpen:   function(callback){
                $('<div id="myelfinder" />').elfinder({
                  url : siteprefix+'/site/plugins/elfinder/connectors/php/connector.php',
                  dialog : { width : 900, modal : true, title : 'Files' }, // open in dialog window
                  closeOnEditorCallback : true, // close after file select
                  editorCallback : callback     // pass callback to file manager
                });
              },
              styleWithCss: false,
              cssfiles: new Array(siteprefix+'/site/themes/ernst/includes/css/style.css')
            });
          }
        });
        
        $(".editable_text").editable(function(value, settings){
          $.ajax({
            type: "POST",
            url: $(this).attr('action')+'&item_id='+str_replace('item', '', $(this).attr('id')),
            data: 'key='+($(this).attr('name'))+'&value='+encodeURIComponent(value),
            success: function(msg){
              //alert(msg);
              showMessage('<div class="success">Succesvol opgeslagen</div>');
            }
          });
          return value;
        }, {
          tooltip   : 'Dubbelklik om te wijzigen',
          indicator : siteprefix+'/site/display/files/images/colorbox/loading.gif" alt="Loading" />',
          submit     : '',
          cancel     : ''
        });
        $(".editable_textarea").editable(function(value, settings){
          $.ajax({
            type: "POST",
            url: $(this).attr('action')+'&item_id='+str_replace('item', '', $(this).attr('id')),
            data: {
              key: $(this).attr('name'),
              value: value
            },
            success: function(msg){
              showMessage('<div class="success">Bericht opgeslagen</div>');
            }
          });
          return value;
        }, { 
          type:       'elrte',
          tooltip:    'Dubbelklik om te wijzigen',
          indicator:  siteprefix+'/site/display/files/images/colorbox/loading.gif" alt="Loading" />',
          onblur:     'ignore'
        });
      }
      $.initEditable();
      
    });
  });
  /**#######
  * MOOTOOLS
  ########*/
  $(function(){
    
  })

function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/urlencode    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str+'').toString();
        // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function getUrlVars(){
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++){
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

function str_replace(search, replace, subject, count) {
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
            }
    }
    return sa ? s : s[0];
}

