subscribeWidgetNeedsToRefreshPage = false;

function doSubscribePageRefresh() {
	//refresh the page
	if(subscribeWidgetNeedsToRefreshPage) {
		window.location.href = unescape(window.location.pathname);
		return true;
	} else return false;
}

function closeModalWindow() {
	if(!doSubscribePageRefresh()) parent.Control.Modal.close();
}

function getConfirmPageParameters() {
	var subscribe2question	= $('subscribeToQuestionCheckbox');
	var subscribe2tag	= $('subscribeToTagCheckbox');

	var params = Array();

	if(subscribe2question!=undefined && subscribe2question.checked) {

		var ptemp = Array();
			ptemp['name']	= 'byquestion';
			ptemp['value']	= 'true';
		params[params.length] = ptemp
	}

	if(subscribe2tag!=undefined && subscribe2tag.checked) {

		var ptemp = Array();
			ptemp['name']	= 'bytag';
			ptemp['value']	= 'true';
		params[params.length] = ptemp
	}

	return params;
}

function subscribeToAlertsAction() {

	var subscribe2question	= $('subscribeToQuestionCheckbox');
	var subscribe2tag		= $('subscribeToTagCheckbox');

	if(subscribe2question!=undefined && subscribe2question.checked) {
		var questionTitle = $('questionTitle');
		if(questionTitle != undefined) {
			var params = Array();
				params[0] = Array();
				params[0]['name'] = 'title';
				params[0]['value'] = questionTitle.value;
			if(subscribe2tag!=undefined && subscribe2tag.checked) {
				executeAjaxFunctionXML('subscribeToQuestion', subscribeByQuestion_return_without_refresh_without_confirm, params);
			} else {
				executeAjaxFunctionXML('subscribeToQuestion', subscribeByQuestion_return_with_refresh, params);
			}
		}
	}

	var pagetype = $('pagetype');
	if(pagetype != undefined) {

		if(subscribe2tag!=undefined && subscribe2tag.checked) {
			//showParentTagListingFromQuestion(true);
			showParentTagListingByUnknown(true);
		} else if(pagetype.value == 'tag_landing') {
			var params = getConfirmPageParameters();

			var tag = $('tagid');
			if(tag != undefined) {
				temp = new Array();
				temp['name'] = 'tagid';
				temp['value'] = tag.value;
				params[params.length] = temp;

			}

			hidePage();
			executeAjaxFunctionXML("parentTagListingFromLanding", showParentTagListing_returnResult, params);
		} else if(pagetype.value == 'question_landing') {
			var params = new Array();
			executeAjaxFunctionXML("parentTagListingFromLanding", showParentTagListing_returnResult, params);
		}
	}
}

function subscribeByQuestion_return_with_refresh(xml) {
	subscribeWidgetNeedsToRefreshPage = true;

	modalWindow.open();
	executeAjaxFunctionXML('subscribeConfirm', subscribeToTags_returnResult, getConfirmPageParameters());
}

function subscribeByQuestion_return_without_refresh(xml, doNotConfirm) {
	subscribeWidgetNeedsToRefreshPage = true;

	executeAjaxFunctionXML('subscribeConfirm', subscribeToTags_returnResult, getConfirmPageParameters());
}

function subscribeByQuestion_return_without_refresh_without_confirm(xml) {
	subscribeWidgetNeedsToRefreshPage = true;
}

function parentTagListingFromQuestion(from) { //temp - from dummy page to open subscribe page
	preparePageForRefresh();
	executeAjaxFunction('parentTagListing', 'modal_container', {fromPage:from});
}

function subscribeConfirm(from) { //temp - from dummy page to open confirm page
	preparePageForRefresh();
	executeAjaxFunction('subscribeConfirm', 'modal_container', getConfirmPageParameters());
}

function hidePage() {
	if($('modal_body') != undefined)
		$('modal_body').hide();
	if($('ajax_errors') != undefined)
		$('ajax_errors').hide();
	if($('ajax_confirmation') != undefined)
		$('ajax_confirmation').hide();
	if($('modal_pleaseWait') != undefined)
		$('modal_pleaseWait').show();
}

function showPage() {
	$('modal_pleaseWait').setStyle({display: 'none'});
	$('modal_body').setStyle({display: 'block'});

	//this is a hack to fix a bug where certain parts of the window disappear
	var tempp=$('modal_container').getStyle('top').gsub('px', '')*1-1;
	$('modal_container').setStyle({top: tempp+'px'});

	//check if user should be subscrived to a question (case where user was not logged in, and had both subscribe by question and tag boxes checked)
	var subscribe2question	= $('subscribeToQuestionCheckbox');
	if(subscribe2question!=undefined && subscribe2question.checked) {
		var questionTitle = $('questionTitle');
		if(questionTitle != undefined) {
			var params = Array();
				params[0] = Array();
				params[0]['name'] = 'title';
				params[0]['value'] = questionTitle.value;
				executeAjaxFunctionXML('subscribeToQuestion', subscribeByQuestion_return_without_refresh_without_confirm, params);
		}
	}

}

