var saveGiftForm = { flowStatus:-1, saveToWishList:false, productName:"", productId:"", recProfileId:"", recProfileType:-1, recProfileName:"", email:"", pwd:"", optIn:"" };
var saveSearchForm = { flowStatus:-1, searchKey:"", recProfileId:"", recProfileType:-1, recProfileName:"", email:"", pwd:"", optIn:"" };
var saveReminderForm = { flowStatus:-1, holidayId:0, occasionId:0, month:"", day:"", year:"", recProfileId:"", recProfileName:"", recProfileType:-1, recProfileAge:0, recProfileGender:"", email:"", pwd:"", optIn:"" };
var tellAFriendForm = { toName:"", toEmail:"", fromName:"", fromEmail:"", productId:"", ideaId:"" };
var saveBdayReminderForm = { occasionId:1, month:"", day:"", year:"", recProfileId:"", recProfileAge:0, recProfileGender:"" };
var registrationForm = { email:"", pwd:"", optIn:"" };

function resetForms() {
	saveGiftForm = { flowStatus:-1, saveToWishList:false, productName:"", productId:"", recProfileId:"", recProfileType:-1, recProfileName:"", email:"", pwd:"" };
	saveSearchForm = { flowStatus:-1, searchKey:"", recProfileId:"", recProfileType:-1, recProfileName:"", email:"", pwd:"" };
	saveReminderForm = { flowStatus:-1, holidayId:0, occasionId:0, month:"", day:"", year:"", recProfileId:"", recProfileName:"", recProfileType:-1, recProfileAge:0, recProfileGender:"", email:"", pwd:"" };
	tellAFriendForm = { toName:"", toEmail:"", fromName:"", fromEmail:"", productId:"", ideaId:"" };
	saveBdayReminderForm = { occasionId:1, month:"", day:"", year:"", recProfileId:"", recProfileAge:0, recProfileGender:"" };
	var registrationForm = { email:"", pwd:"", optIn:"" };
}
function showContextWindow() {
	
	var obj = $('contextWindow');
	windowW = windowWidth(); 	// from main.js.
	windowH = windowHeight();	// from main.js.
	newx = (windowW/2) - (390/2);
	newy = (windowH/2) - (390/2);
	obj.style.left = newx; // center the panel horizontally.
	obj.style.top = getOffset()/2 + newy; // center the panel vertically, noting the current scroll position.
	obj.style.visibility='visible';
}
function refreshContextWindow(data) {
	DWRUtil.setValue('contextWindow', data);
}
function refreshAndRepaintContextWindow(data) {
	showContextWindow();
	DWRUtil.setValue('contextWindow', data);
}
function closeContextWindow() {
	resetForms();
	$('contextWindow').style.visibility='hidden';
}
function flipSubmitLink(divId) {
	if ($(divId)) {  // relink
		if ($(divId).style.display=='none') { 
			$(divId).style.display='block';
			$(divId+'_delinked').style.display='none';
		}
		else {  // delink
			$(divId).style.display='none';
			$(divId+'_delinked').style.display='block';
		}
	}
}

