Drupal.behaviors.spiritBehaviors = function (context) {
	gallerycontainer = $('#gallery .view-content');
	if (gallerycontainer && gallerycontainer.length) {
 	   gallerycontainer.masonry({
			singleMode: true, 
		    itemSelector: '.node' 
		});
	}
	
	$(document).unbind('fb_connect_status', FB_Connect.statusHandle);

	$(document).bind('fb_connect_status', function(e, data) {
		if (data.changed) {
		    // Status has changed, user has logged in or logged out.
			refreshform();
		}
		return false;
	});
};

function refreshform() {
		/*url: "/contestentry/refresh",*/
	$.ajax(
  	{
    	type: "POST",
		url: Drupal.settings.basePath + "contestentry/refresh",
		cache: false,
		success: function(data) {
			var result = Drupal.parseJson(data);
		  	$("#fb-connect-wrapper").html(result['html']);
			Drupal.behaviors.fb_connect($("#fb-connect-wrapper"));
			
			var user_info = result['user_info'];
			if (user_info) {
				$('#edit-field-display-name-0-value')[0].value = user_info[0]['first_name'];
				$('#edit-field-first-name-0-value')[0].value = user_info[0]['first_name'];
				$('#edit-field-last-name-0-value')[0].value = user_info[0]['last_name'];
				$('#edit-field-email-0-email')[0].value = user_info[0]['email'];
        $("#join-now").slideUp();
			}
		}
  	});
}

Drupal.behaviors.setupEventHandlers = function(context) {
	$('#header-tell-us > a', context).bind('click', enterButtonHandler);
	$('#footer-tell-us > a', context).bind('click', enterButtonHandler);
	$('a.enter-now', context).bind('click', enterButtonHandler);
	if (openEnterForm && openEnterForm == true) enterButtonHandler();
	
	$('#entry-form-container .close-btn', context).bind('click', function(){
	  	$('#entry-form').slideUp();
	});
	
	$('.add-photo-button', context).bind('click', function() {
		$('#add-photo-container').slideToggle('fast');
		return false;
	});
	
	$('.join-here-button', context).bind('click', function() {
		$('#join-here-container').slideToggle('fast');
		return false;
	});
	
	$('#edit-field-passage-0-value').bind('focus', function() {
		//if (this.defaultValue == this.value) {
		if (this.value == "Your answer here - 300 character limit\n(approx. 60 words or less)") {
			this.value = '';
		}
	});
	$('#edit-field-passage-0-value').bind('blur', function() {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	});
	//$('#edit-field-passage-0-value').bind('keydown keyup', checkLength);
	$('#edit-field-passage-0-value').keyup(checkLength);
/*
	$('#edit-field-passage-0-value').keyup(function() {
      limitChars('edit-field-passage-0-value', 300, '.textarea-top');
      });
*/
};

function checkLength(){
    var text = $(this).val();
    if (text.length > 300) {
        $(this).val(text.substr(0,299));
        return false;
    }
    return true;
}

function limitChars(textid, limit, infodiv) {
  var text = $(textid).val(); 
  var textlength = text.length;
  if(textlength > limit) {
    $(infodiv).html('You cannot write more then '+limit+' characters!');
    $(textid).val(text.substr(0,limit));
    return false;
  }
  else {
    $(infodiv).html('You have '+ (limit - textlength) +' characters left.');
    return true;
  }
}

function enterButtonHandler() {
	document.documentElement.scrollTop = $('#header-container').height()-10; //firefox
	document.body.scrollTop = $('#header-container').height()-10; // safari/chrome
	
	if (!$('#entry-form').is(':visible')) {
		$('#entry-form').slideDown('slow', function() {});
	}
  return false;
}


function publish_to_facebook(message, attachment, action_link) {
  if (FB.Connect.get_loggedInUser()) {
    FB.Connect.streamPublish(message, attachment, action_link);
    FB.Connect.showPermissionDialog("email", function(perms) {
      if (!perms) {

      // NOT IMPLEMENTED - if user refuses we should tell them that if we can't contact them, they can't win.
        //continue_without_permission();
      //} else {
        //save_session();
      }
    });
  }
};


/**
 * Custom form handler
 * 
 * @param {String} hook
 * @param {Object} args
 * @return {Bool}
 */

Drupal.Ajax.plugins.contestentry = function(hook, args) {
  	if (hook === 'complete') {
		if (args.options) {
			var passage = args.options.entry_passage;
			var image = unescape(args.options.entry_image);
			var link = unescape(args.options.entry_link); // need to unescape because drupal url encoded the url, fb does not like this
			var contest_link = "http://www.spiritofvancouver.com/contest";
			
			if (image && image.length > 0) {
	    		publish_to_facebook('', {
					'name':'What is the Spirit of Vancouver?',
					'href':link,
					'description':passage,
					'media': [{'type':'image','src':image,'href':link}]
					},
					[{'text':'Join the contest','href':contest_link}]	
				);
			}
			else {
				publish_to_facebook('', {
					'name':'What is the Spirit of Vancouver?',
					'href':link,
					'description':passage
					},
					[{'text':'Join the contest!','href':contest_link}]
				);
			}
		}
	}
	else if (hook === 'message') {
		document.documentElement.scrollTop = $('#header-container').height();
		document.body.scrollTop = $('#header-container').height(); // safari/chrome
	}
	
	else if (hook === 'scrollFind') {
		if (args.container.id === 'main') {
	      return false;
	    }
	    else {
	      return true;
	    }
	}
	return true;
}

