function showStatus(mode, errorCode, errorMessage){
	var s;
	switch(errorCode){
		case 0:
			s = "Account not checked";
			break;
		case 1:
			s = "Account checked";
			break;
		case 2:
			s = "Invalid password";
			break;
		case 3:
			s = "Account locked out";
			break;
		case 4:
			s = "Provider error";
			break;
		case 5:
			s = "Provider disabled";
			break;
		case 6:
			s = "Engine error";
			break;
		case 7:
			s = "Missing password";
			break;
	}
	if(errorMessage != "")
		s = s + ': ' + errorMessage;
	alert(s);
}

function showExpirationWarning(message, style){
//	var winwidth, winheight, picWidth, picHeight;
//	picWidth = 350;
//	picHeight = 150;
//	winwidth = (screen.availWidth - picWidth) / 2;
//	winheight = (screen.availHeight - picHeight) / 2;
	showMessagePopup(style, 'Expiration warning', message);
//	statusPage = window.open("/account/warning.php?Message="+encodeURI(message)+"&Style="+style+"&Header="+encodeURI("Expiration Warning"), "status", "height="+picHeight+",width="+picWidth+",left="+winwidth+",top="+winheight+",scrollbars=no,resizable=yes")
//	statusPage.focus()
}

function showRenewNote(accountId){
	if(pda){
		alert('This feature is not available on mobile version'); /*checked*/
		return false;
	}
	new Ajax.Request(
		"/account/renewNote.php?ID="+accountId,
		{
			onSuccess: function(transport){
				showMessagePopup('info', 'Renew note', transport.responseText);
			},
			onFailure: ajaxError
		}
	);
}

function showMessagePopup(style, header, message){
	if(pda){
		alert(message);
	}
	else{
		$('messageHeader').innerHTML = header;
		$('messageText').style.height = '';
		$('messageText').style.overflow = '';
		$('messageText').innerHTML = message;
		var height = $('messagePopupBody').getHeight() + 30;
		var maxHeight = document.viewport.getHeight();
		if(height > maxHeight){
			height = maxHeight;
			$('messageText').style.height = height - 150 + 'px';
			$('messageText').style.overflow = 'auto';
		}
		$('messagePopup').style.height = height + 'px';
		$('messageOKButton').value = "OK";
		$('messageOKButton').onclick = new Function("cancelPopup()");
		$('messageCancelButton').style.display = "none";
		var fader = document.getElementById('fader');
		fader.onclick = function(){cancelPopup()};
		showPopupWindow($('messagePopup'));
	}
}

function showBecomeAFanPopup(){
	$('messageHeader').innerHTML = 'Become our fan on Facebook';
	$('messageText').style.height = '';
	$('messageText').style.overflow = '';
	$('messageText').innerHTML = '<a href="http://www.facebook.com/apps/application.php?id=75330755697" target="_blank" onclick="cancelPopup(); return true;"><img src="/images/becomeAFan.png" width="658" height="250" border="0"></a><br><br>Please go to Facebook, and click on the "Become a Fan" link'; /*checked by Alexi*/
	var height = $('messagePopupBody').getHeight() + 30;
	var maxHeight = document.viewport.getHeight();
	if(height > maxHeight){
		height = maxHeight;
		$('messageText').style.height = height - 150 + 'px';
		$('messageText').style.overflow = 'auto';
	}
	$('messagePopup').style.height = height + 'px';
	$('messagePopup').style.width = '700px';
	$('messageOKButton').value = "Open Facebook.com";
	$('messageOKButton').style.width = '200px';
	$('messageOKButton').onclick = new Function("window.open('http://www.facebook.com/apps/application.php?id=75330755697', 'facebook', ''); cancelPopup();");
	// menubar=no,toolbar=no,location=no,directories=no,status=yes,scrollbars=yes,resizable=no,dependent,width=530,height=450,left=50,top=50
	$('messageCancelButton').style.display = "none";
	showPopupWindow($('messagePopup'));
}

function showQuestionPopup(style, header, message, okCaption, okScript, cancelCaption, cancelScript){
	$('messageHeader').innerHTML = header;
	$('messageText').innerHTML = message;
	$('messagePopup').style.height = $('messagePopupBody').getHeight() + 30 + 'px';
	$('messageOKButton').value = okCaption;
	$('messageOKButton').onclick = new Function(okScript);
	$('messageCancelButton').value = cancelCaption;
	$('messageCancelButton').onclick = new Function(cancelScript);
	$('messageCancelButton').style.display = "";
	showPopupWindow($('messagePopup'));
}

