//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(){
    };
  }
}

/**
 * global wsgn object
 */
var wsgn = {
  
  Map: null,
  
  /**
   * holds all additionall initialisation funcs
   */
  initFuncs: [],
  
  //instance of google analytics pageTracker
  tracker: null,
  
  /**
   * called after thsi script is loaded
   */
  init: function(){
    wsgn.registerEventHandlers();
  },
  
  /**
   * register all global event handlers
   */
  registerEventHandlers: function(){
    //call added init functions
      $.each(wsgn.initFuncs, function(){
        //wsgn.Logger.log('func', this);
        this();
      });
      
    $('body').ajaxComplete(function(event, xhr, options) {
      wsgn.trackAjax(options.url);      
    });
    
    $('#logoutLink').bind('click', k1fb.events.onLogoutClick);
    
    //ajax thumbsUp! links
    $('a.thumbsUp').live('click', 
      function(){
        var elem = this;
        $(this).addClass('loading')
        $(this).load(this.href, function(){
          //alert('load finished!')
          $(elem).removeClass('loading');
        });
        return false;
      }
    );

    this.initQuestions();
    this.initFilterForms();
    this.initSliders();
    this.initHelpSystem(); 
    //TODO: should not alaways be called, only by forms
    this.initSearch();
    this.initTabNavigation();
    this.initMainNavigation();
    //TODO: should not alaways be called 
    this.initCommentsForm(); 
  },
  
  
  /**
   * 
   * global slider elements (e.g. ratings)
   * 
   */
  initSliders: function(){
    $('a.expand').live('click', function(){
      $(this).find('span').each(function() {
        if($(this).hasClass('hidden')) {
          $(this).removeClass('hidden');
        }
        else {
          $(this).addClass('hidden');
        }
      });

      $('#' + this.rel).slideToggle();
      $(this).blur();
      return false;
    });    
  },
  
  /**
   * auto submit filters
   */
  initFilterForms: function(){
    $('form.filters select').change(
      function(){
        console.log('changed!');
        $( $(this).parents('form')[0]).submit();
      }
    );
  },
  
  /**
   * teasers on homepage
   */
  initHometeaser: function(){
    $('ul.teaser li.closed').live('hover', function(){
      $('ul.teaser li').removeClass('open').addClass('closed');
      $(this).removeClass('closed').addClass('open');
      $(this).blur();
      
      var index = $(this).attr('data-index');
      
      $('#top .teaserImage').hide();
      $($('#top .teaserImage')[index]).show();
    });
  },
  
  /**
   * init countdown links for questions
   */
  initQuestions: function(){
    $('.countdown').each(function(){
      wsgn.editTimer(this);
    });
  },
  
  /**
   * global help system
   */
  initHelpSystem: function(){
    $('form select, form input, form textarea').focus(function(){
      $(this).closest('tr').find('.helpContainer.hidden').removeClass('hidden').addClass('hideOnBlur');
      return false;
    });
    $('form select, form input, form textarea').blur(function(){
      $(this).closest('tr').find('.hideOnBlur').removeClass('hideOnBlur').addClass('hidden');
      return false;
    });
    wsgn.Logger.log('init form help');
  },
  
  /**
   * search field
   */
  initSearch: function(){
    $('#q').focus(function(){
      $(this).val('');
    });
  },
  
  /**
   *  "more" link in tab navi
   */
  initTabNavigation: function(){
    $('ul.tabNavigation li.secondary a.more, ul.secondary').hover(function(){
      $(this).parent('li').find('ul.secondary').removeClass('hidden');
    }, function(){
      $(this).parent('li').find('ul.secondary').addClass('hidden');
    });
  },
  
  
  /**
   * handles personal handicap calculation for each hole on a scorecard form
   */
  initScorecardHcpCalculation: function(){
    $('#calculateBtn').click(
        function(){
          var holeInputs = $(':input.personalHcp', $('#scorecardForm')[0]);
          var orderedHoles = [];
          var numHoles = holeInputs.length;
          var personalCourseHcp = $('#personalCourseHcp').val();
          var perHole = 0;
          var rest = 0;
          
          //1. equally distribute
          perHole = Math.floor(personalCourseHcp/holeInputs.length);
          rest = personalCourseHcp - (perHole*holeInputs.length);
          
          //2. order all holes by hcp, the lowest handicap is the hardest hole          
          $(holeInputs).each(function(num){
            $(this).val(perHole);
            orderedHoles[($(this).attr('data-hole-hcp')-1)] = this;
          });
          
          console.log('all', orderedHoles, perHole, rest);
          
          //3. equally distribute the rest on the hardest holes
          var newVal = 0;
          for(var i = 0; i < orderedHoles.length; i++){
            if(rest > 0){
              var newVal = parseInt(parseInt($(orderedHoles[i]).val())+1);
              $(orderedHoles[i]).val(parseInt(newVal));
              rest--;
              console.log('left to distribute:', rest);
            }
          }
          return false;
      }
    );
  },
    
  /**
   * fadeout navi
   */
  initMainNavigation: function(){
    $('ul#mainNavigation a.level1, ul.mainSubNavigation').hover (
      function() {
        $(this).parents('li').children('ul.mainSubNavigation').removeClass('hidden');
      },
      function() {
        $(this).parents('li').children('ul.mainSubNavigation').addClass('hidden');
      }
    );
    $('ul.mainSubNavigation a.level2, ul.regions').hover (
      function() {
        $(this).parents('li').children('ul.regions').removeClass('hidden');
      },
      function() {
        $(this).parents('li').children('ul.regions').addClass('hidden');
      }
    );
    $('ul.regions').hover (
      function() {
        $(this).parent('li').find('a.level2').addClass('hover');
      },
      function() {
        $(this).parent('li').find('a.level2').removeClass('hover');
      }
    );
  },
  
  /**
   * 
   */
  initCommentsForm: function(){
    $('.ajaxCommentsForm').submit(function(){
     var form = this; 
     var target = $($(this).parents('div.commentsList')[0]).find('.expandButton');     
     $(this).ajaxSubmit({
        success: function(data){
          $(data).hide().insertBefore(target).slideDown('fast');
        },
        error: function(){
          alert('Leider ist ein Fehler aufgetreten!');
        },
        complete: function(){
          $('textarea', form).val('');
        }
      });
      return false;
    });    
  },
  
  /**
   * creates a countdown for a countdown link
   * @param {Object} elem
   */
  editTimer: function(elem){
    var timer = setInterval(function(){
      var time = $(elem).find('span.timeLeft').text();
      var secondStr = 'Sekunden';
      time--;
      if(time == 1){
        secondStr = 'Sekunde';
      }
      if(time >= 0 ){
        $(elem).find('span.timeLeft').text(time);
        $(elem).find('span.seconds').text(secondStr);
      }
      else{
        $(elem).fadeOut('slow', function(){$(this).remove()})
        clearInterval(timer);
      }
    }, 1000);
  },
  
  /**
   * state buttons e.g. "my favourite course"
   */
  registerCourseEvents: function() {
    $('a.changeCourseState').die().live('click', function() {
      $(this).addClass('loading');
      
    //target div is stored in link's rel attribute
      var targetDiv = '#' + this.rel;
      var link = $(this);
      
      
      $.ajax({
		url: $(this).attr('href'),
		dataType: 'json',
		success: function(data) {
    	  link.parent().html(data.button);
    	  if($(targetDiv).length > 0) {
    		//TODO make better effect
    		$(targetDiv).hide();  
    	    $(targetDiv).html(data.players);
    	    $(targetDiv).fadeIn('slow');
    	  }
		}
	  });
     
      return false;
    });
    
  },
  
  registerCheckAll: function() {
    $('#checkall').unbind('click').click(
    function(){
      if(this.checked){
        $(this).parents('form').find(':checkbox').each(
          function(num, elem){
            elem.checked = true;
          }
        );
      }
      else{
        $(this).parents('form').find(':checkbox').each(
          function(num, elem){
            elem.checked = false;
          }
        );
      }
    });
  },
  
  /**
   * 
   * @param {Object} tracker an instance of google analytics pageTracker
   */
  setTracker: function(tracker){
    wsgn.Logger.log('tracker activated', tracker);
    this.tracker = tracker;
  },
  
  //TODO: ajax tracking
  trackAjax: function(url){
    if(this.tracker != null  && url != null){
      this.tracker._trackPageview(url);
      wsgn.Logger.log('tracked', url);
    }
    else{
      wsgn.Logger.warn('could not track ajax event because tracker is not defined or no ur was apssed');
    }
  },
  
  /**
   * add functions to the initFuncs array which are executed after dom is ready
   * @param {Function} func
   */
  addInitFunc: function(func){
    wsgn.initFuncs.push(func);
  },
  
  
  /**
   * logging system to handle systems where console.log is not defined
   */
  Logger: {
    log: function(){
      try{
        console.log(arguments);        
      }
      catch(e){}
    },
    warn: function(){
      try{
        console.warn(arguments);        
      }
      catch(e){}
    },
    error: function(){
      try {
        console.error(arguments);        
      }
      catch(e){}
    },
    dir: function(){
      try{
        console.dir(arguments);        
      }
      catch(e){}
    }
  },
  
  
  
  /**
   * stream for hoemapage
   */
  Homestream : {
    settings: {
      interval: 10000
    },
  
    timer: null,
  
    /**
     * init the stream
     * @param {Object} params
     */
    init: function(params){
      this.settigns = $.extend(this.settings, params);
      this.timer = setTimeout(function(){
        wsgn.Homestream.showNextElement();
        }, wsgn.Homestream.settings.interval);
    },
  
    /**
     * triggered by timer
     */
    showNextElement: function(){
      if($('.streamEntry:hidden').length > 0){
        $('.streamEntry:hidden:last').hide().removeClass('hidden').slideDown('slow');
        $('.streamEntry:visible:last').slideUp('slow', function(){
          $(this).remove();
        });
        wsgn.Homestream.timer = setTimeout(arguments.callee, wsgn.Homestream.settings.interval);
      }
      else{
        wsgn.Homestream.timer = null;
      }
    }
  },
  
  /**
   * 
   * @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: 800,
         height: 600,
         top: null,
         left: null,
         resizable: 'yes',
         scrollbars: 'yes',
         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);
     });

     paramStr = params.join(',');
     var win = window.open(url, title, paramStr);
     win.focus();
     return win;
   }
};


(function($){
jQuery.fn.clickDelete = function(originalText) {
  // define defaults and override with options, if available
  // by extending the default settings, we don't modify the argument
  // do the rest of the plugin, using url and settings
  return this.each(function(){
    var currentText = $(this).val();
    /*if(typeof originalText == 'undefined'){
      originalText = $(this).val();
    }*/
   
    var elem = this;
    
    //delete on click/focus
    $(elem).bind('click, focus', function(){
      if( $(elem).val() == originalText){
        $(elem).val('');
      }
    });
    
    //restore on blur
    $(elem).bind('blur', function(){
      if($(elem).val() == ''){
        $(elem).val(originalText);
      }  
    });
    console.log(this);
  });
}
})(jQuery);

