
// TODO2 handle no js
// TODO2 refactor; not DRY

// Get username & pass from cookie
var ATUser = {
	username: false,
	enc_pass: false,
	getUserFromCookie: function() {
		var atco_cookie = jQuery.cookie('atco_session');
		if(atco_cookie) {
			var atco_cookie_values = atco_cookie.split('/');
			if(atco_cookie_values.length > 1) {
				this.username = atco_cookie_values[0];
				this.enc_pass = atco_cookie_values[1];
			}			
		}
	}
};

ATUser.getUserFromCookie();

jQuery(document).ready(function(){
	// Giveaway forms ---------------------------------------------------
	jQuery('.giveaway2009-entry').each(function(){
    var entry_id = jQuery(this).attr('id').substr(13);
    
    var url = 'http://'+ document.domain;
    url += location.port?':'+location.port:'';
    url += '/prox/?proxy_subdomain=giveaways&proxy_path=/entry/get_entry_form&gift_id='+ entry_id +'&username='+ ATUser.username +'&encpass='+ ATUser.enc_pass;
    var formContainer = jQuery(this);
    jQuery(this).load(url, function(){ 
      // handle form submit
      jQuery('#giveaway2009-entryform-'+ entry_id)
        .validate({
          rules: {
            email: { required: true, email: true },
            first: { required: true, minlength: 1 },
            last: { required: true, minlength: 3 },
            address1: { required: true},
            city: { required: true},
            state: { required: true, minlength: 2, maxlength: 2},
            zip: { required: true, minlength: 5 }                
          },
          submitHandler: function(form) {
            // build base AJAX URL
            var url = 'http://'+ document.domain;
            url += location.port?':'+location.port:'';
            url += '/prox/?proxy_subdomain=giveaways&proxy_path=/entry/enter';
            // assembled POST data
            var data = { username: ATUser.username, encpass: ATUser.enc_pass }
            var form_fields = ['email','first','last','address1','address2','city','state','zip','gift_id'];
            for(f in form_fields) {
              var field = form_fields[f];
              var val = jQuery(form).find('input[name='+field+']').val();
              if(val != undefined && val != '') data[field] = encodeURIComponent(val);
            }
            var opt_ins = [];
            jQuery('#giveaway2009-entryform-'+ entry_id +' input:checkbox.opt_in').each(function(){
            	var opt_in = jQuery(this).attr('name');
							if(!opt_in.match(/^function/)) data[opt_in] = jQuery(this).attr('checked')?1:0; // avoid capturing Prototype.js garbage
							data[opt_in] = jQuery(this).attr('checked')?1:0;
						});
            jQuery.ajax({
              url: url,
              type: 'GET',
              data: data,
              success: function(data) {
                formContainer.html(data);
              }
            });
            
            return false;
           }
        }); // form activation
    }); // .load get_entry_form
  }); // entry.each
  

	// Thumbs up --------------------------------------------------------
	// deactivate all thumbsup buttons until counts load
	jQuery('.thumb_button').removeClass('active_thumb_button').addClass('inactive_thumb_button').click(function(){return false;});
	
	// Add a hidden div for displaying modal messages
	jQuery('body').append('<div class="jqmWindow" id="thumbsUpError"><p class="jqmCloseWrapper"><a href="#" class="jqmClose">X</a></p><p class="message"></p></div>');
	jQuery('#thumbsUpError').jqm();

	// Get list of entry ids & set them in the .data() attribute for each container
	var entry_ids = [];
	var scc2009_entry_ids = [];
	var ohscc2009_entry_ids = [];
	var igc2009_entry_ids = [];
	var ohcolor2009_entry_ids = [];
	var kitchnqwm2009_entry_ids = [];

	jQuery('.thumb_container').each(function(){
		var entry_id = jQuery(this).attr('id').substr(9);
		var contest='jj2009';
		if(jQuery(this).hasClass('contest-scc2009')) contest = 'scc2009';
		if(jQuery(this).hasClass('contest-ohscc2009')) contest = 'ohscc2009';
		if(jQuery(this).hasClass('contest-igc2009')) contest = 'igc2009';
		if(jQuery(this).hasClass('contest-ohcolor2009')) contest = 'ohcolor2009';
		if(jQuery(this).hasClass('contest-kitchnqwm2009')) contest = 'kitchnqwm2009';

		jQuery(this).data('entry_id', entry_id);
		jQuery(this).data('contest', contest);
		if(contest === 'jj2009') {
			entry_ids.push(entry_id);			
		}
		else if( contest === 'scc2009') {
			scc2009_entry_ids.push(entry_id);			
		}
		else if( contest === 'ohscc2009') {
			ohscc2009_entry_ids.push(entry_id);
		}
		else if( contest === 'igc2009') {
			igc2009_entry_ids.push(entry_id);
		}
		else if( contest === 'ohcolor2009') {
			ohcolor2009_entry_ids.push(entry_id);
		}
		else if( contest === 'kitchnqwm2009') {
			kitchnqwm2009_entry_ids.push(entry_id);
		}

	});
	
	if(entry_ids.length > 0) {

		// Update jj2009 counts / activate buttons
		jQuery.ajax({
			url: 'http://thumbsup.apartmenttherapy.com/jj2009/thumbCount',
			data: { entry_ids: entry_ids.join(','), username: ATUser.username },
			dataType: 'jsonp',
			jsonp: 'jsonpcallback',

			success: function(data) {
				jQuery.each(data, function(entry_id, message) {
					jQuery('#thumbsup-'+entry_id+' .num').html(message.count +"");
					// If haven't voted, enable button
					if(message.voted === 'false') {
						jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('inactive_thumb_button').addClass('active_thumb_button').click(handleVote);
					}
				});
			}

		}); // end ajax thumbCount
	}
	
	if(scc2009_entry_ids.length > 0) {
		// Update scc2009 counts / activate buttons
		jQuery.ajax({
			url: 'http://thumbsup.apartmenttherapy.com/scc2009/thumbCount',
			data: { entry_ids: scc2009_entry_ids.join(','), username: ATUser.username },
			dataType: 'jsonp',
			jsonp: 'jsonpcallback',

			success: function(data) {
				jQuery.each(data, function(entry_id, message) {
					jQuery('#thumbsup-'+entry_id+' .num').html(message.count +"");
					// If haven't voted, enable button
					if(message.voted === 'false') {
						jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('inactive_thumb_button').addClass('active_thumb_button').click(handleVote);
					}
				});
			}

		}); // end ajax thumbCount
		
	}	

	if(ohscc2009_entry_ids.length > 0) {
		// Update ohscc2009 counts / activate buttons
		jQuery.ajax({
			url: 'http://thumbsup.apartmenttherapy.com/ohscc2009/thumbCount',
			// url: 'http://localhost:4567/thumbCount',
			data: { entry_ids: ohscc2009_entry_ids.join(','), username: ATUser.username },
			dataType: 'jsonp',
			jsonp: 'jsonpcallback',

			success: function(data) {
				jQuery.each(data, function(entry_id, message) {
					jQuery('#thumbsup-'+entry_id+' .num').html(message.count +"");
					// If haven't voted, enable button
					if(message.voted === 'false') {
						jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('inactive_thumb_button').addClass('active_thumb_button').click(handleVote);
					}
				});
			}

		}); // end ajax thumbCount
		
	}	

	if(igc2009_entry_ids.length > 0) {
		// Update igc2009 counts / activate buttons
		jQuery.ajax({
			url: 'http://thumbsup.apartmenttherapy.com/igc2009/thumbCount',
			data: { entry_ids: igc2009_entry_ids.join(','), username: ATUser.username },
			dataType: 'jsonp',
			jsonp: 'jsonpcallback',

			success: function(data) {
				jQuery.each(data, function(entry_id, message) {
					jQuery('#thumbsup-'+entry_id+' .num').html(message.count +"");
					// If haven't voted, enable button
					if(message.voted === 'false') {
						jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('inactive_thumb_button').addClass('active_thumb_button').click(handleVote);
					}
				});
			}

		}); // end ajax thumbCount
		
	}	

	if(ohcolor2009_entry_ids.length > 0) {
		// Update ohcolor2009 counts / activate buttons
		jQuery.ajax({
			url: 'http://thumbsup.apartmenttherapy.com/ohcolor2009/thumbCount',
			data: { entry_ids: ohcolor2009_entry_ids.join(','), username: ATUser.username },
			dataType: 'jsonp',
			jsonp: 'jsonpcallback',

			success: function(data) {
				jQuery.each(data, function(entry_id, message) {
					jQuery('#thumbsup-'+entry_id+' .num').html(message.count +"");
					// If haven't voted, enable button
					if(message.voted === 'false') {
						jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('inactive_thumb_button').addClass('active_thumb_button').click(handleVote);
					}
				});
			}

		}); // end ajax thumbCount
		
	}	

	if(kitchnqwm2009_entry_ids.length > 0) {
		// Update kitchnqwm2009 counts / activate buttons
		jQuery.ajax({
			url: 'http://thumbsup.apartmenttherapy.com/kitchnqwm2009/thumbCount',
			// url: 'http://localhost:4567/thumbCount',
			data: { entry_ids: kitchnqwm2009_entry_ids.join(','), username: ATUser.username },
			dataType: 'jsonp',
			jsonp: 'jsonpcallback',

			success: function(data) {
				jQuery.each(data, function(entry_id, message) {
					jQuery('#thumbsup-'+entry_id+' .num').html(message.count +"");
					// If haven't voted, enable button
					if(message.voted === 'false') {
						jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('inactive_thumb_button').addClass('active_thumb_button').click(handleVote);
					}
				});
			}

		}); // end ajax thumbCount
		
	}	
	
});

