var speedScroll = 500;
var speedSlide = 500;

$JQ(document).ready(function() {

  $JQ('div.sectionBody').each(function() {
    if(!$JQ(this).hasClass('closed')) {
  //CONNECTORTEAM.GENERIC.loadInbox(this, 2);
  }
  });

  CONNECTORTEAM.TOPMENU.bindMenuMain();
  CONNECTORTEAM.EXPANDER.bindExpander();
  //if(!mobileBrowser)
  //{
  //CONNECTORTEAM.TIMESHEETS.timesheetLongpollStart();
  //CONNECTORTEAM.EXPENSES.timesheetLongpollStart();
  //}
	
  $JQ('#ui-datepicker-div').live('mouseover', function() {
    $JQ('#ui-datepicker-div').addClass('datePickerWrapper');
  });
    
});

CONNECTORTEAM = {};

//********************************************************************************************
CONNECTORTEAM.GENERIC = {
		

  loadInbox: function(panel, limit) {
		
    var panelName = $JQ('#privatemessage-inbox').attr('id').replace('-inbox','');
    $JQ('#privatemessage-inbox').load('/team/privatemessage/inbox/new/1/limit/' + limit + '?show_bubble_messages=true&format=html', null, function() {
      CONNECTORTEAM.PRIVATE_MESSAGES.setStyles();
      CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents();
      $JQ('.sectionNews').find('.sectionItemHead').unbind('click');
      var messages = $JQ('#totalUnreadMessages').html();
			
      $JQ('#unreadMessageCount').text(messages);
			
    });
			
  },
		
  bindMenu: function() {
    //hide all but the first elem
    $JQ('fieldset.form:gt(0)').hide();
    //set first active
    $JQ('div.menu ul li:first').addClass('active');
    //create hover
    $JQ('div.menu ul li').mouseenter(function(){
      $JQ(this).addClass('hover')
    });
    $JQ('div.menu ul li').mouseleave(function(){
      $JQ(this).removeClass('hover')
    });
				
    //bind click
    //alert('');
		 		
    $JQ('div.menu ul li').each(function() {
      var elem = $JQ('div.menu ul li').index( $JQ(this) );
      $JQ(this).unbind('click');
		 			
      $JQ(this).click(function(){
        //hide all
        $JQ('fieldset.form:visible').hide();
        $JQ('div.menu ul li').removeClass('active');
        $JQ(this).addClass('active');
        $JQ('fieldset.form:eq('+elem+')').show();
		 			
        return false;
		 			
      });
		 			
    });
		 			
				
  },
  processErrors: function(errors) {
    $JQ("div#messages > *").remove();
    $JQ("div#messages").append("<ul class='errors'>");

    for(k in errors) {
      if(typeof errors[k] == 'string') {
        $JQ('ul.errors').append('<li>' + errors[k] + '</li>');
      }
      else {
        for(k2 in errors[k]) {
          $JQ('ul.errors').append('<li>' + errors[k][k2] + '</li>');
        }
      }
    }
    $JQ("div#messages").show();
  },
  processErrorsToId: function(errors, errorDivId) {
    $JQ("div#" + errorDivId + " > *").remove();
    $JQ("div#" + errorDivId).append("<ul class='errors'>");

    for(k in errors) {
      if(typeof errors[k] == 'string') {
        $JQ('ul.errors').append('<li>' + errors[k] + '</li>');
      }
      else {
        for(k2 in errors[k]) {
          $JQ('ul.errors').append('<li>' + errors[k][k2] + '</li>');
        }
      }
    }
    $JQ("div#" + errorDivId).show();
  },
  processSuccess: function(messages) {
    $JQ("div#messages > *").remove();
    $JQ("div#messages").append("<ul class='success'>");

    for(k in messages) {
      if(typeof messages[k] == 'string') {
        $JQ('ul.success').append('<li>' + messages[k] + '</li>');
      }
      else {
        for(k2 in errors[k]) {
          $JQ('ul.success').append('<li>' + messages[k][k2] + '</li>');
        }
      }
    }
    $JQ("div#messages").show();
  },

  maskWindow: function()
  {
    mask = document.createElement('div');
    $JQ(mask).addClass('windowMask');
    $JQ(mask).css('width', $JQ(window).width());
    $JQ(mask).css('height', $JQ(window).height());
    $JQ('body').append(mask);
    spinner = document.createElement('img');
    $JQ(spinner).addClass('ajaxSpinner');
    $JQ(spinner).attr('src', '/images/ajaxSpinner.gif');
    $JQ(spinner).css('left', ($JQ(window).width()/ 2) - ($JQ(spinner).width() / 2));
    $JQ(spinner).css('top', ($JQ(window).height()/ 2) - ($JQ(spinner).height() / 2));

    $JQ(mask).append(spinner);
  },

  unMaskWindow: function()
  {
    $JQ('.windowMask').remove();
  }
};

//*******************************************************************************************