function showBalanceWarning(message, style){
	var winwidth, winheight, picWidth, picHeight;
	picWidth = 350;
	picHeight = 150;
	winwidth = (screen.availWidth - picWidth) / 2;
	winheight = (screen.availHeight - picHeight) / 2;
	statusPage = window.open("/account/warning.php?Message="+encodeURI(message)+"&Style="+style+"&Header="+encodeURI("Warning"), "status", "height="+picHeight+",width="+picWidth+",left="+winwidth+",top="+winheight+",scrollbars=no,resizable=yes")
	statusPage.focus()
}

var checkCancelled = false;

Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }

    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;

    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } else {

    }
  },
  update: function(position) {
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});

function setHistoryRows(idx, cycle, accounts){
	var rows = 0;
	if(cycle){
		rows = rows + idx;
		if(rows > 5){
			$('checkHistory').style.overflow = 'auto';
			new Effect.Scroll('checkHistory', {x:0, y: 20, mode: 'relative', duration: 0.5});
			rows = 5;
		}
		else
			$('checkHistory').style.overflow = 'hidden';
	}
	else
		$('checkHistory').style.overflow = 'hidden';
	if(rows > 0)
		new Effect.Morph('checkHistory', {style: 'height: '+(20 * rows)+'px;', duration: 0.5});
	else
		$('checkHistory').style.height = (20 * rows) + 'px';
	if(rows == 0)
		$('checkHistory').style.display = 'none';
	else
		$('checkHistory').style.display = '';
	var popupHeight = 355 + 20 * rows;
	if(rows > 0){
		new Effect.Morph('checkPopup', {style: 'height: '+popupHeight+'px;', duration: 0.5});
		var top = Math.round( document.viewport.getHeight() / 2 - popupHeight / 2 + document.viewport.getScrollOffsets().top );
		new Effect.Morph('checkPopup', {style: 'top: '+top+'px;', duration: 0.5});
		new Effect.Morph('checkPopupInner', {style: 'height: '+popupHeight+'px;', duration: 0.5});
	}
	else{
		$('checkPopup').style.height = popupHeight + 'px';
		$('checkPopupInner').style.height = popupHeight + 'px';
	}
	if((idx == 0) || !cycle)
		$('checkHistoryText').innerHTML = '';
}

