// 
// Constants
//
var loc_scripts_base = 'http://creative.kickstatic.com/shape/kickapps/widgets/newsletters';

// Newsletter settings
//
// NOTE: This is now in http://www.shape.com/ka/js/newsletters.js
//
// var newslettersJSON = { "newsletter": [ { "label": "Shape Your Life", "id": 1, "ischecked" : "no" }, { "label": "Shape Your Look", "id": 2, "ischecked" : "no" }, { "label": "Eat Right, Get Fit, Live Healthy", "id": 3, "ischecked" : "no" }, { "label": "Partner Promotions", "id": 4, "ischecked" : "no" } ] };
					
// 
// Newsletter handling
//
function displayNewsletterInfo (displayJSON) {
	
	var nlHTML;
	
	nlHTML = '<div id="newsletters">';
	nlHTML = nlHTML + '<label for="Newsletters">Newsletters:</label>';
	
	// Loop through the options
	dnOptions = displayJSON.newsletter;
	for (x in dnOptions)
	{
		if (dnOptions.hasOwnProperty(x)) {
			nlHTML = nlHTML + '<input type="checkbox" id="newsletter_' + dnOptions[x].id + '" name="newsletters" value="' + dnOptions[x].label + '"';
			if (dnOptions[x].ischecked == "yes") {
				nlHTML = nlHTML + ' checked="' + dnOptions[x].ischecked + '"';
			}
			nlHTML = nlHTML + '> '+ dnOptions[x].label + '<br />';
		}
	}	
	nlHTML = nlHTML + '</div>';
	
	return nlHTML;

}

function setNewsletterInfo (settingJSONStr) {
	
	var varid;
	var settingJSON;

	// Build the JSON object
	try {
		settingJSON = eval("(" + settingJSONStr + ')');
	} catch (e) {
		settingJSON = newslettersJSON;
	}

	// alert(JSON.stringify(settingJSON));

	// Loop through the options
	dnOptions = settingJSON.newsletter;
	for (x in dnOptions)
	{
		if (dnOptions.hasOwnProperty(x)) {
			varid = "newsletter_" + dnOptions[x].id;
			if (dnOptions[x].ischecked == "yes") {
				$j('input[id=' + varid + ']').attr('checked', true);
			}
			else {
				$j('input[id=' + varid + ']').attr('checked', false);
			}
		}	
	}	
}

function getNewsletterInfo (displayJSON) {

	var newsletterJSON;
	
	newsletterJSON = '';
	
	// Loop through the options to build the JSON string with the settings
	dnOptions = displayJSON.newsletter;
	for (x in dnOptions)
	{
		if (dnOptions.hasOwnProperty(x)) {
			if (newsletterJSON != '') {
				newsletterJSON = newsletterJSON + ', ';
			};
			varid = "newsletter_" + dnOptions[x].id;
			if ($j('input[id=' + varid + ']').attr('checked')) {
				newsletterJSON = newsletterJSON + '{ "id": ' + dnOptions[x].id + ', "ischecked" : "yes" }';
			}
			else {
				newsletterJSON = newsletterJSON + '{ "id": ' + dnOptions[x].id + ', "ischecked" : "no" }';
			}
		}	
	}	
	newsletterJSON = '{ "newsletter": [ ' + newsletterJSON + ' ] }';
	
	return newsletterJSON;

}

// Add in Registration Information
if (Ka.Info.PAGE == "login/registerUser.jsp") {
    $j('#ka_joinDOB').after('<li>' + displayNewsletterInfo(newslettersJSON) + '</li>');
}

// Handle Edit Profile Page
if (Ka.Info.PAGE == "pages/manageProfileQuestions.jsp") {
	
	// Hide answer 5
	$j('.ka_supplementalQuestions:eq(4)').css("display", "none");
	
	// Display the check boxes
    $j('.ka_supplementalQuestions:eq(4)').before(displayNewsletterInfo(newslettersJSON));
	
	// Set the check boxes
	setNewsletterInfo($j('#PQ5').val());
	
	// Setup the on change handler to set answer 5 when a check box changes
	$j("#newsletters").change( function() {
		$j('#PQ5').val(getNewsletterInfo(newslettersJSON));
	});

}

// Handle profile page
if (Ka.Info.PAGE == "pages/kickPlaceServerSide.jsp") {
	// Hide extra answers
	$j('#ka_profileAboutMeExt').css("display", "none");
}

// 
// Cookie Handling Routines
//
function getCookieValue (cookieName) {
	return Ka.Cookie.read(cookieName);
}

function writeSessionCookie (cookieName, cookieValue) {
	Ka.Cookie.create(cookieName, cookieValue, 7);
}

function deleteCookie (cookieName) {
	Ka.Cookie.erase(cookieName);
}

// 
// Handle additional registration fields save
//
function cleanupCookies() {
	deleteCookie("newsletters");
	deleteCookie("email");	
	deleteCookie("password");	
}

// Handle the JSONRequest Response
function profResponse(response, message) {

	if (response != 'GOOD') {
		alert(message);
	}

	// Cleanup the cockies if saved
	cleanupCookies()	
}

function saveNCRegistration() {
	var passedParams = '';
	
	if (Ka.Info.USERID != '') {
	
		// Get the user information
		var username = Ka.Info.USERNAME;
		var userid = Ka.Info.USERID;
	
		// Read From the cookie
		var newsletters = getCookieValue("newsletters");
		var email = getCookieValue("email");
		var password = getCookieValue("password");
		
		// Setup the user info.
		passedParams = passedParams + '&username=' + escape(username);
		passedParams = passedParams + '&userid=' + escape(userid);
		passedParams = passedParams + '&email=' + escape(email);
		passedParams = passedParams + '&password=' + escape(password);
		passedParams = passedParams + '&newsletters=' + escape(newsletters);

		// Handle the update
		request = loc_scripts_base + '/saveprofile.php?callback=profResponse' + passedParams;

		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
		aObj.addScriptTag();
		
	}
}

// 
// Handle the setting and saving of the registration fields
//
if (window.location.href.indexOf('displayMyPlace') != -1) {
	var hasProfInfo = getCookieValue('newsletters');
	if (hasProfInfo != null && hasProfInfo != '') {
		saveNCRegistration();
	}
}

function setProfileCookies(){
	
	// Custom Fields
	var newsletters;
	var email = document.getElementById("email").value;
	var password = document.getElementById("password").value;
	
	newsletters = getNewsletterInfo(newslettersJSON);
	
	// Write to the cookies
	writeSessionCookie('newsletters', newsletters);
	writeSessionCookie('email', email);
	writeSessionCookie('password', password);

	// Submit the form
	document.RegisterUser.submit();
} 

function setNCRegistration() {
	
	// Read From the cookies
	nlsettingsJSON = getCookieValue("newsletters");
	document.getElementById("email").value = getCookieValue("email");
	setNewsletterInfo(nlsettingsJSON);

}

// Put the cookie setting function into effect
$j(document).ready(function() {
	if (Ka.Info.PAGE == 'login/registerUser.jsp') {
		$j('#RegisterUser').attr('onvalid','setProfileCookies');

		// Check to see if was an error and refill in the fields
		// if the cookies are still there
		var hasProfInfo = getCookieValue('newsletters');
		if (hasProfInfo != null && hasProfInfo != '') {
			setNCRegistration();
		}
	}
});