CONNECTORTEAM.PRIVATE_MESSAGES = {
  initialized: false,
  inboxLongPollRunning: false,
  markReadUrl: '/team/privatemessage/markread',
  initialize: function() {
    $JQ('.bubble_message_option').hide();
    if(CONNECTORTEAM.PRIVATE_MESSAGES.initialized)
    {
      return;
    }
    CONNECTORTEAM.PRIVATE_MESSAGES.initialized = true;
    CONNECTORTEAM.PRIVATE_MESSAGES.setStyles();
    CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents();
    $JQ('.recipients-list').parent().hide();
    $JQ('.recipients-list').parent().next('br').hide();
    $JQ('.recipients-list').bind('change', function() {
      if($JQ(this).attr('checked') == true)
      {
        $JQ(this).parent().show();
        $JQ(this).parent().next('br').show();
      } else {
        $JQ(this).parent().hide();
        $JQ(this).parent().next('br').hide();
        var allElementsOff = 1;
        var numberOfElements = $JQ('.recipients-list').size();
        var countOfElements = 0;
        $JQ('.recipients-list').each(function() {
          var eachElement = $JQ(this);
          countOfElements++;
          if (eachElement.parents('label').css('display') != 'none') {
            allElementsOff = 0;
          }
          if ((countOfElements == numberOfElements) && (allElementsOff == 1)) {
            $JQ('#hiddenRecipients').addClass('hide');
          }
        });
      }

    });
    if($JQ("#mailboxTabs").tabs()) {
	    
    }
    $JQ("#mailboxTabs").bind('tabsselect', function(event, ui){
      $JQ("div#messages > *").remove();
    });

    //$JQ('#message_compose-recipients-' + uuid).parent().show();
    $JQ('.recipients-list').attr('checked', false);
    //$JQ('#unreadMessageCount').text($JQ('.unread').length)
    CONNECTORTEAM.PRIVATE_MESSAGES.inboxLongpollStart();
  },

  setStyles: function() {
	    
    $JQ(' #messageOutbox .sectionItem:odd').addClass('evenItem');
  },

  inboxLongpollStart: function()
  {

    if(!CONNECTORTEAM.PRIVATE_MESSAGES.inboxLongPollRunning)
    {
      $JQ.ajax(
      {
        url: '/team/privatemessage/checkfornewmessages',
        data: 'message_count=' + $JQ('#unreadMessageCount').text(),
        dataType: 'json',
        success: function(data){
          CONNECTORTEAM.PRIVATE_MESSAGES.inboxLongpollComplete(data)
        }
      });
      CONNECTORTEAM.PRIVATE_MESSAGES.inboxLongPollRunning = true;
    }
		    
  },

  inboxLongpollComplete: function(data)
  {
    CONNECTORTEAM.PRIVATE_MESSAGES.inboxLongPollRunning = false;
    //alert(data);
    //$JQ('.messageRowHeader').after(data);
	
    if(data.newMessages == true)
    {
      $JQ('#unreadMessageCount').text(data.unreadMessageCount)
      if(CONNECTORTEAM.PRIVATE_MESSAGES.inboxPage == 1)
      {
		
        CONNECTORTEAM.PRIVATE_MESSAGES.addNewMessages(data.messageData);
      }
	    
      $JQ('#noMessagesInInbox').show();
    }
    CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents();
	
    if($JQ('#unreadMessageCount').html() != '0') {
      $JQ('#noMessagesInInbox').hide();
    }
    CONNECTORTEAM.PRIVATE_MESSAGES.inboxLongpollStart();

  },

  addNewMessages: function(messageData)
  {
    $JQ(messageData).each(function(){
      $JQ.ajax({
        url: '/team/privatemessage/messagerow/id/' + this.id,
        dataType: 'html',
        success: function(data) {
          $JQ('#messageInbox').find('.sectionItemTitles').after(data);
          CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents();
        }
      });
    });
	
  },

  bindEvents: function() {
    $JQ('#mailboxTabs').bind('tabsselect', CONNECTORTEAM.PRIVATE_MESSAGES.composeTabSelectEventHandler);
    $JQ('#message_compose-send').unbind('click').bind('click', function(){
      $JQ('#message-compose-form').submit();
      return false;
    });
    $JQ('#message_compose-cancel').bind('click', function(){
      $JQ('#message-compose-form').clearForm();
      CONNECTORTEAM.PRIVATE_MESSAGES.activateInboxTab();
      CONNECTORTEAM.PRIVATE_MESSAGES.clearRecipients();
      return false;
    });
    $JQ('#message_compose-bubble_message').change(CONNECTORTEAM.PRIVATE_MESSAGES.toggleBubbleMessage)
    $JQ('#message_compose-attach').bind('click', function(){
      $JQ('#fileUpload').removeClass('hide');
      return false;
    });
    $JQ('.sectionItemHead').bind('click', this.messageRowClickEventHandler);
    //$JQ('p.button.messageForward').bind('click', CONNECTORTEAM.PRIVATE_MESSAGES.messageForwardOnclickHander);
		
    $JQ('.messageDelete').click(CONNECTORTEAM.PRIVATE_MESSAGES.messageDeleteOnclickHander);
    $JQ('#message-compose-form').submit(function(){
      $JQ('#messages > *').remove();
    // tinyMCE.triggerSave()
    //do validation here
    //clear form
		  
    });
    $JQ('#message-compose-form').ajaxForm(
    {
      beforeSubmit: function()
      {
        CONNECTORTEAM.GENERIC.maskWindow();
      },
      success : function(data, json) {
        CONNECTORTEAM.GENERIC.unMaskWindow();
        $JQ('#messages > *').remove();
        if (data == true) {
          CONNECTORTEAM.PRIVATE_MESSAGES.updateOutbox();
          CONNECTORTEAM.PRIVATE_MESSAGES.clearComposeForm();
          CONNECTORTEAM.GENERIC.processSuccess( [ "Message Sent" ]);
        } else {
          CONNECTORTEAM.GENERIC.processErrors(data.message_compose);
        }

      },
      error: function() {
        CONNECTORTEAM.GENERIC.unMaskWindow();
        CONNECTORTEAM.GENERIC.processErrors(["Error sending private message"]);
      },
      dataType: 'json'
    });

    $JQ('.recipients').click(function() {
      if($JQ(this).next(".recipientsList").html() == null)
      {
        return;
      }
      else if($JQ(this).next('.recipientsList').html().length == 0)
      {
        $JQ(this).next('.recipientsList').load('/team/privatemessage/recipientslist/mu/' + $JQ(this).attr('id'));
      }
      $JQ(this).closest('.recipients').find('.recipientsList').toggleClass('hide');
    });
	
  },

  toggleBubbleMessage: function() {
    $JQ('.bubble_message_option').hide();
    if($JQ(this).attr('checked'))
    {
      $JQ('.bubble_message_option').show();
    }
  },

  messageDeleteOnclickHander: function() {
  //alert($JQ(this).find('a').attr('href'));
  //return false;
  //	$JQ.ajax({
  //	    url: $JQ(this).find('a').attr('href'),
  //	    success: function () {
  //		CONNECTORTEAM.PRIVATE_MESSAGES.updateInbox()
  //		CONNECTORTEAM.PRIVATE_MESSAGES.updateArchive()
  //
  //	    }
  //	});
  //	return false;
  },

  composeTabSelectEventHandler: function(event, ui) {
    $JQ('.error').remove();
  },

  parseComposeFormErrors: function(field, message) {
	
    if(field == 'recipients') {
      field = 'to';
      message = message.notInArray;
    }
    $JQ('#message_compose-' + field).closest('.formRow').append('<ul class="errors"><li>' + message + '</li></ul>');
	
  },

  clearRecipients: function() {
    $JQ('#hiddenRecipients').addClass('hide');
    $JQ('#recipients-element >label').css('display','none');
    $JQ('.recipients-list').attr('checked', false);
  },

  clearComposeForm: function()
  {
    $JQ('#message-compose-form').clearForm();
    CONNECTORTEAM.PRIVATE_MESSAGES.clearRecipients();
    CONNECTORTEAM.PRIVATE_MESSAGES.clearAttachments();
  },

  clearAttachments: function()
  {
    $JQ('#file_attachments-element').find('label').remove();
  },

  messageRowClickEventHandler: function(e)
  {
    $JQ(this).next('.sectionItemBody').find('.recipientsList').load('/team/privatemessage/recipientslist/mu/' + $JQ(this).attr('id'));
    $JQ(this).next('.sectionItemBody').toggle('fast',
      function () {
        $JQ('.sectionItemBody').toggleClass('activeItem');
	    			
        if($JQ(this).parent('div.sectionItem').hasClass('unreadItem')) {
          $JQ.getJSON(CONNECTORTEAM.PRIVATE_MESSAGES.markReadUrl, {
	    			    		
            element: $JQ(this).parent('div.sectionItem').attr('id')
          }, function(json) {
	    			    	
            $JQ('#unreadMessageCount').text(json.data.unreadMessageCount);
	    				
          });
          $JQ(this).parent('div.sectionItem').removeClass('unreadItem');
        }
      });
    return false;
  },

  messageForwardOnclickHander: function() {
    CONNECTORTEAM.PRIVATE_MESSAGES.clearRecipients();
    subject = 'RE: ' + $JQ(this).closest('.sectionItem').find('.subject').find('a').text();
    $JQ('#message_compose-subject').val(subject.replace("\t", ''));
    CONNECTORTEAM.PRIVATE_MESSAGES.activateComposeTab();
    messageText = $JQ(this).closest('.sectionItem').find('.sectionItemBody').find('p').html();

    $JQ('#message_compose-message').val("\n\n===========================\n\n");
    $JQ('#message_compose-message').val($JQ('#message_compose-message').val() + messageText);
    $JQ('#message_compose-message').val($JQ('#message_compose-message').val() + "\n\n===========================");
    return false;
  },

  messageReplyOnclickHander: function() {
    subject = 'RE: ' + $JQ(this).closest('.sectionItem').find('.subject').find('a').text();
    $JQ('#message_compose-subject').val(subject.replace("\t", ''));
    CONNECTORTEAM.PRIVATE_MESSAGES.activateComposeTab();
    messageText = $JQ(this).closest('.sectionItem').find('.sectionItemBody').find('p').html();

    $JQ('#message_compose-message').val("\n\n===========================\n\n");
    $JQ('#message_compose-message').val($JQ('#message_compose-message').val() + messageText);
    $JQ('#message_compose-message').val($JQ('#message_compose-message').val() + "\n\n===========================");
    uuid = $JQ(this).closest('.sectionItem').find('.sender-uuid').text();
    uuid = uuid.replace(/\-/g,'');
		
    $JQ('#hiddenRecipients').removeClass('hide');
    $JQ('#message_compose-recipients-' + uuid).attr('checked', true);
    $JQ('#message_compose-recipients-' + uuid).parent().show();
    return false;
  },

  activateComposeTab: function() {
    $JQ("#mailboxTabs").tabs('select', 1);
  },

  activateInboxTab: function() {
    $JQ("#mailboxTabs").tabs('select', 0);
  },

  activateOutboxTab: function() {
    $JQ("#mailboxTabs").tabs('select', 2);
  },

  populateComposeForm: function(data) {
		
  },
  getDataFromComposeForm: function()
  {

  },
  updateInbox: function()
  {
    $JQ('#receivedMessages').load('/team/privatemessage/receivedmessages', function() {
      CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents()
      });
    CONNECTORTEAM.PRIVATE_MESSAGES.updateNewMessageCount();

  },
  updateArchive: function()
  {
    $JQ('#archivedMessages').load('/team/privatemessage/archivedmessages', function () {
      CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents()
      });

	
  },
  updateOutbox: function()
  {
    $JQ('#sentMessages').load('/team/privatemessage/sentmessages', {}, function() {
      CONNECTORTEAM.PRIVATE_MESSAGES.setStyles();
      CONNECTORTEAM.PRIVATE_MESSAGES.bindEvents();
    });
	
	
  },

  updateNewMessageCount: function()
  {
    $JQ.getJSON('/team/privatemessage/newmessagecount', function(data){
      $JQ('#unreadMessageCount').text(data.new_message_count);
	    
    });
		
  },
	    
  addRecipient: function(event, data, formatted)
  {
    $JQ(event.target).val('');
    uuid = data[1].replace(/\-/g,'');
    $JQ('#hiddenRecipients').removeClass('hide');
    $JQ('#message_compose-recipients-' + uuid).attr('checked', true);
    $JQ('#message_compose-recipients-' + uuid).parent().show();
  },

  fileAttachmentSuccessHandler: function(file, serverData) {
    try {
	    
      var progress = new FileProgress(file, this.customSettings.progressTarget);
      progress.setComplete();
      progress.setStatus("Complete.");
      progress.toggleCancel(false);
      serverData = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.
        test(serverData.replace(/"(\\.|[^"\\])*"/g, '')))
      && eval('(' + serverData + ')');
      //$JQ('#message_compose-file_attachments').append('<option id="file_attachment_' + serverData.data.file_row.id + '" value="' + serverData.data.file_row.id + '" selected="selected" class="icon-' + serverData.data.icon + '">' + serverData.data.file_row.title + '</option>');
      $JQ('#file_attachments-element').append('<label for="message_compose-file_attachments-' + serverData.data.file_row.id + '"><input class="message-attachment-checkbox" type="checkbox" checked="true" name="message_compose[file_attachments][]" id="message_compose-file_attachments-' + serverData.data.file_row.id + '" value="' + serverData.data.file_row.id + '" />' + serverData.data.file_row.title + '</label>');
	
      $JQ('#message_compose-file_attachments-' + serverData.data.file_row.id).bind('change', function() {
        $JQ(this).closest('label').remove();
      });
    } catch (ex) {
      this.debug(ex);
    }
  },

  removeAttachment: function(id)
  {
    $JQ('#file_attachment_' + id).remove();
  }



};