function checkAccountIdx(idx, cycle){
	checkCancelled = false;
	var accounts = $('body').getElementsBySelector('a.checkLink');
	var thisPopup;
	if(idx < accounts.length){
		setHistoryRows(idx, cycle, accounts);
		var account = accounts[idx];
		var accountId = account.readAttribute('accountId');
		$('checkStopButton').onclick = stopChecking;
		if(cycle)
			$('checkPopupHeader').innerHTML = 'Checking account '+(idx+1)+' of '+accounts.length+': '+account.readAttribute('UserName');
		else
			$('checkPopupHeader').innerHTML = 'Checking <span style="font-weight: bold;">"'+$('rewardName'+accountId).innerHTML+ '"</span> for '+account.readAttribute('UserName');
		$('checkText').innerHTML = '<img src="/lib/images/progressCircle.gif"> Currently checking: <span style="font-weight: bold;">'+$('providerName'+accountId).innerHTML+'</span>';
		$('checkNote').innerHTML = '*All advertising links open in a new window, checking balances will not stop.';
		if($('checkPopup').style.visibility != 'visible')
			showPopupWindow($('checkPopup'));
		new Ajax.Request(
			"/top10/getContent.php?AccountID="+accountId,
			{
				onSuccess: function(transport){
					if(!transport.responseJSON){
						ajaxError(transport);
						return false;
					}
					var response = transport.responseJSON;
					var content = response.Content;
					if(content != ""){
						$('checkAdContent').innerHTML = content;
						var links = $('checkAdContent').getElementsBySelector('a');
						for(var n = 0; n < links.length; n++){
							var link = links[n];
							link.target = "_blank";
							link.onclick = function(){
								new Ajax.Request(
									"/top10/countClick.php?UserID="+response.UserID+'&SocialAdID='+response.SocialAdID,
									{
										onFailure: ajaxError
									}
								)
							}
						}
					}
				},
				onFailure: ajaxError
			}
		);
		new Ajax.Request(
			"/account/ajaxCheck.php?ID="+accountId+'&Cycle='+(cycle?"1":"0"),
			{
				onSuccess: function(transport){
					if(checkCancelled)
						return false;
					if(!transport.responseJSON){
						ajaxError(transport);
						return false;
					}
					var response = transport.responseJSON;
					if(response.Status == "Unauthorized"){
						authorize();
					}
					else{
						if(response.Status == 'Question'){
							thisPopup = activePopupWindow;
							thisPopup.style.zIndex = '9';
							activePopupWindow = null;
							var onCancel;
							if(cycle)
								onCancel = function(){
									activePopupWindow = thisPopup;
									activePopupWindow.style.zIndex = "50";
									cycleAccountChecked(accounts, response.Message, idx);
								};
							else
								onCancel = function(){
									activePopupWindow = thisPopup;
									activePopupWindow.style.zIndex = "50";
									stopChecking();
									document.location.reload()
								};
							askAccountQuestion(accountId, response.DisplayName, response.Question, function(){
								activePopupWindow = thisPopup;
								activePopupWindow.style.zIndex = "50";
								checkAccountIdx(idx, cycle);
							}, onCancel);
						}
						else{
							if(!cycle){
								$('checkText').innerHTML = response.Message;
								$('checkStopButton').value = 'Close';
								$('checkStopButton').onclick = function(){stopChecking(); document.location.reload();};
								if(response.Detail != ""){
									$('checkAdContent').style.display = 'none';
									$('checkAdMessage').style.display = '';
									setTimeout(function(){
										var msgHeight = $('checkAdMessage').getHeight();
										if((msgHeight + 220) > document.viewport.getHeight()){
											msgHeight = document.viewport.getHeight() - 220;
										}
										$('checkAd').style.height = msgHeight + 'px';
										$('checkAd').style.overflow = 'auto';
										var popupHeight = 195 + msgHeight;
										new Effect.Morph('checkPopup', {style: 'height: '+popupHeight+'px;', duration: 0.5});
										var top = Math.round( document.viewport.getHeight() / 2 - popupHeight / 2 + document.viewport.getScrollOffsets().top );
										new Effect.Morph('checkPopup', {style: 'top: '+top+'px;', duration: 0.5});
										new Effect.Morph('checkPopupInner', {style: 'height: '+popupHeight+'px;', duration: 0.5});
									}, 100);
									$('checkAdMessage').innerHTML = "<div id=checkAdError style=\"text-align: left; padding: 5px; font-size: 16px;\">"+response.Detail+"</div>";
/*									var fontSize = 17;
									while(($('checkAd').getHeight() - 10) < $('checkAdMessage').getHeight()){
										$('checkAdMessage').innerHTML = "<div id=checkAdError style=\"text-align: left; padding: 5px; font-size: "+fontSize+"px;\">"+response.Detail+"</div>";
										fontSize--;
									}
									$('checkAd').style.border = '1px solid red';*/
								}
								//document.location.reload();
							}
							else{
								cycleAccountChecked(accounts, response.Message, idx);
							}
						}
					}
				},
				onFailure: ajaxError
			}
		);
	}
	else
		document.location.reload();
}

function cycleAccountChecked(accounts, message, idx){
	$('checkHistoryText').innerHTML += '<div>'+message+'</div>';
	setHistoryRows(idx + 1, true, accounts);
	if(idx == (accounts.length - 1)){
		$('checkText').innerHTML = '<span style="font-weight: bold;">All accounts checked</span>'; /*checked by Alexi*/
		$('checkStopButton').value = 'Close';
		$('checkStopButton').onclick = function(){cancelPopup(); document.location.reload();};
	}
	else
		setTimeout('checkAccountIdx('+(idx+1)+', true)', 10);
}

function stopChecking(){
	checkCancelled = true;
	cancelPopup();
	$('checkStopButton').onclick = stopChecking;
	$('checkAdMessage').style.display = 'none';
	$('checkAdContent').style.display = '';
	$('checkAd').style.border = '1px solid #0b70b8';
	document.location.reload();
}

