// JavaScript Document
/**
 * @var String Token form token
 */
var Token;


/**
 * @var Object refForm Reference to the current form being used
 */
var refForm;


/*
 * Main Ajax call.
 */
var submitNewsletterForm = function(elmt)
{
	refForm	= elmt.form;
	
	if (undefined != Token) {
		elmt.form.token.value	= Token;
	}
	
	new Ajax.Request(elmt.form.action, {
			method:		elmt.form.method,   
			parameters: Form.serialize(elmt.form),
			onComplete:	newsletterReturn,
			onFailure:	function(req) {alert("Sorry but there has been an error. Please try again.")}
		});
	
	disableForm(true);
}


/*
 * resultsAction for the main Ajax call.
 */
var newsletterReturn = function(req, json)
{
	try {
		updateToken(json.token);
		displayMessage(json.message);
	} catch (e) {
		message		= new Array();
		message[0]	= "Sorry, there was an error, please try again";
		displayMessage(message);
	}
	
	disableForm(false);
}

/*
 * loadingIcon for the Ajax call.
 */
var disableForm = function(state)
{
	if (refForm) {
		// Get all the images within the form
		images	= refForm.getElementsByTagName("img");
		
		// Look for the loading icon
		for (a = 0; a < images.length; a++) {
			if ("loading" == images[a].className) {
				loadingIcon	= images[a];
				break;
			}
		}
		
		// Ditch the rest of the image references
		images	= null;
		
		// If we have found a loading icon, lets display/hide it
		if (loadingIcon) {
			if (state) {
				loadingIcon.style.display	= "";
			} else {
				loadingIcon.style.display	= "none";
			}
		}
		
		// Now lets disable/enable the form inputs to prevent resubmission
		// Check if we also have an input image as a submit button, and hide/display it
		inputs	= refForm.getElementsByTagName("input");
		for (a = 0; a < inputs.length; a++) {
			if ("image" == inputs[a].type) {
				submitButton	= inputs[a];
				submitButton.style.display	= state ? "none" : "";
			} else {
				inputs[a].disabled	= state;
			}
		}
	}
}

/*
 * each Ajax call returns a new token. Here is where we update it.
 */
var updateToken = function(newToken)
{
    Token = newToken;
}


/*
 * Each payload comes back with a message array. If there's anything
 * in it, display it.
 */
var displayMessage = function(messages)
{
	var msg	= "";
	
	if (refForm) {
		messageDiv	= refForm.getElementsByClassName('message');
		messageDiv	= messageDiv[0];
		//messageDiv.innerHTML	= "";
	}

	if ((messages != undefined) && (messages.length > 0)) {
		for (a = 0;a < messages.length; a++) {
			msg	+= messages[a] + (messageDiv ? "<br/>" : "\n");
		}
	}

	if (msg) {
		try {
			messageDiv.style.display	= "";
			messageDiv.innerHTML		= "<div class='messages'>" + msg + "</div>";
		} catch(e) {
			alert(msg);
		}
	} else {
			messageDiv.style.display	= "block";
	}
	
	return;
}

var resetCaptchaForm = function(showId)
{
	var show = showId;
	
	document.getElementById('fieldSet_' + show).style.display = 'block';
	document.getElementById('crossRed_' + show).style.display = 'none';
	document.getElementById('closeBtn_' + show).style.display = 'none';
	document.getElementById('thanksMsg_' + show).style.display = 'none';
	
	document.getElementById('submitAlert_' + show).style.display = 'none';
}
 
var startCaptcha = function(captchaId, showId, codeResultImg)
{
	var show = showId;
	
	if (codeResultImg != '1') {
		document.getElementById('crossRed_' + show).style.display = 'block';
		document.getElementById('crossRed_' + show).src = '/images/cross_red.png';
	}
	
	if (codeResultImg == '1') {
		document.getElementById('crossRed_' + show).style.display = 'block';
		document.getElementById('crossRed_' + show).src = '/images/submit_tick.png';
		document.getElementById('fieldSet_' + show).style.display = 'none';
		document.getElementById('closeBtn_' + show).style.display = 'block';
		document.getElementById('thanksMsg_' + show).style.display = 'block';
	}
	
	document.getElementById('captchaImg_' + show).src = '/images/captcha/' + captchaId + '.png';
	document.getElementById('captchaId_' + show).value = captchaId;
	document.getElementById('captchaInput_' + show).value = 'Enter Code';
}
 