//*******************************************************************************************

CONNECTORTEAM.UI = {
		
  /**
		*sets an element to slide up and down (roller blind) please see read me and index.html for element structure
		*@param clickClass string the element you want show/hide buttons added to
		*@param showClass string the element you want to slide
		*@param parentClass string the parent element tp scoll to
		*@param scrollTo boolean if true where needed the page will scroll to the page position
		*@param speedSlide INT speed of slide defaults to 500 millisecs
		*@param speedScroll INT speed of scrollTo defaults to 500 millisecs
		*
		*/
		
  bindSlideUpDown: function(options) {
			
    defaults = jQuery.extend({
      clickClass : ".showHide",
      showClass : ".slide",
      parentClass : ".scrollTo",
      scrollTo : false,
      speedSlide : 500,
      speedScroll: 500
    },options);
			
    $JQ(defaults.showClass).hide();
			
    $JQ(defaults.clickClass).each(function() {
      var clickBtn = $JQ(this).html()
      clickBtn += ' <span class="doShow">Show</span> / <span class="doHide">Hide</span>';
      $JQ(this).html(clickBtn);
    });
			
    $JQ('.doShow').hover(function(){
      $JQ(this).addClass('hover')
    },function(){
      $JQ(this).removeClass('hover')
    });
    $JQ('.doHide').hover(function(){
      $JQ(this).addClass('hover')
    },function(){
      $JQ(this).removeClass('hover')
    });
    $JQ('.doShow').unbind('click');
    $JQ('.doShow').bind('click',function() {
      var theElement = $JQ(this);
      $JQ(defaults.showClass, theElement.parents(defaults.parentClass)).slideDown(defaults.speedSlide, function() {
        if (defaults.scrollTo) {
          $JQ(window).scrollTo(theElement.parents(defaults.parentClass), {
            duration: defaults.speedScroll,
            axis:'y'
          });
        }
      });
      return false;
    });
			
    $JQ('.doHide').unbind('click');
    $JQ('.doHide').bind('click',function() {
      var theElement = $JQ(this);
      $JQ(defaults.showClass, theElement.parents(defaults.parentClass)).slideUp(defaults.speedSlide, function() {
        if (defaults.scrollTo) {
          $JQ(window).scrollTo(theElement.parents(defaults.parentClass), {
            duration: defaults.speedScroll,
            axis:'y'
          });
        }
      });
      return false;
    });
		
  }
};