function checkAll(){
	var winwidth, winheight, picWidth, picHeight, param;
	picWidth = 400;
	picHeight = 200;
	winwidth = (screen.availWidth - picWidth) / 2;
	winheight = (screen.availHeight - picHeight) / 2;
	if( pda )
		location.href = "/account/checkall.php";
	else{
		checkAccountIdx(0, true);
	}
}

function stopRedirecting(){
	window.close();
}

function redirectAccount(accountId, programName, providerName){
	checkCancelled = false;
	$('checkStopButton').onclick = stopRedirecting;
	$('checkCloseButton').onclick = stopRedirecting;
	$('checkPopupHeader').innerHTML = 'Auto-login to <span style="font-weight: bold;">"'+programName+ '"</span> website';
	$('checkText').innerHTML = '<img src="/lib/images/progressCircle.gif"> We are attempting to automatically log you in';
	$('checkNote').innerHTML = '*All advertising links open in a new window, auto-login will not stop.';
	if($('checkPopup').style.visibility != 'visible')
		showPopupWindow($('checkPopup'));
	new Ajax.Request(
		"/top10/getContent.php?AccountID="+accountId,
		{
			onSuccess: function(transport){
				if(!transport.responseJSON){
					ajaxError(transport);
					return false;
				}
				var response = transport.responseJSON;
				var content = response.Content;
				if(content != ""){
					$('checkAdContent').innerHTML = content;
					var links = $('checkAdContent').getElementsBySelector('a');
					for(var n = 0; n < links.length; n++){
						var link = links[n];
						link.target = "_blank";
						link.onclick = function(){
							new Ajax.Request(
								"/top10/countClick.php?UserID="+response.UserID+"&SocialAdID="+response.SocialAdID,
								{
									onFailure: ajaxError
								}
							)
						}
					}
				}
				processRedirect();
			},
			onFailure: ajaxError
		}
	);
//	$('checkText').innerHTML += "<br/><iframe src='/account/redirect.php?ID="+accountId+"' width='100' height='100' border='0' frameborder='0'></iframe>";
}

function getDateString(y_obj,m_obj,d_obj)
{
  var y = y_obj.options[y_obj.selectedIndex].value;
  var m = m_obj.options[m_obj.selectedIndex].value;
  var d = d_obj.options[d_obj.selectedIndex].value;
  if (y=="" || m=="") { return null; }
  if (d=="") { d=1; }
  return str= y+'-'+m+'-'+d;
}

function AdjustDates( sName, sInput1, sInput2 )
{
  y_obj1 = document.SearchForm[sInput1 + '_year'];
  m_obj1 = document.SearchForm[sInput1 + '_month'];
  d_obj1 = document.SearchForm[sInput1 + '_day'];
  y_obj2 = document.SearchForm[sInput2 + '_year'];
  m_obj2 = document.SearchForm[sInput2 + '_month'];
  d_obj2 = document.SearchForm[sInput2 + '_day'];
  var y1 = y_obj1.selectedIndex;
  var m1 = m_obj1.selectedIndex;
  var d1 = d_obj1.selectedIndex;
  var y2 = y_obj2.selectedIndex;
  var m2 = m_obj2.selectedIndex;
  var d2 = d_obj2.selectedIndex;
  days1 = y1 * 400 + m1 * 40 + d1;
  days2 = y2 * 400 + m2 * 40 + d2;
  if( ( sName == sInput1 ) && (
  ( y1 > y2 )
  || ( ( y1 == y2 ) && ( m1 > m2 ) )
  || ( ( y1 == y2 ) && ( m1 == m2 ) && ( d1 > d2 ) ) ) )
  {
    y_obj2.selectedIndex = y_obj1.selectedIndex;
    m_obj2.selectedIndex = m_obj1.selectedIndex;
    d_obj2.selectedIndex = d_obj1.selectedIndex;
  }
  var y1 = y_obj1.selectedIndex;
  var m1 = m_obj1.selectedIndex;
  var d1 = d_obj1.selectedIndex;
  var y2 = y_obj2.selectedIndex;
  var m2 = m_obj2.selectedIndex;
  var d2 = d_obj2.selectedIndex;
  if( ( sName == "Form" ) && (
  ( y1 > y2 )
  || ( ( y1 == y2 ) && ( m1 > m2 ) )
  || ( ( y1 == y2 ) && ( m1 == m2 ) && ( d1 > d2 ) ) ) )
  {
  	alert( 'The <?=$sDate2Caption?> has to be after the <?=$sDate1Caption?>' );
  	return false;
  }
  return true;
}