var emailDefaultText = 'enter email address';
function cleartEmailDefaultText() {
	if ($('inputEmail').value==emailDefaultText) $('inputEmail').value='';
}
function validateEmail(email) {
	var valid = checkMail(email);	
	updateErrorDiv('emailErrorDiv','Please enter a valid email address.',valid);
	return valid;
}
function validateEmailLanding(email) {
	var valid = checkMail(email);	
	updateErrorDiv('emailErrorDivLanding','Please enter a valid email address.',valid);
	return valid;
}
function validateProfileName(processForm) {
	var valid = true;
	if (processForm.recProfileName==null || processForm.recProfileName.length == 0) {
		updateErrorDiv('recProfileNameErrorDiv','Required field',false);
		valid = false;
	}
	else if (processForm.recProfileName.indexOf(',')>-1) {
		updateErrorDiv('recProfileNameErrorDiv','Please do not use commas',false);
		valid = false;
	}
	return valid;
}
function updateErrorDiv(divName, msg, valid) {
	if (!valid) {
		$(divName).style.display='block';
		DWRUtil.setValue(divName,msg);
	}
	else {
		$(divName).style.display='none';
		DWRUtil.setValue(divName,"");
	}
}
function validateProfileAge(processForm) {
	var valid = (processForm.recProfileAge!=null && processForm.recProfileAge > 0);
	if (!valid)
		DWRUtil.setValue('recProfileAgeErrorDiv','Required field');
	else if ($('recProfileAgeErrorDiv'))
		DWRUtil.setValue('recProfileAgeErrorDiv',"");
	return valid;
}
function validateProfileAgeNoDisplay(processForm) {
	return (processForm.recProfileAge!=null && processForm.recProfileAge > 0);
}
function validateProfileGender(processForm) {
	var valid = (processForm.recProfileGender!=null && processForm.recProfileGender != "Choose One" && processForm.recProfileGender != "");
	if (!valid)
		DWRUtil.setValue('recProfileGenderErrorDiv','Required field');
	else if ($('recProfileGenderErrorDiv'))
		DWRUtil.setValue('recProfileGenderErrorDiv',"");
	return valid;
}
function validateProfileGenderNoDisplay(processForm) {
	return (processForm.recProfileGender!=null && processForm.recProfileGender != "Choose One" && processForm.recProfileGender != "");
}
function validatePassword(pwd) {
	var valid = (pwd!=null && pwd.length >= 4);
	if (!valid)
		DWRUtil.setValue('passwordErrorDiv','Please enter your password.'); 
	else
		DWRUtil.setValue('passwordErrorDiv', '');
	return valid;
}
function getSearchKeyFromUrl() {
	var url = new String (window.location);
	var slash = url.lastIndexOf("/");
	if (slash == -1) {
		url = "";
	}
	else {
		url = url.substring(slash);
		if (url.length == 1) {
			url = "";
		}
		else if (url.length > 0) {
			url = url.substring(1);
			if (url.indexOf("?") != -1) {
				url = url.substring(0, url.indexOf("?"));
			}
		}
	}
	return url;
}
function loadSponsoredListings(keyword, label) {
    SponsoredListing.loadListings(keyword, label, sponsoredListingCallback);
    DWRUtil.setValue("sponsoredListingModule", "");
}

function sponsoredListingCallback(data) {
    DWRUtil.setValue("sponsoredListingModule", data);
}

function submitRegisterUser() {
	var emailValid = true;
	if ($("inputEmailGgtpSignup")) {
		registrationForm.email = DWRUtil.getValue("inputEmailGgtpSignup");
		emailValid = validateEmail(registrationForm.email);
	}
	if (emailValid) {
		RegUser.processRegisterUser(registrationForm, regCallback);
		DWRUtil.setValue("userModule", "Processing registration...");
	}
}
function submitRegisterUserLanding() {
	var emailValid = true;
	if ($("inputEmailLandingSignup")) {
		registrationForm.email = DWRUtil.getValue("inputEmailLandingSignup");
		emailValid = validateEmailLanding(registrationForm.email);
	}
	if (emailValid) {
		RegUser.processRegisterUserLanding(registrationForm, regCallbackLanding);
		DWRUtil.setValue("landingUserModule", "Processing registration...");
	}
}
function regCallback(data) {
    DWRUtil.setValue("userModule", data);
}
function regCallbackLanding(data) {
	DWRUtil.setValue("landingUserModule", data);
}
function startSaveGift(prodId, prodName) {
	resetForms();
	saveGiftForm.productId=prodId;
	saveGiftForm.productName=prodName;
	SaveGift.loadSaveGift(saveGiftForm, refreshAndRepaintContextWindow);
}
function startSaveSearch() {
	resetForms();
	saveSearchForm.searchKey = getSearchKeyFromUrl();
	SaveSearch.selectRecipient(saveSearchForm, refreshAndRepaintContextWindow);
}
function startTellAFriend(productId, ideaId) {
	resetForms();
	tellAFriendForm.productId = productId;
	tellAFriendForm.ideaId = ideaId;	
	TellAFriend.loadTellAFriend(refreshAndRepaintContextWindow);
}
function startSaveReminder(occasionId) {
	resetForms();
	if (occasionId != null) {
		saveReminderForm.occasionId = occasionId;
	}
	Reminder.loadSelectReminder(saveReminderForm, refreshAndRepaintContextWindow);
}
function startSaveReminderHoliday(holidayId) {
	resetForms();
	if (holidayId == null) {
		startSaveReminder();
	} else {
		selectHoliday(holidayId);
	}
}
function startSaveBirthdayReminder(recProfileId) {
	resetForms();
	if (recProfileId==null) recProfileId=0;
	Reminder.loadBirthdayReminder(refreshAndRepaintContextWindow, recProfileId);
}