//*******************************************************************************************

CONNECTORTEAM.TOPMENU = {
	
  bindMenuMain: function() {
    $JQ('.breadcrumb').unbind('mouseup').bind('mouseup', function(){
      if ($JQ('.menuMainSliding').css('display') == 'none') {
        $JQ('.menuMainSliding').slideDown(speedSlide);
        $JQ('.tutorial-video, .training-video').css("visibility", "hidden");
      }
    });
    $JQ('.breadcrumb').unbind('mousedown').bind('mousedown', function(){
      if ($JQ('.menuMainSliding').css('display') != 'none') {
        $JQ('.menuMainSliding').slideUp(speedSlide);
        $JQ('.tutorial-video, .training-video').css("visibility", "visible");
      }
    });
		
    $JQ('.menuMainSliding').unbind('mouseleave').bind('mouseleave', function(){
      if ($JQ('.menuMainSliding').css('display') != 'none') {
        $JQ('.menuMainSliding').slideUp(speedSlide);
        $JQ('.tutorial-video, .training-video').css("visibility", "visible");
      }
    });
  /*$JQ(document+':not(.breadcrumb,.menuMainSliding)').unbind().bind('mousedown', function(){
			if ($JQ('.menuMainSliding').css('display') != 'none') {
				$JQ('.menuMainSliding').slideUp(speedSlide);
			}
		});*/
  }
}