function switchExt( n ){
	var extImage = document.getElementById('extImage'+n);
	var extRow = document.getElementById('extRow'+n);
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000));
	if( extImage.src.indexOf("/lib/images/bulletPlus1.gif") >= 0 ){
		extImage.src = "/lib/images/bulletMinus1.gif";
		extRow.style.display = '';
		setCookie('ext'+n, '1', expdate, "/account/list.php");
	}
	else{
		extImage.src = "/lib/images/bulletPlus1.gif";
		extRow.style.display = 'none';
		setCookie('ext'+n, '0', expdate, "/account/list.php");
	}
}

function forceExt( n, enabled ){
	var extImage = document.getElementById('extImage'+n);
	var extRow = document.getElementById('extRow'+n);
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000));
	if( enabled ){
		extImage.src = "/lib/images/bulletMinus1.gif";
		extRow.style.display = '';
		setCookie('ext'+n, '1', expdate, "/account/list.php");
	}
	else{
		extImage.src = "/lib/images/bulletPlus1.gif";
		extRow.style.display = 'none';
		setCookie('ext'+n, '0', expdate, "/account/list.php");
	}
}

function switchSection( n ){
	var extImage = document.getElementById('allExtImage'+n);
	if( extImage.src.indexOf("/lib/images/bulletPlus1.gif") >= 0 ){
		extImage.src = "/lib/images/bulletMinus1.gif";
	}
	else{
		extImage.src = "/lib/images/bulletPlus1.gif";
	}
}

function sectionState( n ){
	var extImage = document.getElementById('allExtImage'+n);
	return ( extImage.src.indexOf("/lib/images/bulletPlus1.gif") >= 0 );
}

var activePopup = 0;
var nextPopup = 0;
var showEffect = null;
var hideEffect = null;
var showTimer = 0;
var popupHeight;
var popupTop;

function clickRow( id ){
	var fader = $('fader');
	fader.style.height = $('body').getHeight() + 'px';
	fader.style.visibility = 'visible';
	fader.onclick = function(){
		hidePopup(id)
		fader.style.visibility = 'hidden';
		fader.onclick = function(){cancelPopup()};
	};
	if( showTimer > 0 )
		clearTimeout( showTimer );
	showPopup(id);
	setTimeout('clearTimeout(showTimer)', 100);
}

function overRow( id ){
	var fader = $('fader');
	if(fader.style.visibility == 'visible')
		return false;
	if( showTimer > 0 )
		clearTimeout( showTimer );
	showTimer = setTimeout('showPopup("'+id+'")', 200);
}

function outRow( id ){
	var fader = $('fader');
	if(fader.style.visibility == 'visible')
		return false;
	if( showTimer > 0 )
		clearTimeout( showTimer );
	showTimer = setTimeout('hidePopup("'+id+'")', 200);
}