function prepareSubscribeToQuestion() { //temp
	executeAjaxFunctionXML('ajaxSubscribeToQuestion', 'defaultAjaxSuccessFunction', {tag:'testing'});
}

function checkUserStatus() {
	var form = $('sidebarSubscribeForm');
	var input = form['email'];
	var email=$(input).getValue();

	if (validateEmail(email)==false) {
		showValidationError("The email address you submitted is not properly formatted.<br><br>Please try again.");
	} else {
		var params = new Array();
			var tempArray = new Array();
				tempArray["name"] = "email";
				tempArray["value"] = email;
			params[0] = tempArray;

		executeAjaxFunctionXML('getUserStatus', checkUserStatus_returnResult, params);
	}
}

function checkUserStatus_returnResult(xml) {
	// convert the string to an XML object
	var xmlobject = new DOMParser().parseFromString(xml, "text/xml");
	var status = xmlobject.getElementsByTagName("status")[0].firstChild.nodeValue;

	var form = $('sidebarSubscribeForm');
	var input = form['email'];
	var email=$(input).getValue();

	if (status=="registered") {
		modalWindow.open();

		var params = new Array();
			var tempArray = new Array();
				tempArray["name"] = "email";
				tempArray["value"] = email;
		params[0] = tempArray;
		
		executeAjaxFunctionXML('displayLoginForm', displayLogin_returnResult, params);
	} else {
		$("sidebarSubscribeForm").submit()
	}
}

function displayLogin_returnResult(resultHTML) {
	$('modal_container').setStyle({height: '325px'});
	centerModalWindow();
	$('modal_container').update(resultHTML);
	showPage();
}

function login() {
	var email = $F('lightbox_email');
	var password = $F('lightbox_password');

	/*
	if (validateEmail(email)==false || password=="") {
		//showValidationError(errorText)
		alert("Please enter a valid email address and password.");
	} else {
	}
	*/
	var params = new Array();
		var tempArray = new Array();
			tempArray["name"] = "email";
			tempArray["value"] = email;
		params[0] = tempArray;

		tempArray.length = 0;

		tempArray = new Array();
			tempArray["name"] = "password";
			tempArray["value"] = password;
		params[1] = tempArray;

	hidePage();
	executeAjaxFunctionXML('login', login_returnResult, params);
}

function login_returnResult(xml) {
	// convert the string to an XML object
	var xmlobject = new DOMParser().parseFromString(xml, "text/xml");
	var errors = xmlobject.getElementsByTagName("error");

	if (errors.length>0) {
		var html='<ul class="normalList_noBullets">';
		for (var i = 0 ; i < errors.length ; i++) {
			var error = errors[i].firstChild.nodeValue;
			html+='<li>Error - '+error+'.</li>';
		}
		html+='</ul>';

		//resize window to fit error and display errors
		$('modal_container').setStyle({height: '335px'});
		centerModalWindow();
		$('ajax_errors').update(html);
		$('default_copy').setStyle({display: 'none'});
		$('ajax_errors').setStyle({display: 'block'});
		$('ajax_errors').setStyle({display: 'block'});

		showPage();
	} else {
		//redirect to the parent tag listing
		subscribeWidgetNeedsToRefreshPage = true;

		//if the user wanted to subscribe to tags .. continute on in the lightbox, otherwise close it
		var subscribe2tag	= $('subscribeToTagCheckbox');
		if(subscribe2tag != undefined && subscribe2tag.checked) {
			showParentTagListingByUnknown();
		} else {
			subscribeToAlertsAction();
			//closeModalWindow();
		}
	}
}

function showParentTagListingByUnknown(openModal) {
	if($('questionTitle') != undefined) showParentTagListingFromQuestion(openModal);
	else if($('tagid') != undefined) showParentTagListingFromTag(openModal);
	else {
		if (openModal==true) modalWindow.open();
		var params = new Array();
		executeAjaxFunctionXML("parentTagListingFromLanding", showParentTagListing_returnResult, params);
	}
}

function showParentTagListingFromQuestion(openModal) {
	var questionTitle = $('questionTitle');

	var params = new Array();
		if(questionTitle != undefined) {
			params[0] = new Array();
			params[0]['name'] = 'title';
			params[0]['value'] = questionTitle.value;
		}

	if (openModal==true) modalWindow.open();		

	executeAjaxFunctionXML("parentTagListingFromQuestion", showParentTagListing_returnResult, params);
}

function showParentTagListingFromTag(openModal) {
	var tag = $('tagid');


	var params = getConfirmPageParameters();

	var tag = $('tagid');
	if(tag != undefined) {
		temp = new Array();
		temp['name'] = 'tagid';
		temp['value'] = tag.value;
		params[params.length] = temp;

	}

	if (openModal==true) modalWindow.open();

	subscribeWidgetNeedsToRefreshPage = true;
	executeAjaxFunctionXML("parentTagListingFromLanding", showParentTagListing_returnResult, params);
}