//*******************************************************************************************

CONNECTORTEAM.EXPANDER = {
  bindExpander: function() {
    $JQ('.expander a').live('click',function() {
      if ($JQ(this).parents('.expander').siblings('.expandingContent').css('display') != 'none') {
        $JQ(this).parents('.expander').siblings('.expandingContent').slideUp(speedSlide);
      //$JQ(this).css('background-image','url("/images/team/arrow_black_right.gif")');
      } else {
        $JQ(this).parents('.expander').siblings('.expandingContent').slideDown(speedSlide);
      //$JQ(this).css('background-image','url("/images/team/arrow_black_down.gif")');
      }
      return false;
    });
  }
}

//*******************************************************************************************

CONNECTORTEAM.POSTCOMMENT = {
  initialize: function(controller) {
    CONNECTORTEAM.POSTCOMMENT.controller = controller;
    CONNECTORTEAM.POSTCOMMENT.bindEvents();
  },

  bindEvents: function() {
    $JQ('.commentEdit').click(CONNECTORTEAM.POSTCOMMENT.commentEditOnClickHandler);
    $JQ('.commentCancel').click(CONNECTORTEAM.POSTCOMMENT.commentCancelOnClickHandler);
    $JQ('.commentSave').click(CONNECTORTEAM.POSTCOMMENT.commentSaveOnClickHandler);
    $JQ('.commentDelete').click(CONNECTORTEAM.POSTCOMMENT.commentDeleteOnClickHandler);
    $JQ('.comment-edit-form').ajaxForm({
      success: CONNECTORTEAM.POSTS.updateComments,
      dataType: 'json',
      clearForm: false
    });
  },

  setStyles: function() {

  },

  // Event Handlers

  commentEditOnClickHandler: function() {
    CONNECTORTEAM.POSTCOMMENT.toggleClasses(this);
    return false;
  },

  toggleClasses: function(clickedElement) {
    $JQ(clickedElement).closest('.commentItem').find('.commentForm').toggleClass('hide');
    $JQ(clickedElement).closest('.commentItem').find('.commentCancel').parent('p').toggleClass('hide');
    $JQ(clickedElement).closest('.commentItem').find('.commentSave').parent('p').toggleClass('hide');
    $JQ(clickedElement).closest('.commentItem').find('.commentDelete').parent('p').toggleClass('hide');
    $JQ(clickedElement).closest('.commentItem').find('.commentEdit').parent('p').toggleClass('hide');
  },

  commentCancelOnClickHandler: function() {
    CONNECTORTEAM.POSTCOMMENT.toggleClasses(this);
    return false;
  },

  commentSaveOnClickHandler: function() {
    $JQ(this).closest('.commentItem').find('.commentForm').find('form').submit();
    return false;
  },

  commentDeleteOnClickHandler: function() {
    commentId = $JQ(this).attr('id');
    $JQ.post('/team/' + CONNECTORTEAM.POSTCOMMENT.controller + '/deletecomment', {
      comment_id: commentId
    },
    function(data, textStatus) {
      $JQ('#comment-item-' + data.deletedCommentId).remove();

      $JQ('#count-blog-comments-list-' + data.row.parent_message_id).html(data.newMessageCount + ' comments');
    }, "json");
    $JQ(this).closest('.commentItem').remove();

    return false;
  }
}
//*******************************************************************************************