function showPopup( id ){
	var img = $('balanceGraph'+id);
	if(img)
			img.src = img.getAttribute('realSrc');
	var popup = $('extRow'+id);
	// hide current other popup, if any
	if( ( activePopup != 0 ) && ( activePopup != id ) ){
		if( hideEffect ){
			hideEffect.cancel();
			nextPopup = 0;
		}
		popupHidden();
	}
	// stop if hiding current popup
	if( ( activePopup == id ) && hideEffect ){
		hideEffect.cancel();
		hideEffect = null;
		activePopup = 0;
		nextPopup = 0;
	}
	// show new popup if any
	if( popup && ( activePopup != id ) && !hideEffect && !showEffect ){
		activePopup = id;
		var accountCell = $('accountCell'+parseInt(id));
		var tblAccounts = $('tblAccounts');
		var rowHeight = accountCell.getHeight();
		var top = accountCell.cumulativeOffset().top + rowHeight;
		popup.style.left = accountCell.cumulativeOffset().left + 'px';
		popup.style.width = tblAccounts.getWidth() - 40 + 'px';
		popup.style.display = '';
		var inDiv = popup.firstDescendant();
		inDiv.style.width = popup.style.width;
		var height = inDiv.getHeight() + 2;
		var scrollOffset = document.viewport.getScrollOffsets().top;
		var bodyHeight = getBodyHeight();
//		alert( body.getHeight() );
	/*	alert( top );
		alert( height );
		alert( bodyHeight );
		alert( scrollOffset );*/
		popupHeight = height;
		if( ( ( bodyHeight + scrollOffset ) < ( top + height ) ) && ( ( top - rowHeight - scrollOffset ) >= height ) ){
			// popup top
			top -= rowHeight;
			popupTop = true;
			popup.style.top = top - height + 'px';
			popup.style.marginTop = height + 'px';
		}
		else{
			// popup down
			popupTop = false;
			popup.style.top = top + 'px';
//			showEffect = new Effect.Morph('extRow'+id, {style: 'height: '+height+'px; padding-top: 0px;', duration: 0.5, afterFinish: popupShown});
		}
		showEffect = new Effect.Morph('extRow'+id, {style: 'height: '+height+'px; margin-top: 0px;', duration: 0.5, afterFinish: popupShown});
	}
}

function getBodyHeight() {
	if (self.innerWidth) return self.innerHeight;
	else if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientHeight;
	else if (document.body) return document.body.clientHeight;
}


function popupShown(){
	showEffect = null;
}

function hidePopup( id ){
	// hide popup
	if( ( activePopup != 0 ) && !hideEffect ){
		if( showEffect ){
			showEffect.cancel();
			showEffect = null;
		}
		var popup = $('extRow'+activePopup);
		hideEffect = new Effect.Morph('extRow'+activePopup, {style: 'height: 1px; margin-top: '+popupHeight+'px', duration: 0.5, afterFinish: popupHidden});
	}
}

function popupHidden(){
	if( activePopup != 0 ){
		var popup = $('extRow'+activePopup);
		popup.style.display = 'none';
		popup.style.height = '1px';
		popup.style.marginTop = '0px';
		activePopup = 0;
		hideEffect = null;
		if( nextPopup != 0 ){
			setTimeout('showPopup('+nextPopup+')', 200);
			nextPopup = 0;
		}
	}
}

var revealLink;
var revealAccountId;

function revealPassword( fieldId, link, accountId ){
	if(link.innerHTML == 'Hide password'){
		var field = $($('revealFieldId').value);
		var field2 = createInput('password');
		field2.value = field.value;
		field.parentNode.replaceChild(field2,field);
		link.innerHTML = 'Reveal password';
		return;
	}
	revealAccountId = accountId;
	var box = $('revealPasswordBox');
	var input = $(fieldId);
	revealLink = link;
	var pos = input.positionedOffset();
	box.style.top = pos.top + input.getHeight() + 'px';
	box.style.left = pos.left + 'px';
	box.style.width = input.getWidth();
	$('revealFieldId').value = fieldId;
	Event.observe($('revealPassword'), 'keypress', function(event){ if(event.keyCode == Event.KEY_RETURN) checkRevealPassword();});

	new Effect.Appear('revealPasswordBox', {
		duration: 0.7,
		afterFinish: function() { $('revealPassword').focus(); }
	});
}

function cancelReveal(){
	new Effect.Fade('revealPasswordBox', {
		duration: 0.7,
		afterFinish: function() { $($('revealFieldId').value).focus(); }
	});
}

function checkRevealPassword(){
	new Ajax.Request('/account/checkUserPassword.php', {
	  onSuccess: checkUserPasswordSuccess,
	  parameters: "Password="+encodeURI($('revealPassword').value)+'&AccountID='+encodeURI(revealAccountId),
	  onFailure: ajaxError
	});
}

function createInput(type){
	var field2 = document.createElement("input");
	// <input class="inputTxt" type="text" name="Pass" autocomplete="off" id="fldPass" maxlength="40" size="42" value="********">
	field2.setAttribute('type', type);
	field2.setAttribute('className', 'inputTxt');
	field2.setAttribute('class', 'inputTxt');
	field2.setAttribute('name', 'Pass');
	field2.setAttribute('id', 'fldPass');
	field2.setAttribute('maxlength', '40');
	field2.setAttribute('size', '42');
	return field2;
}

