
$(function() {
  globalBehaviours(document);
});

function globalBehaviours(context) {
	pym.community.behaviours.bind(context);
}

var pym = {
	community: {
		
	  venueSelected: function(options, callback) {
		    var urlTemplate = '/community/event_venues/create/?activity_id={activity_id}';

		    $.ajax({
		      url: options.url || urlTemplate.substitute({activity_id:options.activityId}),
		      dataType: 'script',
		      success: callback,
			     data: {
	        		'venue[name]': options.name,
			        'venue[address]': options.address || '',
			        'venue[postcode]': options.postcode || '',
			        'venue[latitude]': options.latitude,
			        'venue[longitude]': options.longitude
	      		}
	    	});
	  	},
		
		behaviours: {
			local: [],
		
			registerLocal: function(f) {
				pym.community.behaviours.local.push(f);
			},
			bind: function(context) {
				
    	  $('.act-interactive-search', context).click(function() {
		       var target = $('.venue-input', $(this).parents('form:first'))[0].id;
		       window.open('/community/business/local_search?activityId=' + target.replace(/venue-input-/,''), '_blank', 'width=680,height=504');
		       return false;
		    });

 			  $('.ajax-destroy', context).click(function() {
			    if(!$(this).hasClass('confirm') || confirm('Are you sure?')) {
			      $.ajax({
			        dataType: 'script',
			        type: 'POST',
			        url: $(this).attr('href')
			      });
			    }
			    return false;
			  });

			  $('.ajax-link', context).click(function() {
			    $.ajax({
			      dataType: 'script',
			      url: this.href,
			      beforeSend: function(xhr) {
			        xhr.setRequestHeader("Accept", "text/javascript");
			      }
			    });
			    return false;
			  });
			
		    $('a.ajax-post', context).click(function() {      
		      if(!$(this).hasClass('confirm') || confirm('Are you sure?')) {
		      $.ajax({
		        type: "POST",
		        url: $(this).attr('href'),
		        dataType: 'script',
		        beforeSend: function(xhr) {
		          xhr.setRequestHeader('Accept', 'text/javascript');
		        }        
		      });

		      }
		      return false;
		    });
	
			  $('.ajax-form', context).ajaxForm({
				type: 'GET',
			    dataType: 'script',
				beforeSubmit: function(data, form, options) {
					$('.ajax-form input:image, .ajax-form input:submit').attr('disabled',true);
				},
				success: function() {
					$('.ajax-form input:image, .ajax-form input:submit').attr('disabled', false);
				}
			  });

			  $('.rating-bar').starBar();

				$('.business-panel-review', context).each(function() {
					var reviewItem = this;
					var reviewId = reviewItem.id.split('-').pop();
					$('.review-rating a', this).click(function() {
						var score = $(this).hasClass('yes') ? 1 : -1;
						$.ajax({
							url: '/community/reviews/rate',
							data: {score: score, id: reviewId},
							dataType: 'script',
							beforeSend: function(xhr) {
								xhr.setRequestHeader('Accept', 'text/javascript');
							},
							type: 'POST'
						});
						return false;
					});
					$('.flag-review', this).click(function() {
						var me = this;
						if (confirm("Are you sure you wish to report this review?")) {
							$.ajax({
								url:'/community/reviews/flag', 
								data:{id: reviewId},
								type: 'POST',
								dataType: 'script',
								beforeSend: function(xhr) {
									xhr.setRequestHeader('Accept', 'text/javascript');
								}
							});
						}
					});
				});
				
				$('input.memo').each(function() {
				   var val = $(this).val();
				   $(this).focus(function() { if ($(this).val() == val) $(this).val(''); }); 
				   $(this).blur(function() { if ($(this).val() == '') $(this).val(val); }); 
				});

				$('.open-dialog').click(function() {
					window.open(this.href, '_blank', 'width=720,height=504,status=no,toolbar=no,menubar=0,resizable=0,scrollbars=0');
					return false;
				});

				$('.favourites-list li', context).click(function() {
					window.location = $('a:first', this).attr('href');
				});
				
				for(var i = 0; i < pym.community.behaviours.local.length; i++) {
					pym.community.behaviours.local[i](context);
				}
			}
		}
	}
};

function substitute(string, subs, esc) {
  return string.replace(/\{(\w+)\}/g, function(matches, index) {
    var val = '' + typeof(subs[index]) == 'undefined' ? '' : subs[index];
    if(typeof(val) == 'string' && esc) {
      val = val.replace("'", '&#39;').replace('"', '&#34;');
    }
    return esc ? val : val;
  });
};

String.prototype.substitute = function(subs, esc) {
	return substitute(this, subs, esc);
}

/* Photo upload form handling */

$(function() {
	var index = 0;
  var template = "<li>";
  template += "<p><input type='file' name='photo[{index}][uploaded_data]' /></p>";
  template += "<p><input type='text' size='30' name='photo[{index}][caption]' class='default' value='Enter title here' /> <input type='text' size='60' name='photo[{index}][description]' class='default' value='Enter description here' /></p>";
  template += "</li>";

  $('#actuator-add-photo').click(function() {
    if($('#photo-input-list li').size() >= 3) {
      alert('Only three photos may be uploaded at a time');
    } else {
      var html = $(template.replace(/\{index\}/g, index++));

      $('input.default', html).each(function() {
        var defaultText = $(this).val();
        $(this).focus(function() {
          if($(this).val() == defaultText) {
            $(this).val('');
            $(this).removeClass('default');
          }
        }).blur(function() {
          if($(this).val() == '') {
            $(this).val(defaultText);
            $(this).addClass('default');
          }
        });
      });
      $('#photo-input-list').append(html);
    }
    return false;
  });

  $('form').submit(function() {
    $('input.default', this).val('');
    $("input[name$='[caption]']", this).each(function(v) {
      if($(this).val() == '') {
        var li = $(this).parents('li:first');
        var f = $("input[name$='[uploaded_data]']", li).val();
        if(f && f.length > 0) {
          var filename = f.split(/[\/\\]/);
          filename = filename[filename.length-1];
          filename = filename.replace(/\.(.+)$/, '');
          $(this).val(filename);
        }
      }
    });
  });
  
  $('#actuator-add-photo').click();
});