var handleVote = function() {
	// basic logged in check
	ATUser.getUserFromCookie();
	if(!ATUser.username) {
		jQuery('#thumbsUpError .message').html('You must be logged in to vote. <a href="http://community.apartmenttherapy.com/com/SignUp" target="_blank"><br /><br />Click here to <strong>register</strong> a new account</a>.<br /><br />If you already have an account, login on the comment form of any post.');
		jQuery('#thumbsUpError').jqmShow();
		return false;
	}
	
	// Attempt to record vote
	var entry_id = jQuery(this).parent('div.thumb_container').data('entry_id');
	var contest = jQuery(this).parent('div.thumb_container').data('contest');

	jQuery.ajax({
		url: 'http://thumbsup.apartmenttherapy.com/'+contest+'/recordThumb',
		// url: 'http://localhost:4567/recordThumb',
		data: { username: ATUser.username, enc_pass: ATUser.enc_pass, entry_id: entry_id },
		dataType: 'jsonp',
		jsonp: 'jsonpcallback',
		
		success: function(data) {
			if(data.status === 'success') {
				jQuery('#thumbsup-'+entry_id+' .num').fadeOut('slow',function(){
					// Update vote counts
					// this sometimes incorrectly returns a count of 1: 
					// jQuery(this).html(data.count +"").fadeIn('slow');
					// fake it:
					var count = parseInt(jQuery('#thumbsup-'+entry_id+' .num').html()) + 1;
					jQuery(this).html(count +"").fadeIn('slow');					
				});
				jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('active_thumb_button').addClass('inactive_thumb_button').unbind('click',handleVote).click(function(){return false;});
			}
			else if(data.status === 'error') {
				if(data.message === "already voted") {
					jQuery('#thumbsup-'+entry_id+' .thumb_button').removeClass('active_thumb_button').addClass('inactive_thumb_button').unbind('click',handleVote).click(function(){return false;});						
				}
				else if(data.message === 'User not verified') {
					jQuery('#thumbsUpError .message').html('Your user account has not been verified.<br /><br />When you signed up, we sent you an email with a link you must click to complete verification; <a href="http://community.apartmenttherapy.com/com/RegisterEmail" target="_blank">click here to <strong>resend</strong> your verfication email.</a>.');
					jQuery('#thumbsUpError').jqmShow();
				}
				else if(data.message === 'voting closed') {
					jQuery('#thumbsUpError .message').html('Thumbs Up voting for this entry is closed.');
					jQuery('#thumbsUpError').jqmShow();					
				}
				// 'User not found' 'Missing username or password' 'User is banned' 'Incorrect password' or other unknown error
				else {
					jQuery('#thumbsUpError .message').html('Oops. We had a problem recording your vote.<br /><br />Please <a href="http://www.apartmenttherapy.com/superlogout" target="_blank">click here to <strong>logout</strong></a>, and then reload this page and log back in (or register) on the comment form of any post.');
					jQuery('#thumbsUpError').jqmShow();
				}
			}
		}
		
	});
	return false;
}