CONNECTORTEAM.POSTS = {
  controllerName: null,
    
  init: function(controllerName) {
    CONNECTORTEAM.POSTS.controllerName = controllerName;
    CONNECTORTEAM.POSTS.bindEvents();
    CONNECTORTEAM.POSTS.loadStyles();
    CONNECTORTEAM.POSTS.loadJavascripts();
  },

  loadJavascripts: function()
  {
    $JQ.getScript('/js/jquery-plugins/thickbox-compressed.js');
  },

  loadStyles: function()
  {
  //$JQ('head').append('<link href="/styles/thickbox.css" type="text/css" media="screen"/>');
  },

  bindEvents: function() {
    $JQ('.comment-form-cancel').click(CONNECTORTEAM.POSTS.commentFormCancelOnClickHandler);
    $JQ('.delete').click(CONNECTORTEAM.POSTS.deleteOnClickHandler);
    $JQ('#post-compose-submit').unbind('click').bind('click', function(){
      $JQ('#post-compose-form').submit();
    });
    $JQ('.read-on-button-large').click(CONNECTORTEAM.POSTS.readOnButtonLargeOnClickHandler);
    $JQ('.commentsHead').click(CONNECTORTEAM.POSTS.commentsHeadOnClickHandler);
    $JQ('.add-comment-button-large').click(CONNECTORTEAM.POSTS.addCommentButtonLargeOnClickHandler);
    $JQ('.comment-form').ajaxForm({
      success: CONNECTORTEAM.POSTS.updateComments,
      dataType: 'json',
      clearForm: true
    });
    $JQ('.comment-form-submit').click(CONNECTORTEAM.POSTS.commentFormSubmitOnClickHandler);
    $JQ('.showAttachments').click(CONNECTORTEAM.POSTS.showAttachmentsOnClickHandler);
  },

  showAttachmentsOnClickHandler: function() {
    $JQ(this).closest('.sectionItemBody').find('.attachmentRow').toggleClass('hide');
    return false;
  },

  commentFormCancelOnClickHandler: function() {
    $JQ(this).closest('.comment-form').clearForm();
    return false;
  },

  deleteOnClickHandler: function()
  {
    if(!confirm('Are you sure?'))
    {
      return false;
    }
  },

  readOnButtonLargeOnClickHandler: function() {
    $JQ(this).closest('.sectionItemBody').find('.post-contents').toggleClass('summary-view');
    if($JQ(this).closest('.sectionItemBody').find('.post-contents').hasClass('summary-view'))
    {
      $JQ(this).find('span').text('Read on');
    } else {
      $JQ(this).find('span').text('Show summary');
    }

  },

  addCommentButtonLargeOnClickHandler: function() {
    $JQ(this).closest('.sectionItemBody').children('.comments').addClass('commentsActive');
    $JQ.scrollTo($JQ(this).closest('.sectionItemBody').children('.comments').find('.comment-form'), 1000);
    return false;
  },

  commentFormSubmitOnClickHandler: function() {
    $JQ(this).closest('.comment-form').submit();
    return false;
  },

  commentsHeadOnClickHandler: function()
  {
    $JQ(this).closest('.comments').toggleClass("commentsActive")
  },

  addCommentButtonHeadOnClickHandler: function() {
  //alert('test');
  //$JQ(this).parent().closest('.comments').addClass("commentsActive")
  },

  addCommentButtonOnClickHandler: function() {
    $JQ.scrollTo('.blog-comment-form-anchor');
    $JQ(this).siblings('.comment-form').show();
  },

  updateComments: function(formData, jqForm, form)
  {
    if(formData == false)
    {
      CONNECTORTEAM.GENERIC.processErrors(['Please enter some text for your comment']);
    } else {
      $JQ('.error').remove();
      CONNECTORTEAM.POSTS.updateCommentsCount(formData.postId);
      CONNECTORTEAM.POSTS.updateCommentsList(formData.postId);
      $JQ(form).children('.comment-submit-success').show();
    //$JQ.scrollTo('#comment-item-' + formData.comment.id, 1000);
    }
	
    return false;
  //$JQ(formElement).hide();
  },

  updateCommentsCount: function(blogId)
  {
    elementId = 'count-blog-comments-list-' + blogId;
    $JQ('#' + elementId).load('/team/' + CONNECTORTEAM.POSTS.controllerName + '/countcomments/id/' + blogId, {}, function() {
      $JQ(this).append(' comments')
    });
  //$JQ('#' + elementId).append(' Comments');
  },

  updateCommentsList: function(blogId)
  {
    elementId = 'post-comments-list-' + blogId;
    $JQ('#' + elementId).load('/team/' + CONNECTORTEAM.POSTS.controllerName + '/commentlist/id/' + blogId);
  },

  fileAttachmentSuccessHandler: function(file, serverData) {
    try {
      var progress = new FileProgress(file, this.customSettings.progressTarget);
      progress.setComplete();
      progress.setStatus("Complete.");
      progress.toggleCancel(false);
      serverData = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.
        test(serverData.replace(/"(\\.|[^"\\])*"/g, '')))
      && eval('(' + serverData + ')');
      //$JQ('#message_compose-file_attachments').append('<option id="file_attachment_' + serverData.data.file_row.id + '" value="' + serverData.data.file_row.id + '" selected="selected" class="icon-' + serverData.data.icon + '">' + serverData.data.file_row.title + '</option>');
      $JQ('#file_attachments-element').append('<label for="message_form-file_attachments-' + serverData.data.file_row.id + '"><input class="message-attachment-checkbox" type="checkbox" checked="true" name="message_form[file_attachments][]" id="message_form-file_attachments-' + serverData.data.file_row.id + '" value="' + serverData.data.file_row.id + '" />' + serverData.data.file_row.title + '</label>');

      $JQ('#message_form-file_attachments-' + serverData.data.file_row.id).bind('change', function() {
        $JQ(this).closest('label').remove();
      });
    } catch (ex) {
      this.debug(ex);
    }
  },

  removeAttachment: function(id)
  {
    $JQ('#file_attachment_' + id).remove();
  }
}