function checkUserPasswordSuccess(transport){
	if(!transport.responseJSON){
		ajaxError(transport);
		return false;
	}
	var response = transport.responseJSON;
	if (response.Error == ''){
		var field = $($('revealFieldId').value);
		//var field2 = field.cloneNode(false);
		//field2.type='text';
		var field2 = createInput('text');
		field2.value = response.Password;
		field.parentNode.replaceChild(field2,field);
		//field.type = 'text';
		cancelReveal();
		field2.focus();
		revealLink.innerHTML = 'Hide password';
	}
	else{
		alert(response.Error);
	}
}

function ajaxError(transport){
	if(transport.status != 0)
		if(document.location.host.toLowerCase().indexOf('awardwallet.com') == -1)
			alert('Error ' + transport.status + ' ' + transport.statusText + "\n" + transport.responseText);

}

var activePopup;
var activePopupWindow;
var reloadAfterClose;

function showPopupWindow(popup){
	if(activePopupWindow && (activePopupWindow != popup))
		activePopupWindow.style.display = 'none';
	reloadAfterClose = 0;
	activePopupWindow = popup;
	popup.style.left = ( document.viewport.getWidth() / 2 - popup.getWidth() / 2 ) + 'px';
	popup.style.top = ( document.viewport.getHeight() / 2 - popup.getHeight() / 2 + document.viewport.getScrollOffsets().top ) + 'px';
	popup.style.display = 'none';
	popup.style.visibility = 'visible';
	var fader = $('fader');
	fader.style.height = $('body').getHeight() + 'px';
	fader.style.visibility = 'visible';
	setTimeout("new Effect.SlideDown('"+popup.id+"', {duration: 0.7})", 300 );
}

function hidePopupWindow(){
	if(activePopupWindow){
		activePopupWindow.style.visibility = 'hidden';
		activePopupWindow.style.display = '';
		if($('messagePopup')){
			$('messagePopup').style.width = '';
			$('messageOKButton').style.width = '120px';
		}
	}
}

function cancelPopup(){
	new Effect.Shrink(activePopupWindow, {duration: 0.5});
	if( activePopupWindow.id == 'framePopup' )
		setTimeout('$("popupFrameContainer").innerHTML = ""', 500);
	setTimeout('popupCancelled()', 600 );
}

function popupCancelled(){
	var fader = $('fader');
	fader.style.visibility = 'hidden';
	hidePopupWindow();
	if( reloadAfterClose == 1 )
		document.location.reload();
}

function showPolicy(){
	var winwidth, winheight, picWidth, picHeight;
	picWidth = 700;
	picHeight = 550;
	winwidth = (screen.availWidth - picWidth) / 2;
	winheight = (screen.availHeight - picHeight) / 2;
	statusPage = window.open("/user/termsOfUse.php", "termsOfUse", "height="+picHeight+",width="+picWidth+",left="+winwidth+",top="+winheight+",scrollbars=yes,resizable=yes")
	statusPage.focus()
}

function showFrame(src){
	$('popupFrameContainer').innerHTML = '<iframe id="popupFrame" src="about:blank" width="100%" height="250" border="0" frameborder="0" onload="popupFrameLoadComplete()"></iframe>';
	$('popupFrame').src = src;
}

function popupFrameLoadComplete(){
	var frame = $('popupFrame');
	if(frame.src == 'about:blank')
		return;
	// show abnormally loaded frame
	var document;
	if(frame.contentWindow)
		document = frame.contentWindow.document;
	else
		document = frame.contentDocument;
	if( document.body.innerHTML.indexOf('<!-- frame header end -->') < 0 ){
		var popup = $('framePopup');
		frame.style.height = '340px';
		popup.style.height = '400px';
		popup.style.width = '';
		$('framePopupDiv').style.height = '400px';
		showPopupWindow(popup);
	}
}