function restartSaveReminder() {
	saveReminderForm.holidayId = 0;
	clearReminderRecipientSelections();
	Reminder.loadSelectReminder(saveReminderForm, refreshAndRepaintContextWindow);
}

function selectHoliday(holidayId) {
	resetForms();
	saveReminderForm.holidayId = holidayId;
	Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
}
function selectOccasionDate() {
	saveReminderForm.month = DWRUtil.getValue('month');
	saveReminderForm.day   = DWRUtil.getValue('day');
	saveReminderForm.year  = DWRUtil.getValue('year');
	Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
}
function selectReminderNewRecipient(profileType) {
	clearReminderRecipientSelections();
	saveReminderForm.recProfileType = profileType;
	saveReminderForm.flowStatus = 1;
	Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
}
function selectReminderSavedRecipient(profileId, age, gender) {
	clearReminderRecipientSelections();
	saveReminderForm.recProfileId = profileId;
	saveReminderForm.flowStatus = 0;
	saveReminderForm.recProfileAge = age;
	saveReminderForm.recProfileGender = gender;
	var ageValid = validateProfileAgeNoDisplay(saveReminderForm);
	var genderValid = validateProfileGenderNoDisplay(saveReminderForm);
	if (ageValid && genderValid) {
		Reminder.processSaveReminder(saveReminderForm, refreshAndRepaintContextWindow);
	} else {
		Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
	}
}
function showReminderNewRecipients() {
	clearReminderRecipientSelections();
	saveReminderForm.flowStatus = 1;
	Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
}
function showReminderSavedRecipients() {
	clearReminderRecipientSelections();
	saveReminderForm.flowStatus = 0;
	Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
}
function reenterReminderEmail() {
	saveReminderForm.email = "";
	saveReminderForm.pwd = "";
	Reminder.loadSelectRecipient(saveReminderForm, refreshAndRepaintContextWindow);
}
function submitSaveReminder(divId) {
	flipSubmitLink(divId);  
	var recProfileAgeValid = true;
	if ($("inputRecProfileAge")) {
		saveReminderForm.recProfileAge = DWRUtil.getValue("inputRecProfileAge");
		recProfileAgeValid = validateProfileAge(saveReminderForm);
	}
	var recProfileGenderValid = true;
	if ($("inputRecProfileGender")) {
		saveReminderForm.recProfileGender = DWRUtil.getValue("inputRecProfileGender");
		recProfileGenderValid = validateProfileGender(saveReminderForm);
	}
	var recProfileNameValid = true;
	if ($("inputRecProfileName")) {
		saveReminderForm.recProfileName = DWRUtil.getValue("inputRecProfileName");
		recProfileNameValid = validateProfileName(saveReminderForm);
	}
	var emailValid = true;
	if ($("inputEmail")) {
		saveReminderForm.email = DWRUtil.getValue("inputEmail");
		emailValid = validateEmail(saveReminderForm.email);
	}
	if ($('optInCB')) saveReminderForm.optIn = $('optInCB').checked;
	if ($('inputPassword')) saveReminderForm.pwd = DWRUtil.getValue("inputPassword");
	var formValid = recProfileNameValid && recProfileAgeValid && recProfileGenderValid && emailValid;
	if (formValid) {
		Reminder.processSaveReminder(saveReminderForm, refreshAndRepaintContextWindow);
	}
	else flipSubmitLink(divId); 
}
function submitSaveBirthdayReminder() {
	saveBdayReminderForm.month = DWRUtil.getValue('month');
	saveBdayReminderForm.day   = DWRUtil.getValue('day');
	saveBdayReminderForm.recProfileId = DWRUtil.getValue("inputRecProfileId");
	var recProfileAgeValid = true;
	if ($("inputRecProfileAge")) {
		saveBdayReminderForm.recProfileAge = DWRUtil.getValue("inputRecProfileAge");
		recProfileNameValid = validateProfileAge(saveBdayReminderForm);
	}
	var recProfileGenderValid = true;
	if ($("inputRecProfileGender")) {
		saveBdayReminderForm.recProfileGender = DWRUtil.getValue("inputRecProfileGender");
		recProfileGenderValid = validateProfileGender(saveBdayReminderForm);
	}
	var formValid = recProfileAgeValid && recProfileGenderValid;
	if (formValid) {
		Reminder.processSaveBirthdayReminder(saveBdayReminderForm, refreshAndRepaintContextWindow);
	}
}
function clearReminderRecipientSelections() {
	saveReminderForm.recProfileId = "";
	saveReminderForm.recProfileName = "";
	saveReminderForm.recProfileType = -1;
	saveReminderForm.recProfileAge = "";
	saveReminderForm.recProfileGender = "";
	saveReminderForm.email = "";
	saveReminderForm.pwd = "";
}