CONNECTORTEAM.TIMESHEETS = {
  instanceId: null,
  controllerName: null,
  entryExists: false,
  init: function(controllerName, instanceId) {
	
    CONNECTORTEAM.TIMESHEETS.controllerName = controllerName;
    CONNECTORTEAM.TIMESHEETS.instanceId = instanceId || null;
    CONNECTORTEAM.TIMESHEETS.bindEvents();
    $JQ('.time').timeEntry(
    {
      spinnerImage: '', //spinnerImage: '/js/jquery-plugins/jquery.timeentry/spinnerUpDownBlue.png',
      spinnerSize: [15, 14, 0],
      spinnerBigSize: [30, 32, 0],
      show24Hours: true,
      appendText: '<p class="explanation">&nbsp;formatted as hours:minutes ie 03:15</p>',
      spinnerIncDecOnly: true
    });
	
  },
  updateConnections: function() {
    $JQ(this).find('img').attr('src', '/images/team/refresh-anim.gif');
    clickedElement = $JQ(this);
    $JQ.ajax({
      url: $JQ(this).attr('href'),
      success: function(response) {
        $JQ(clickedElement).closest('td').find('span').text('Updated ' + response.connections);
        $JQ(clickedElement).find('img').attr('src', '/images/team/refresh.gif');
      },
      dataType: 'json'
    })
    return false;
  },
  bindEvents: function() {
    $JQ('.updateConnections').live('click', CONNECTORTEAM.TIMESHEETS.updateConnections);

    /* when a date is selected, we grab the number of connections from Bolser */
    $JQ("#timesheet_locations_form-location_date, input#edited_location_date").change(function() {
      var date = $JQ(this).val();
      var form = $JQ(this).parents("form");
	    
      $JQ.post('/team/timesheets/checkforentrybydate', {
        location_date: date
      },
      function(data, success)
      {
        CONNECTORTEAM.TIMESHEETS.entryExists = data;
        if(data == 'true')
        {
          alert('A timesheet entry already exists for this date. Please edit the timesheet entry to add hours by using the "Review & Submit" tab and clicking "Edit" next to the timesheet entry.');
          return;
        } else {
          $JQ.post('/team/timesheets/connectioninformation', {
            location_date:date
          }, function(data, status) {
				
            //			    console.log(form);
            //			    connection_count = Math.floor(Math.random()*9999);
            //			    console.log(connection_count);
            //	    		form.find('#connectionsCount').text(connection_count);
            //
            //	    		// update a hidden field to save to the db.
            //	    		form.find("input#connections").val(connection_count);
            //
            //	    		return ;
	    		
            if(data.success === true && status === 'success')
            {
              var connection_count = data.connection_count;
				    
              form.find('#connectionsCount').text(connection_count);
	
              // update a hidden field to save to the db.
              form.find("input#connections").val(connection_count);
			    	
            }
            else
            {
			    	
              alert(data.message);
            }
				    
          }, 'json')
        }
      }
      );
		
	    
	    
    });

	
  },

  timesheetLongpollStart: function()
  {

    if(!CONNECTORTEAM.TIMESHEETS.timesheetLongPollRunning)
    {
      $JQ.ajax(
      {
        url: '/team/timesheets/checkforalerts',
        dataType: 'json',
        success: function(data){
          CONNECTORTEAM.TIMESHEETS.timesheetLongpollComplete(data)
        }
      });
      CONNECTORTEAM.TIMESHEETS.timesheetLongPollRunning = true;
    }

  },

  timesheetLongpollComplete: function(data)
  {
    CONNECTORTEAM.TIMESHEETS.timesheetLongPollRunning = false;
    if(data.is_alert == true)
    {
      CONNECTORTEAM.TIMESHEETS.updateRightColumnAlert(data.alert);
    } else {
      CONNECTORTEAM.TIMESHEETS.updateRightColumnAlert(data.alert, true);
    }

    CONNECTORTEAM.TIMESHEETS.timesheetLongpollStart();

  },
    
  updateRightColumnAlert: function(message, alertclear) {
    alertElement = $JQ('.bodyRight').find('.sectionTimesheets').find('a');
    alertElement.html(message);
    if(alertclear)
    {
      alertElement.removeClass('pink');
      alertElement.addClass('green');
    } else {
      alertElement.removeClass('green');
      alertElement.addClass('pink');
    }

  }
}

//*******************************************************************************************
CONNECTORTEAM.EDITORFILEBROWSER = {
  initialize: function(category) {
    CONNECTORTEAM.EDITORFILEBROWSER.category = category;
    CONNECTORTEAM.EDITORFILEBROWSER.populateFileList(category);

	
	
  },

  bindEvents: function() {
    $JQ('.nokiaBrowserFile').click(CONNECTORTEAM.EDITORFILEBROWSER.nokiaBrowserFileOnClickEvent);

  },

  populateFileList: function(category) {
	
    $JQ('.fileList').load('/team/file/filelist/type/' + category, {} , CONNECTORTEAM.EDITORFILEBROWSER.bindEvents);
	
  },

  nokiaBrowserFileOnClickEvent: function() {
    $JQ('#src').val($JQ(this).find('.file-url').html());
	
    if(CONNECTORTEAM.EDITORFILEBROWSER.category == 'image') {
      ImageDialog.update();
    }
    if(CONNECTORTEAM.EDITORFILEBROWSER.category == 'media') {
      $JQ('#media_type').val($JQ(this).find('.fileTypeForSelect').html());
      generatePreview();
      mcTabs.displayTab('general_tab','general_panel');
    }
  },

  callback: function(field_name, url, type, win) {
    var connector = "/team/file/browser";
    var enableAutoTypeSelection = true;

    var cType;
    tinyfck_field = field_name;
    tinyfck = win;

    switch (type) {
      case "image":
        cType = "image";
        break;
      case "flash":
        cType = "Flash";
        break;
      case "file":
        cType = "File";
        break;
    }

    if (enableAutoTypeSelection && cType) {
      connector += "/type/" + cType ;
    }

    window.open(connector, "tinyfck", "modal,width=600,height=400");
	
  },

  openFile: function( fileUrl )
  {
    $JQ('#src').val(fileUrl);
  //	window.top.opener.tinyfck.document.forms[0].elements[window.top.opener.tinyfck_field].value = fileUrl;
  //
  //	if (window.top.opener.tinyfck.document.forms[0].elements[window.top.opener.tinyfck_field].onchange != null) {
  //	    window.top.opener.tinyfck.document.forms[0].elements[window.top.opener.tinyfck_field].onchange();
  //	}
  //
  //	window.top.close();
  //
  //	window.top.opener.tinyfck.focus();
  },

  uploadSuccess: function(file, serverData) {
    try {

      var progress = new FileProgress(file, this.customSettings.progressTarget);
      progress.setComplete();
      progress.setStatus("Complete.");
      progress.toggleCancel(false);
      serverData = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.
        test(serverData.replace(/"(\\.|[^"\\])*"/g, '')))
      && eval('(' + serverData + ')');
      //$JQ('#message_compose-file_attachments').html('<option>' + serverData.file_row.title + '</option>');
      //alert('test');
      CONNECTORTEAM.EDITORFILEBROWSER.populateFileList(CONNECTORTEAM.EDITORFILEBROWSER.category);
    } catch (ex) {
      this.debug(ex);
    }
  }

}