var refreshCaptcha = function(captchaId, showId, captchaSubmit, question, name, userSession)
{
	var show = showId;

	var controller = document.getElementById('captchaController_' + show).value;

	if (controller) {
		if (controller == 'index') {
			if (captchaSubmit == true) {
				document.getElementById('submitAlert_' + show).style.display = 'block';
			}
			
			document.getElementById('captchaPostName_' + show).value = name;
			document.getElementById('captchaPostQuestion_' + show).value = question;
		}
	}
	
	document.getElementById('captchaImg_' + show).src = '/images/captcha/' + captchaId + '.png';
	document.getElementById('captchaId_' + show).value = captchaId;
		
	if (userSession == true) {
		document.getElementById('chatCaptcha').style.display = 'none';
		document.getElementById('captchaInput_' + show).value = 'true';
	} else {
		document.getElementById('captchaInput_' + show).value = 'Enter Code';
	}
}

function fbDialog(u,w,h) {
	if(w == undefined){var w=600;}
	if(h == undefined){var h=400;}
	window.open(u,'fbdialogpopup','width='+w+',height='+h);
}

/*
 * Add some helpfull String trimming addons
 */
String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function()
{
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function()
{
	return this.replace(/\s+$/,"");
}

//Methods for show countdown timer


var countdown = {
					started: false,			//Make sure it only starts once
					timeLeft:0,				//Seconds till show start
					displayTimer: null, 	//Reference to the timer process
					timeLeftObject: null,   //h:m:s time left
					interval: 120000,		//Synchronise with server interval 120000 = 3mins
				};


function handleCountdown() {
	if($j('span.timer-wrap').length >0) {
		if(window.countdown.displayTimer !== null) {
			clearInterval(window.countdown.displayTimer);
			window.countdown.displayTimer = null;
		}

		window.countdown.timeLeftObject = secondsToTime(window.countdown.timeLeft);	
		
		if (window.countdown.displayTimer === null) {
			window.countdown.displayTimer = setInterval("tick()",1000);
		}		
	}	
}

function tick() {
	
	if (window.countdown.timeLeftObject.s <= 0 && window.countdown.timeLeftObject.m <= 0) {
		$j('span.timer-wrap').html('ANY SECOND NOW');
		clearInterval(window.countdown.displayTimer);
		return;
	} 

	if (window.countdown.timeLeftObject.s === 0) {
		window.countdown.timeLeftObject.s = 59;
		if (window.countdown.timeLeftObject.m >0) {
			window.countdown.timeLeftObject.m--;
		}
	} else {
		window.countdown.timeLeftObject.s--;
	}
	$j('span.timer-prefix').html("IN ");
	$j('span.timer-minutes').html((window.countdown.timeLeftObject.m < 10  && window.countdown.timeLeftObject.m > 0) ? '0' + window.countdown.timeLeftObject.m + ' mins ': window.countdown.timeLeftObject.m + ' mins ' );
	$j('span.timer-seconds').html(window.countdown.timeLeftObject.s < 10 ? '0' + window.countdown.timeLeftObject.s + ' secs': window.countdown.timeLeftObject.s + ' secs');
}

function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));
   
    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
 
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
   
    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
}

function scheduleCountdown() {
	//console.log("scheduleCountdown called");
	if(window.countdown.started === false){
		//console.log("scheduleCountdown activated");
		checkChatTimer();
		setInterval('checkChatTimer()', window.countdown.interval);
		window.countdown.started = true;
	}
}
function checkChatTimer(){
		
	this.success = function(o) {
		if(o.responseText !== undefined) {
			
			var json = eval("(" + o.responseText + ")");

			if(typeof json.countdown !== 'undefined' && json.countdown) {
				window.countdown.timeLeft = json.countdown;
				handleCountdown();
			}

		}
	};

	this.failure = function(o) {
		
	};

	var randomnumber = Math.floor(Math.random()*1000001);
	
	var sUrl = baseUrl + "/ajaxcheckchatcountdown/" + alias + "/" + randomnumber;
	YAHOO.util.Connect.asyncRequest('GET', sUrl, this, null);
}	