function reloadSaveSearch() {
	SaveSearch.selectRecipient(saveSearchForm, refreshContextWindow);
}

function selectSaveSearchExistingRecipient(profileId) {
	saveSearchForm.recProfileId = profileId;
	saveSearchForm.recProfileType = -1;
	saveSearchForm.flowStatus = 0;	
	if (Number(profileId) == 0) reloadSaveSearch();
	else submitSaveSearch();
}

function selectSaveSearchNewRecipient(profileType) {
	saveSearchForm.recProfileId = "";
	saveSearchForm.recProfileType = profileType;
	saveSearchForm.flowStatus = 1;	
	saveSearchForm.recProfileName = "";
	if ( $( "inputRecProfileName" ) )
		DWRUtil.setValue("inputRecProfileName", "");
	
	reloadSaveSearch();
}
function selectSaveSearchForUser(loggedIn) {
	saveSearchForm.recProfileId = -1;
	saveSearchForm.recProfileType = -1;
	saveSearchForm.recProfileName = "";

	if (!loggedIn) reloadSaveSearch();
	else SaveSearch.saveSearch(saveSearchForm, refreshContextWindow);
}
function submitSaveSearch(divId) {
	flipSubmitLink(divId);  
	var isRecProfileNameValid = true;
	if ( $( "inputRecProfileName" ) ) {
		saveSearchForm.recProfileName = DWRUtil.getValue("inputRecProfileName");
		isRecProfileNameValid = validateProfileName(saveSearchForm);
	}
	var isEmailValid = true;
	if ( $( "inputEmail" ) ) {
		saveSearchForm.email = DWRUtil.getValue("inputEmail");
		isEmailValid = validateEmail(saveSearchForm.email);
	}
	if ($('optInCB')) saveSearchForm.optIn = $('optInCB').checked;
	if ( $( "inputPassword" ) )
		saveSearchForm.pwd = DWRUtil.getValue("inputPassword");
	if ( isRecProfileNameValid && isEmailValid )
		SaveSearch.saveSearch(saveSearchForm, refreshContextWindow);
	else flipSubmitLink(divId);  //re-link
}

function reloadSaveGift() {
	SaveGift.loadSaveGift(saveGiftForm, refreshContextWindow);
}

function clearPreviousRecipientSelections() {
	saveGiftForm.recProfileId = "";
	saveGiftForm.recProfileType = -1;
	saveGiftForm.recProfileName = "";
	saveGiftForm.saveToWishList = false;
}
function selectSaveGiftNewRecipient(profileType) {
	clearPreviousRecipientSelections();
	saveGiftForm.recProfileType = profileType;
	saveGiftForm.flowStatus = 1;
	reloadSaveGift();
}	
function selectSaveGiftExistingRecipient(profileId) {
	clearPreviousRecipientSelections();
	saveGiftForm.recProfileId = profileId;
	saveGiftForm.flowStatus = 0;
	if (Number(profileId) == 0) reloadSaveGift();
	else submitSaveGift();	
}
function clickAddToWishList(loggedIn) {
	clearPreviousRecipientSelections();
	saveGiftForm.saveToWishList = true;	
	if (!loggedIn) reloadSaveGift();
	else SaveGift.saveToWishList(saveGiftForm, refreshContextWindow);
}
function submitSaveGift(divId) {
	flipSubmitLink(divId);	
	var recProfileNameValid = true;
	if ($("inputRecProfileName")) {
		saveGiftForm.recProfileName = DWRUtil.getValue("inputRecProfileName");
		recProfileNameValid = validateProfileName(saveGiftForm);
	}
	var emailValid = true;
	if ($("inputEmail")) {
		saveGiftForm.email = DWRUtil.getValue("inputEmail");
		emailValid = validateEmail(saveGiftForm.email);
	}
	if ($('optInCB')) saveGiftForm.optIn = $('optInCB').checked;
	if ($('inputPassword')) saveGiftForm.pwd = DWRUtil.getValue("inputPassword");
	var formValid = recProfileNameValid && emailValid;
	if (formValid) {
		if (saveGiftForm.saveToWishList) 
			SaveGift.saveToWishList(saveGiftForm, refreshContextWindow);
		else
			SaveGift.processSaveGift(saveGiftForm, refreshContextWindow);
	}
	else flipSubmitLink(divId);  
}