function showParentTagListing_returnResult(resultHTML) {
	$('modal_container').setStyle({height: '415px'});
	centerModalWindow();
	$('modal_container').update(resultHTML);
	showPage();
}

function forgotPassword() {
	var email = $F('forgotEmail');

	/*
	if (validateEmail(email)==false) {
		alert("Please enter a valid email address.");
	} else {
	}
	*/
	var params = new Array();
		var tempArray = new Array();
			tempArray["name"] = "email";
			tempArray["value"] = email;
		params[0] = tempArray;

	hidePage();
	executeAjaxFunctionXML('forgotPassword', forgotPassword_returnResult, params);
}

function forgotPassword_returnResult(xml) {
	var email = $F('forgotEmail');

	//strip out any php errors from the response
	while(xml.indexOf('<ajaxresult>') !== 0 && xml.length >0) {
		xml = xml.substring(1);
	}

	//just close the window if the expected XML wasn't sent
	if(xml.length == 0) closeModalWindow();

	// convert the string to an XML object
	var xmlobject = new DOMParser().parseFromString(xml, "text/xml");
	var success = xmlobject.getElementsByTagName("success")[0];

	var html='<ul class="normalList_noBullets">';
	if (success != undefined) { //success
		html+='<li>Your password has been e-mailed to you at '+email+'.</li>';
	} else { //some sort of failure
		html+='<li>Error - Your password could not be sent. Please try again.</li>';
	}
	html+='</ul>';

	//resize window to fit and display confirmation
	$('modal_container').setStyle({height: '335px'});
	centerModalWindow();
	$('ajax_confirmation').update(html);
	$('default_copy').hide(html);
	$('ajax_confirmation').setStyle({display: 'block'});
	showPage();
}

function subscribeToTags() {
	var howManyChecked=0;
	var allCheckboxes=$('modal_form').getInputs('checkbox');
	allCheckboxes.each(function(input){
		if (input.checked) howManyChecked++;
	});

	if (howManyChecked==0) {
		var html='<ul class="normalList_noBullets">';
		html+='<li>Error - Please select at least one tag.</li>';
		html+='</ul>';

		$('modal_container').setStyle({height: '465px'});
		centerModalWindow();
		$('ajax_errors').update(html);
		$('ajax_errors').setStyle({display: 'block'});
	} else {
		var params = getConfirmPageParameters();

		tparams = new Array();
		tparams['name']	= 'numTags';
		tparams['value']	= howManyChecked;

		params[params.length] = tparams;

		var x = 0;
		allCheckboxes.each(function(input){
			if (input.checked) {
				var tempArray = new Array();
					tempArray["name"] = "tag"+x;
					tempArray["value"] = input.name;
				x++;
				params[params.length] = tempArray;
				tempArray.length = 0;
			}
		});

		hidePage();
		executeAjaxFunctionXML('subscribeConfirm', subscribeToTags_returnResult, params);
	}
}

function subscribeToTags_returnResult(resultHTML) {
	$('modal_container').setStyle({height: '150px'});
	centerModalWindow();
	$('modal_container').update(resultHTML);
	showPage();
}


function validateEmail(email) {
	// Regex from: http://regexlib.com/REDetails.aspx?regexp_id=599
	var filter = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/;
	if (!filter.test(email)) {
		return false;
	}
	return true;
}

function centerModalWindow() {
	var element=$('modal_container');
	var dimensions = element.getDimensions();
	Position.prepare();
	var offset_left = (Position.deltaX + Math.floor((Control.Modal.getWindowWidth() - dimensions.width) / 2));
	var offset_top = (Position.deltaY + ((Control.Modal.getWindowHeight() > dimensions.height) ? Math.floor((Control.Modal.getWindowHeight() - dimensions.height) / 2) : 0));
	element.setStyle({
		top: ((dimensions.height <= Control.Modal.getDocumentHeight()) ? ((offset_top != null && offset_top > 0) ? offset_top : '0') + 'px' : 0),
		left: ((dimensions.width <= Control.Modal.getDocumentWidth()) ? ((offset_left != null && offset_left > 0) ? offset_left : '0') + 'px' : 0)
	});
}

if(typeof(DOMParser) == 'undefined') {
	DOMParser = function() {}
	DOMParser.prototype.parseFromString = function(str, contentType) {
		if(typeof(ActiveXObject) != 'undefined') {
			var xmldata = new ActiveXObject('MSXML.DomDocument');
			xmldata.async = false;
			xmldata.loadXML(str);
			return xmldata;
		} else if(typeof(XMLHttpRequest) != 'undefined') {
			var xmldata = new XMLHttpRequest;
			if(!contentType) {
				contentType = 'application/xml';
			}
			xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);
			if(xmldata.overrideMimeType) {
				xmldata.overrideMimeType(contentType);
			}
			xmldata.send(null);
			return xmldata.responseXML;
		}
	}
}
