NewsletterForm = function() {
	this.options = []
}

NewsletterForm.prototype.bindEvents = function() {
	jQuery('#email').focus(function() {
		if (jQuery(this).val() == 'enter email address') {
			jQuery(this).val('')
		}
	})
	
	jQuery('#email').blur(function() {
		if (jQuery(this).val() == '') {
			jQuery(this).val('enter email address')
		}
	})
	
	jQuery('.option_box').click(function() {
		var index = jQuery(this).attr('id').split('_')[1]
		var group =  (jQuery(this).is(':checked')) ? jQuery("#available_group_" + index).val() : null
		var interest = (jQuery(this).is(':checked')) ? jQuery("#available_interests_" + index).val() : null
		jQuery("#group_"+index).val(group)
		jQuery("#interest_"+index).val(interest)
	})
	
	var options = this.options
	
	jQuery("#multiple_newsletter_form").validate({
    	invalidHandler: function(form, validator) {
        	jQuery('#email').css("border-color", "#ffcb68")
        }
		,submitHandler: function(form) {
			jQuery('#email').css("border-color", "#7C7D7D")
			var email = jQuery('#email').val()
			for (i in options) {
         		if (typeof options[i].onSubmit !== "undefined" && options[i].onSubmit !== null && options[i].isChecked()) {
         			options[i].onSubmit(email)
         		}
         	}
			jQuery.ajax({
         		type: "POST",
         		url: jQuery(form).attr('action'),
         		data: jQuery(form).formSerialize(),
         		success: function(resp) {
         			setTimeout(function() {
         				jQuery(location).attr('href',"http://support.thirteen.org/site/PageNavigator/Registration_Thanks")
         			})
         		}
       		})
			return false;
		}	
        ,rules: {
            "email": {
            	required: true,
                email: true
            }
        }
        ,messages: {
            "email": "please enter a valid address"
        }
        ,errorElement: "div"	
    })	
}

NewsletterForm.prototype.add = function(item) {
	var $element = this.addElement(jQuery("#newsletteraccordion .option.prototype"), { $appendTo: jQuery("#newsletteraccordion") }) 
	var $popup = this.addElement(jQuery("#newsletteraccordion .optionPopup.prototype"), { $appendTo: jQuery("#newsletteraccordion") }) 
	item.populateHtml($element, $popup)
	this.options.push(item)
}

NewsletterForm.prototype.addElement = function($prototype, options) {
    if (typeof options !== "undefined" && options !== null && typeof options.$appendTo !== "undefined" && options.$appendTo !== null) {
		var $element = $prototype.clone().appendTo(options.$appendTo)
	} else {
		var $element = $prototype.clone().before($prototype)
	}
	$element.removeClass("prototype")
	$element.addClass("from_data")
	$element.show()
	return $element
}

NewsletterForm.prototype.activateAccordion = function() {

	jQuery("#newsletteraccordion h3 input").click(function(evt) {
		evt.stopPropagation()
    }) 		
		
	/*jQuery('.accordion .head').click(function() {
	
		jQuery(this).next().toggle('slow')
		return false
	}).next().hide()*/
	
	jQuery('#newsletteraccordion').accordion({
    	active: false,
    	collapsible: true            
	})
}

ConvioOption = function(id, name, opts) {
	this.id = id
	this.name = name
	this.groups = opts.groups
	this.interests = opts.interests
	this.popupTitle = opts.popupTitle
	this.popupBody = opts.popupBody	
	this.checkedByDefault = (typeof opts.checked !== "undefined" && opts.checked !== null && opts.checked)
}

ConvioOption.prototype.populateHtml = function($element, $popup) {
	this.$element = $element
	$element.attr("id", "option_" + this.id)
	$popup.attr("id", "popup_" + this.id)
	$element.find(".optionName").text(this.name)
	$element.find(".option_box").attr("id", "option_" + this.id)
	$popup.find(".popupTitle").text(this.popupTitle)
	$popup.find(".popupBody").text(this.popupBody)
	if (this.checkedByDefault) {
		$element.find(".option_box").attr('checked','checked')
	}
	jQuery('<input>').attr({
    	type: 'hidden',
    	id: 'available_group_'+this.id,
    	name: 'available_group['+this.id+']',
    	value: this.joinArray(this.groups)
	}).prependTo($element)
	jQuery('<input>').attr({
    	type: 'hidden',
    	id: 'available_interests_'+this.id,
    	name: 'available_interests['+this.id+']',
    	value: this.joinArray(this.interests)
	}).prependTo($element)
	jQuery('<input>').attr({
    	type: 'hidden',
    	id: 'group_'+this.id,
    	name: 'group['+this.id+']'
	}).prependTo($element);
	jQuery('<input>').attr({
    	type: 'hidden',
    	id: 'interest_'+this.id,
    	name: 'interests['+this.id+']'
	}).prependTo($element);
}