function validateTellAFriendName(value, errorDiv) {
	var valid = (value != null && value.length > 0);
	if (!valid) {
		DWRUtil.setValue(errorDiv, "Please enter a name.");
	} else {
		DWRUtil.setValue(errorDiv, "");
	}
	return valid;
}
function validateTellAFriendEmail(email, errorDiv) {
	var valid = checkMail(email);
	if (!valid) {
		DWRUtil.setValue(errorDiv, "Please enter a valid email.");
	} else {
		DWRUtil.setValue(errorDiv, "");
	}
	return valid;	
}
function submitTellAFriend() {	
	tellAFriendForm.toName = DWRUtil.getValue('inputToName');
	var isValidToName = validateTellAFriendName(tellAFriendForm.toName, 'toNameErrorDiv');
	tellAFriendForm.toEmail = DWRUtil.getValue('inputToEmail');
	var isValidToEmail = validateTellAFriendEmail(tellAFriendForm.toEmail, 'toEmailErrorDiv');
	var isValidFromName = true;
	if ( $( 'inputFromName' ) ) {
		tellAFriendForm.fromName = DWRUtil.getValue('inputFromName');
		isValidFromName = validateTellAFriendName(tellAFriendForm.fromName, 'fromNameErrorDiv');
	}
	var isValidFromEmail = true;
	if ( $( 'inputFromEmail' ) ) {
		tellAFriendForm.fromEmail = DWRUtil.getValue('inputFromEmail');
		isValidFromEmail = validateTellAFriendEmail(tellAFriendForm.fromEmail, 'fromEmailErrorDiv');
	}
	
	if ( isValidToName && isValidToEmail && isValidFromName && isValidFromEmail )
		TellAFriend.processTellAFriend(tellAFriendForm, refreshContextWindow);
}
function getSelectedIds() {
	var checkBoxes = document.getElementsByName('interests');
	var selectedIds = new Array ();
	if (checkBoxes != null) {
		for (var i=0; i<checkBoxes.length; i++) {
			if (checkBoxes[i].checked) 
				selectedIds[selectedIds.length] = checkBoxes[i].value;
		}
	}
	return selectedIds;
}

function addInterests(profileId) {
	Reminder.processSaveInterests(profileId, getSelectedIds(), refreshContextWindow);
}
function addInterestLater(profileId) {
	Reminder.processSaveInterests(profileId, new Array (), refreshContextWindow);
}
function imgLayer(imgSrc,imgCap) {
	x = document.getElementById("imgCaption");
	x.innerHTML = "<img src='" + imgSrc + "'><p style='padding: 6px 0px 4px 0px; text-align: center;'></p>" + imgCap;
}
function selectedCount() {
	var checkBoxes = document.getElementsByName('interests');
	var count = 0;
	if (checkBoxes != null) {
		for (var i=0; i<checkBoxes.length; i++) {
			if (checkBoxes[i].checked) count++;
		}
	}
	return count;
}
function updateForm() {
   var k = selectedCount();
   var checkBoxes = document.getElementsByName('interests');
    if (checkBoxes != null) {
       for (var i=0; i<checkBoxes.length; i++) {
           if (!checkBoxes[i].checked) checkBoxes[i].disabled = (k>=3);
       }
   }
}
var errorHtml = '<table border="0" cellspacing="0" cellpadding="0">' +
'	<tr>' +
'		<td>' +
'			<font class=error>giftdunia.com encounter an error.  Please close this window and try again.</font><P>' +
'			<button onclick="closeContextWindow();">Close</button>' +
'		</td>' +
'	</tr>' +
'</table>';								
function errorHandler() {
	DWRUtil.setValue('contextWindow', errorHtml);
}
DWREngine.setErrorHandler(errorHandler);