(function($){
jQuery.fn.charCount = function(maxChars, countField) {
  // define defaults and override with options, if available
  // by extending the default settings, we don't modify the argument
  // do the rest of the plugin, using url and settings
  return this.each(function(){
    var originalText = $(this).val();
    var elem = this;
    
    //delete on click/focus
    $(elem).bind('keyup', function(){
      var val = $(this).val();
      var len = val.length;
      $(countField).text(maxChars-len);
      /*if(maxChars-len <= 0){
        alert('Sorry!');
      }*/
    });    
    
    console.log(this);
  });
}
})(jQuery);



/**
*
* extended text Plugin, extend a hidden Text
*
*/
(function($){
 $.fn.wallForm = function(settings){
	 console.log('init wallform!', this);
   var form = this;
   var errorMsgs = [];
   var config = {
     listSelector: '#commentsList'
   };
   
   $.extend(config, settings);
   
   function onFormSubmit(){
     $(this).ajaxSubmit({
       beforeSubmit: function(){
         console.log($('textarea',form));
         if($('textarea',form).val() == ''){
           alert('Bitte gib einen Kommentar ein');
           return false;
         }
       },
       success: function(data){
         $(config.listSelector).append('<ul class="itemList" <li>' + data + '</li></ul>');
       },
       error: function(){
         alert('Leider ist ein Fehler aufgetreten!');
       }
     });
     return false;
   }
   
   if ($(config.listSelector).length > 0) {
     this.each(function(){
       $(this).bind('submit', onFormSubmit);
     });
   }
   
   else {
     console.warn('comments list not present!');
   }
   
   
   return this;
 };
 
})(jQuery);