ConvioOption.prototype.joinArray = function(arr) {
	var str = ""
	for (i in arr) {
		str += arr[i]
		if (i < arr.length - 1) {
			str += ","
		}
	}
	return str;
}

ConvioOption.prototype.isChecked = function() {
	return this.$element.find(".option_box").is(':checked')
}

ConstantContactOption = function(id, name, opts) {
	this.id = id
	this.name = name
	this.popupTitle = opts.popupTitle
	this.popupBody = opts.popupBody	
	this.checkedByDefault = (typeof opts.checked !== "undefined" && opts.checked !== null && opts.checked)
	this.list = opts.list
	this.source = opts.source
	this.url = opts.url
}

ConstantContactOption.prototype.populateHtml = function($element, $popup) {
	this.$element = $element
	$element.attr("id", "option_" + this.id)
	$popup.attr("id", "popup_" + this.id)
	$element.find(".optionName").text(this.name)
	$element.find(".option_box").attr("id", "option_" + this.id)
	$popup.find(".popupTitle").text(this.popupTitle)
	$popup.find(".popupBody").text(this.popupBody)
	if (this.checkedByDefault) {
		$element.find(".option_box").attr('checked','checked')
	}
}

ConstantContactOption.prototype.onSubmit = function(email) {
	var self = this
	jQuery.ajax({
  		type: 'POST',
  		url: this.url,
  		data: {
  			CC_List: self.list,
  			source: self.source,
  			Email: email
  		},
  		success: function(r) { 
  			console.log("constant contact: email submitted for " + self.name) 
  		},
  		dataType: "html"
	});
}

ConstantContactOption.prototype.isChecked = function() {
	return this.$element.find(".option_box").is(':checked')
}

jQuery(document).ready(function() {
	
	var form = new NewsletterForm()
	
	form.add(new ConvioOption(1, "Program Highlights", {
		checked: true,
		groups: [51202],
		interests: [1606, 2541],
		popupTitle: "THIRTEEN WEEK",
		popupBody: "A rundown of the week ahead - program premieres, special offers, more. Sent Mondays"
	}))
	
	form.add(new ConvioOption(2, "News & Current Affairs", {
		groups: [51203],
		interests: [2222,2541],
		popupTitle: "NEWSTHIRTEEN",
		popupBody: "A roundup of news & current affairs on THIRTEEN, sent Fridays"
	}))
	
	form.add(new ConvioOption(3, "Arts & Culture", {
		groups: [51204],
		interests: [2521, 2541],
		popupTitle: "ARTSTHIRTEEN",
		popupBody: "Music, art, dance & theater on THIRTEEN, sent Tuesdays"
	}))
	
	form.add(new ConvioOption(4, "Saturday Night Films", {
		groups: [51205],
		interests: [2221, 2541],
		popupTitle: "Reel13",
		popupBody: "THIRTEEN's Saturday night classic, indie & short film lineup, sent Wednesdays"
	}))
	
	form.add(new ConvioOption(5, "Kids & Family", {
		groups: [48101],
		interests: [2601],
		popupTitle: "KIDS CLUB THIRTEEN",
		popupBody: "A fun rundown of free & discounted family events in NYC, sent biweekly on Thursdays"
	}))	
	
	form.add(new ConstantContactOption(6, "Local News & Culture", {
		popupTitle: "MetroFocus",
		popupBody: "A roundup of local news and culture in and around New York",
		list: "General Interest",
		source: "thirteen.org",
		url: "/wp-content/common/cc-signup/cc_process/cc_contactsave_metrofocus.php"
	}))
	
	jQuery("#newsletteraccordion .prototype").remove()
	form.activateAccordion()
	form.bindEvents()
	
})