function popupFrameLoaded(success, width, height, closePopup, reloadParent){
	var frame = $('popupFrame');
	var popup = $('framePopup');
	if( closePopup == 1 ){
		reloadAfterClose = reloadParent;
		cancelPopup();
		return;
	}
	height = height + 30;
	if( popup.style.visibility == 'visible' ){
		// only update size
		if( frame.getHeight() < height + 20 ){
			new Effect.Morph(frame, {style: 'height: '+height+'px', duration: 0.5});
			height = height + 20;
			new Effect.Morph(popup, {style: 'height: '+height+'px', duration: 0.5});
			new Effect.Morph($('framePopupDiv'), {style: 'height: '+height+'px', duration: 0.5});
		}
		return;
	}
	if( height < 150 )
		height = 150;
	frame.style.height = height + 'px';
	height = height + 20;
	popup.style.height = height + 'px';
	popup.style.width = width;
	$('framePopupDiv').style.height = height + 'px';
	showPopupWindow(popup);
}
/*
function kayakSearch(){
	showFrame('/kayakSearch.php');
}
*/

function tradeMiles(accountId){
	new Ajax.Request('/account/tradeText.php?ID='+accountId, {
		onSuccess: function(transport){
			if(!transport.responseJSON){
				ajaxError(transport);
				return false;
			}
			var response = transport.responseJSON;
			if(response.Status == "Unauthorized"){
				authorize();
				return false;
			}
			showMessagePopup('info', response.Title, response.Text);
			$('messageOKButton').value = "Close";
			return true;
		},
		onFailure: ajaxError
	});
}

function showGoals(){
	var cells = $('body').getElementsBySelector('td.goal');
	for(var n = 0; n < cells.length; n++){
		var cell = cells[n];
		var offset = -1000 + Math.round(cell.getWidth() * cell.getAttribute("goalComplete"));
		cell.style.backgroundPosition = offset + 'px';
	}

}

function setGoal(){
	showFrame('/account/setGoal.php');
}

var reviewProviderId;

function showLastReview(a, providerId){
	a = $(a);
	var top = a.cumulativeOffset().top + 20;
	var left = a.cumulativeOffset().left;
	var popup = $('reviewPopup');
	popup.style.left = left + 'px';
	popup.style.top = top + 'px';
	popup.style.visibility = 'visible';
	popup.style.height = '30px';
	$('reviewPopupText').innerHTML = 'Loading..';
	popup.style.display = '';
	reviewProviderId = providerId;
	new Ajax.Request('/rating/reviewText.php?ID='+providerId, {
		onSuccess: function(transport){
			if(!transport.responseJSON){
				ajaxError(transport);
				return false;
			}
			var response = transport.responseJSON;
			if(reviewProviderId == response.providerId){
				$('reviewPopupText').innerHTML = response.review;
				popup.style.height = $('reviewPopupText').getHeight() + 'px';
				return true;
			}
			return false;
		},
		onFailure: ajaxError
	});
}

function hideLastReview(){
	var popup = $('reviewPopup');
	popup.style.display = 'none';
}

function rateReview(link, reviewId, providerId, score){
	var params = new Hash();
	params.set("ReviewID", reviewId);
	params.set("ProviderID", providerId);
	params.set("Useful", score);
	new Ajax.Request(
		"/rating/useful.php",
		{
			parameters: params,
			onSuccess: function(transport){
				if(transport.responseText != "OK"){
					alert(transport.responseText);
					return false;
				}
				link.parentNode.innerHTML = "Thank you. Your opinion is very important to us.";
				return true;
			},
			onFailure: ajaxError
		}
	);

}

function ungroupClick(){
	grouped = !document.getElementById('ungroupCheck').checked;
	d = new Date();
	setCookie("grouped", grouped, new Date(d.getFullYear() + 2, 1, 1), "/account/", "", false);
	document.location.reload();
}

function onlyCouponsClick(){
	onlyCoupons = document.getElementById('couponCheck').checked;
	var url = document.location.href;
	url = url.replace(/[\&\?]Coupons=\d+/ig, "");
	if(onlyCoupons){
		if(url.indexOf("?") >= 0)
			url = url + "&";
		else
			url = url + "?";
		url = url + "Coupons=1";
	}
	document.location.href = url;
}


function sendReminder(agentId, element, source){
	new Ajax.Request(
		"/agent/sendReminder.php?UserID="+agentId+'&Source='+source,
		{
			onSuccess: function(transport){
				element.style.display = 'none';
				element.innerHTML = transport.responseText;
				new Effect.Appear(element);
			},
			onFailure: ajaxError
		}
	);
}
