//prevent errors in browsers that do not support console.
if (typeof console == "undefined"){
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
  var console = {};
  for (var i = 0; i < names.length; ++i) {
    console[names[i]] = function(){};
  }
}


var wp = {
  settings: {
    signinUrl: null
  },

  init: function(params){
    this.settings = $.extend(this.settings, params);
    console.log('init', this.settings);
    this.registerEventListeners();
  },
  
  registerEventListeners: function(){
    $('.fbConnectBtn').click(
     function(){
         try{
            FB.Connect.requireSession(
             wp.connected
            );
          }
          catch(e){ 
            alert('Fehler! Leider konnten wir dich nicht mit deinem Facebook Account verbinden');
          }
          return false;
      } 
    ); 
  },
  
  connected: function(){
    FB.Connect.showPermissionDialog(
      "email", 
      function(perms) {
        document.location.href= wp.settings.signinUrl;
      });
  },
  
  

  /**
   * make an element editable inline
   * @param {Object} elem
   */
  makeEditable: function(elem, options){
    //console.log('make editable', elem);
    
    //if we focus on the input/textarea its also a click, so we have to unbind click here
    $(elem).unbind('click');
    
    
    var currentValue = $.trim($(elem).text());
    var type = $(elem).attr('data-type');
    var field = $(elem).attr('data-field');
    var editable = '';
    var settings = $.extend({
      updateUrl: '/wedding/editInline'
    }, options);



    switch(type){
      case "textarea":
        editable = $('<div class="editArea"><textarea class="newValue">'+currentValue +'</textarea><a class="editDone" href="#" onclick="return false;">ok</a></div>');
      break;
      case "input":
      case "url":
        editable = $('<div class="editArea"><input class="newValue" value="'+currentValue +'" /><a class="editDone" href="#" onclick="return false;">ok</a></div>');
      break;
      case "date":
        editable = $('<div class="editArea"><input class="newValue" value="'+currentValue +'" /><a class="editDone" href="#" onclick="return false;">ok</a></div>');
      break;
      case 'file':
      case 'link': //link = point to edit form
        document.location.href= $('#editAllBtn').attr('href')+'#'+field;
        return false;
      break;
    }

    $(elem).html(editable);

    $('.editDone', elem).click(
      function(){
        $(this).unbind('click');
        var parentField =  $(this).parents('.editInline')[0];
        var newValue = $(':input', parentField).val();

        $.ajax({
          url: settings.updateUrl,
          type: 'POST',
          dataType: 'json',
          data: {
            value: newValue,
            field: field,
            type: type
          },
          success: function(data){
            $('.editArea', parentField).remove();
            //console.log('setting ', elem, 'to', data.value);
            if(type == 'url'){
              $(elem).html('<a href="'+data.value+'">'+data.value+'</a>');
            }
            else{
              $(elem).text(data.value);
            }
           
          },
          complete: function(){
            //re-init the editable
            //wp.makeEditable(elem);
           $(elem).click(function(){
             wp.makeEditable(this);
           });
           
          },
          beforeSend: function(){
            //console.log('add loading animation');
            return true;
          }
        });
        return false;
      });
  },
  
  
  pickFbUser: function(elem, saveUrl, callback){
    $('#dialogueContent').html('<div class="loader">lade Freunde...</div>');
    $('#dialogue').dialog('open');
    
    FB.api(
      {
         method: 'friends.get'
      },
      function(result) {
        FB.getLoginStatus(function(response) {
          if (response.session) {
            // logged in and connected user, someone you know
            var myUid = response.session.uid;
            var markup = '<fb:profile-pic size="square" uid="'+myUid+ '" facebook-logo="false" linked="false" class="fbUserPic"></fb:profile-pic>';
            var num_friends = result ? result.length : 0;
            if (num_friends > 0) {
              for (var i=0; i<num_friends; i++) {
                markup +=  '<fb:profile-pic size="square" uid="'+ result[i]+ '" facebook-logo="false" linked="false" class="fbUserPic"></fb:profile-pic>';
              }
            }
            $('#dialogueContent').html(markup);
            
            FB.XFBML.parse($('#dialogueContent')[0]);
    
            $('.fbUserPic').click(function(){
              
              //standard behaviour for inline edit
              if(typeof callback === 'undefined'){
                wp.saveFbUser(
                  $(elem).attr('data-field'), 
                  $(this).attr('uid'),
                  saveUrl,
                  $(elem).parents('p').find('.fbUserContainer')
                );
              }
              
              else{//behaviour for form
                callback(
                  $(elem).attr('data-field'), 
                  $(this).attr('uid'),
                  $(elem).parents('p').find('.fbUserContainer')
                );
              }
            
              
              $('#dialogue').dialog('close');
              return false;
            });
            
          } 
          else {
            // no user session available, someone you dont know
          }
        });
        //end get login status
      
    });
  },
  
  
  /**
   * saves a facebook userId to a field for inline edit
   * @param {Object} fieldName
   * @param {Object} uid
   * @param {Object} saveUrl
   * @param {Object} container
   */
  saveFbUser: function(fieldName, uid, saveUrl, container){
    var editable = $(container).parents('p');
    
    
    //set html
    $(container).html(
        '<fb:profile-pic size="square" uid="'+uid+'" facebook-logo="false" linked="false" class="fbUserPic"></fb:profile-pic>'
    );
    
    //also set the name
    $(editable).find('.editInline').html(
      '<fb:name uid="'+uid+'" linked="false"></fb:name>'
    );
    
    try{
      FB.XFBML.parse( $(editable)[0]);
    }
    catch(e){
      //console.warn(e);
    }
    
    $.ajax({
      url: saveUrl,
      dataType: 'json',
      data: {
        uid: uid,
        fieldName: fieldName
      },
      success:function(data){
        //console.log('ok', data);
      },
      beforeSend:function(){},
      error:function(){}
    });
  },
  
  
  
  
  /**
   * generic error func for ajax requests
   */
  onError: function(){
    alert('Leider ist ein Fehler aufgetreten');
  },
  
  /**
   * 
   * @param {String} url
   * @param {String} title
   * @param {Object} options
   * @param {Boolean} centered
   * @return the window instance
   */
  popup:function (url, title, options, centered) {
    var title = title || 'Popup';
    var settings = {
       width: 400,
       height: 400,
       top: null,
       left: null,
       resizable: 'no',
       scrollbars: 'no',
       toolbar : 'no',
       menubar: 'no',
       directories: 'no',
       status: 'yes'
    };
    
    //merge config
    if(options){
     settings = jQuery.extend(settings, options);
    }
    
    //centers the window if top/left are null or smaller than zero
    if(!settings.top > -1 && settings.left > -1){
     settings.top = screen.height/2 - settings.height;
     settings.left = screen.width/2 - settings.width/2;
    }
    
    //create popup
    var params = [];
    var paramStr = '';
    var propCount = 0;
    jQuery.each(settings, function(prop){
     propCount++;
     params.push(prop+'='+this);
    });
    //console.info(params);
    
    paramStr = params.join(',');
    //console.log(paramStr);
    var win = window.open(url, title, paramStr);
    win.focus();
    return win;
  },
  
  /**
   * signs a user out also out of Facebook if connected
   * @param {String} redirectUrl
   */
  signout: function(redirectUrl){
    try{
      FB.getLoginStatus(function(response) {
        if (response.session) {
          // logged in and connected user, someone you know
          FB.logout(function(response) {
            // user is now logged out
            document.location.href = redirectUrl;
          });

        }
        else {
          // no user session available, someone you dont know
           document.location.href = redirectUrl;
        }
      });
    }
    catch(e){
      console.warn('no fb connect!');
      document.location.href = redirectUrl;
    }
    
  }
};


/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
  $.datepicker.regional['de'] = {
    closeText: 'schließen',
    prevText: '&#x3c;zurück',
    nextText: 'Vor&#x3e;',
    currentText: 'heute',
    monthNames: ['Januar','Februar','März','April','Mai','Juni',
    'Juli','August','September','Oktober','November','Dezember'],
    monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
    'Jul','Aug','Sep','Okt','Nov','Dez'],
    dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
    dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
    dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
    weekHeader: 'Wo',
    dateFormat: 'dd.mm.yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''};
  $.datepicker.setDefaults($.datepicker.regional['de']);
});

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    
                    //MODIFICATION: unserialize!
                    break;
                }
            }
        }
        return cookieValue;
    }
};