CONNECTORTEAM.EDITORIMAGEINSERT = {
  browserId: 'upload_panel',

  initialize: function() {
    alert('test')
    return;
    CONNECTORTEAM.EDITORIMAGEINSERT.loadBrowser()
    CONNECTORTEAM.EDITORIMAGEINSERT.bindEvents()
  },

  bindEvents: function() {

  },

  loadBrowser: function() {
  //$JQ('#' + CONNECTORTEAM.EDITORIMAGEINSERT.browserId).load('/team/file/browser');
  }
}


//*******************************************************************************************

CONNECTORTEAM.PROFILEEDIT = {
  initialize: function() {

  },

  profileImageUploadSuccessHandler: function(file, serverData) {
    try {

      var progress = new FileProgress(file, this.customSettings.progressTarget);
      progress.setComplete();
      progress.setStatus("Complete.");
      progress.toggleCancel(false);
      serverData = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.
        test(serverData.replace(/"(\\.|[^"\\])*"/g, '')))
      && eval('(' + serverData + ')');
      //$JQ('#message_compose-file_attachments').html('<option>' + serverData.file_row.title + '</option>');
      //alert('test');
      $JQ('#photo_file_id').val(serverData.data.file_row.id);
      imageSrc = '/team/file/getimagebysize/width/145/height/145/name/' + serverData.data.file_row.slug + serverData.data.file_extension;
      $JQ.ajax({
        type: "GET",
        url: imageSrc
      });
	    
	    
      $JQ('#profileImagePreview').attr('src', imageSrc)
      CONNECTORTEAM.EDITORFILEBROWSER.populateFileList(CONNECTORTEAM.EDITORFILEBROWSER.category);
    } catch (ex) {
      this.debug(ex);
    }
  }
}

CONNECTORTEAM.EXPENSES = {
  timesheetLongpollStart: function()
  {

    if(!CONNECTORTEAM.EXPENSES.timesheetLongPollRunning)
    {
      $JQ.ajax(
      {
        url: '/team/expenses/checkforalerts',
        dataType: 'json',
        success: function(data){
          CONNECTORTEAM.EXPENSES.timesheetLongpollComplete(data)
        }
      });
      CONNECTORTEAM.EXPENSES.timesheetLongPollRunning = true;
    }

  },

  timesheetLongpollComplete: function(data)
  {
    CONNECTORTEAM.EXPENSES.timesheetLongPollRunning = false;
    if(data.is_alert == true)
    {
      CONNECTORTEAM.EXPENSES.updateRightColumnAlert(data.alert);
    } else {
      CONNECTORTEAM.EXPENSES.updateRightColumnAlert(data.alert, true);
    }

    CONNECTORTEAM.EXPENSES.timesheetLongpollStart();

  },

  updateRightColumnAlert: function(message, alertclear) {
    alertElement = $JQ('.bodyRight').find('.sectionExpenses').find('a');
    alertElement.html(message);
    if(alertclear)
    {
      alertElement.removeClass('pink');
      alertElement.addClass('green');
    } else {
      alertElement.removeClass('green');
      alertElement.addClass('pink');
    }

  }
}

CONNECTORTEAM.APPLICATIONS = {
  initialize: function()
  {
    CONNECTORTEAM.APPLICATIONS.bindEvents();
    $JQ('.ajax-loader').hide();
    ajaxLoader = document.createElement('img');
    $JQ(ajaxLoader).attr('src', '/images/team/icons/ajax-loader.gif');
    $JQ(ajaxLoader).hide();
    $JQ(ajaxLoader).addClass('ajax-loader')
    //$JQ('.application-select').closest('td').appendChild(ajaxLoader);
    $JQ('.application-select').closest('td').append(ajaxLoader);
  },

  bindEvents: function()
  {
    $JQ('.application-select').bind('change', CONNECTORTEAM.APPLICATIONS.updateApplicationStatus);
  },

  updateApplicationStatus: function() {
    application = $JQ(this)
    applicationId = $JQ(this).attr('id').replace('application-select-', '');
    $JQ(application).hide();
    loaderImage = $JQ(application).parents('tr.application-row').find('.ajax-loader');
    //loaderImage = $JQ('.ajax-loader');
    $JQ(loaderImage).show();
    $JQ.ajax({
      type: "GET",
      url: '/team/ajax/applicationstatusupdate/id/' + applicationId,
      data: {
        status: $JQ(this).val()
        },
      type: 'POST',
      success: function() {
        if($JQ(application).val() == 'Yes')
        {
          $JQ(application).parents('tr.application-row').toggleClass('accepted-application');
          $JQ(application).parents('tr.application-row').removeClass('not-accepted-application')
        }
        else if($JQ(application).val() == 'No')
        {
          $JQ(application).parents('tr.application-row').removeClass('accepted-application')
          $JQ(application).parents('tr.application-row').toggleClass('not-accepted-application');
        } else {
          $JQ(application).parents('tr.application-row').removeClass('accepted-application')
          $JQ(application).parents('tr.application-row').removeClass('not-accepted-application');
        }
        
        $JQ(application).show();
        $JQ(loaderImage).hide();

      }
    });
  }
}