var request = false;
var movie = "";

try {
 request = new XMLHttpRequest();
} catch (trymicrosoft) {
 try {
   request = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (othermicrosoft) {
   try {
	 request = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (failed) {
	 request = false;
   }  
 }
}

if (!request)
 alert("Problem: Couldn't tell your friend");


function submitForm() {
     var a = document.getElementById("p_name").value;
	 var c = document.getElementById("t_email").value;
	 var d = document.getElementById("comment").value;
	
	 var url = "tellAFriendHandler.php";
	 var queryString = "p_name=" + escape(a)+"&email="+ escape(c)+"&comment="+ escape(d);
	
	 request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
     request.open("POST", url, true);	 
     request.send(queryString);
}


// validates that the field value string has one or more characters in it
function isNotEmpty(elem) {
    var str = elem.value;
    var re = /.+/;
    if(!str.match(re)) {
        //alert("Please fill in the required field.");
        return false;
    } else {
        return true;
    }
}



/**
	<input type="text" size="30" name="eMail" id="eMail" 
    onchange="if (isNotEmpty(this)) {isEMailAddr(this)}">
*/
// validates that the entry is formatted as an email address
//param: the element reference
function isEmailAddr(elem) {
    var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        //alert("Verify the email address format.");
        return false;
    } else {
        return true;
    }
}

//validates that the entry is a positive or negative number
function isNumber(elem) {
    var str = elem.value;
    var re = /^[-]?\d*\.?\d*$/;
    str = str.toString( );
    if (!str.match(re)) {
        //alert("Enter only numbers into the field.");
        return false;
    }
    return true;
}

// validate that the user made a selection other than default
function isChosen(select) {
    if (select.selectedIndex == 0) {
        //alert("Please make a choice from the list.");
        return false;
    } else {
        return true;
    }
}


//validates the email address contained in the element specified
//shows some information message based on the outcome of the user input
function validateEmail(elem){
	var status = isEmailAddr(elem);
	var msgElem = document.getElementById("newsMsg");
	
	if(status){
		//switchOff('errorMsg');
		//switchOn('successMsg');
		msgElem.innerHTML = "Sending Email...";
		msgElem.style.display = "block";
		msgElem.style.color = "green";
		
		var url = "newsletter/signup_user.php";
		var queryString = "e=" + escape(elem.value);
		//console.log(queryString);
		request.onreadystatechange = handleStateChange;
		request.open("POST", url, true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
		request.send(queryString);
		
		//setTimeout(function(){switchOff('errorMsg'); switchOff('successMsg');elem.value="";}, 2000);
	}else{
		msgElem.style.color = "red";
		msgElem.style.display = "block";
		msgElem.innerHTML = "There was an error in the email you just typed in. Please re-type it.";
		
		setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";}, 5000);
		/*switchOff('successMsg');
		switchOn('errorMsg');
		
		setTimeout(function(){switchOff('errorMsg'); switchOff('successMsg');}, 2000);*/
	}
}

function handleStateChange(){
	if(request.readyState == 4){
		if(request.status == 200){
			var response = request.responseText;
			var msgElem = document.getElementById("msg");
			
			if(response){//success = 1, failure = 0 or (empty)
				msgElem.style.color = "green";
				msgElem.style.display = "block";
				msgElem.innerHTML = "Successfully signed you up for the newsletter. Log in to your mailbox to activate it. Thank you.";
				
				setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";}, 5000);
			}else{
				msgElem.style.color = "red";
				msgElem.style.display = "block";
				msgElem.innerHTML = "An error occurred in trying to sign you up for our newsletter because you have already signed up for it before. If this is not the case, try to sign up again and if the problem persists, try to send a mail to us at <a href='mailto:customercare@fusiongreen.com'>customercare@fusiongreen.com</a>. Thank you.";
				
				setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";}, 5000);
			}
		}else{
			msgElem.style.color = "red";
			msgElem.style.display = "block";
			msgElem.innerHTML = "Error connecting to server";
			
			setTimeout(function(){msgElem.innerHTML = "";}, 2000);
		}
	}
}

var v1 = new Array;//store sthe states of the panels (whether they are visible or not)
//Hides the element specified
function switchOff(objId){
	v1[objId] = false;
	var elementStyle = document.getElementById(objId).style;
	elementStyle.display = "none";return false;
}

//Shows the element sopecified
function switchOn(objId){
	v1[objId] = true;
	var elementStyle = document.getElementById(objId).style;
	elementStyle.display = "block";return false;
}

/*function tellAFriend(){
	switchOff('tellAFriend');
	switchOn('thankYou');
	submitForm();
	
	//clear the fields
	document.getElementById("p_name").value="";
	document.getElementById("t_email").value="";
	document.getElementById("comment").value="";
	return false;
}*/

function tellAFriend(){
	$(document).ready(function(){
		//clear the previous error if any
		$('#ppmsg').remove();
		
		//check if the parameters are correct, and if not, report error
		$a = $('#p_name');
		$b = $('#t_email');
		$c = $('#comment');
		
		$aVal = $a.val();
		$bVal = $b.val();
		$cVal = $c.val();
		$preHTML = "<div id='ppmsg' style='background: #FFC; color: #CC0000; font-size: 11px; padding: 1px;'>";
		$postHTML = "</div>";
		
		if(!$aVal){
			$('div#popupForm h2').after($preHTML+'You need to specify your name'+$postHTML);
			return false;
		}
		
		if(!$bVal){
			$('div#popupForm h2').after($preHTML+'You need to specify your email address'+$postHTML);
			return false;
		}
		
		if(!$bVal.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)){
			$('div#popupForm h2').after($preHTML+'The email address specified is not valid'+$postHTML);
			return false;
		}
		
		if(!$cVal){
			$('div#popupForm h2').after($preHTML+'You need to enter you comments'+$postHTML);
			return false;
		}
		
		//hide the tell a friend window
		$('#tellAFriend').hide('fast');
		$('#thankYou').show('fast');
		
		
		$form = $('div#popupForm form');
		
		$url = "tellAFriendHandler.php";
		$data = "p_name="+escape($aVal)+"&email="+escape($bVal)+"&comment="+escape($cVal);
		$.post($url, $data, function(){
			//clear the fields
			$a.val('');
			$b.val('');
			$c.val('');
		});
	});
	return false;
}

function tellAFriendAboutThis(){
	 var p_name = document.getElementById("p_name").value;
	 var email = document.getElementById("email").value;
	 var comments = document.getElementById("comment").value;
	 var m = document.getElementById("movie").value;
	 var t = document.getElementById("type").value;
	 
	 var url = "tellAFriendHandler.php";
	 var queryString = "p_name=" + escape(p_name)+"&email="+ escape(email)+"&comment="+ escape(comments)+"&movie="+ escape(m)+"&t="+ escape(t);
	 //console.log(queryString);
     request.open("POST", url, true);
	 request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
     request.send(queryString);
	
	switchOff('a');switchOff('c');switchOff('e');switchOff('comments');switchOn('thanks');

	return false;
}

function f(){
	var msgElem = document.getElementById("fMsg");
	
	var isv = isEmailAddr(document.getElementById("email"));
	if(!isv){//notify the user that the email entered is not a valid one
		switchOff('a');switchOff('b');switchOff('c');switchOff('d');switchOff('e');switchOff('f');
		
		msgElem.style.color = "red";
		msgElem.style.display = "block";
		msgElem.innerHTML = "There was an error in the email you filled in. Please correct the error and resubmit the form.";
		setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";switchOff('f');switchOn('a');switchOn('b');switchOn('c');switchOn('d');switchOn('e');switchOff('fMsg');}, 5000);
		
		
		
		return false;
	}
	
	var a = document.getElementById("email").value;
	var b = document.getElementById("country").value;
	if(b == 0){
		switchOff('a');switchOff('b');switchOff('c');switchOff('d');switchOff('e');switchOff('f');
		
		msgElem.style.color = "red";
		msgElem.style.display = "block";
		msgElem.innerHTML = "You need to specify the country you are in. Please select it from the menu provided and resubmit the form.";
		setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";switchOff('f');switchOn('a');switchOn('b');switchOn('c');switchOn('d');switchOn('e');switchOff('fMsg');}, 5000);
		
		return false;
	}
	//	alert('You need to specify the country you are in');
	var c = document.getElementById("fd").value;
	if(!isNotEmpty(document.getElementById("fd"))){
		switchOff('a');switchOff('b');switchOff('c');switchOff('d');switchOff('e');switchOff('f');
		
		msgElem.style.color = "red";
		msgElem.style.display = "block";
		msgElem.innerHTML = "You need to fill in the message you want to send. Please type the message and then resubmit the form.";
		setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";switchOff('f');switchOn('a');switchOn('b');switchOn('c');switchOn('d');switchOn('e');switchOff('fMsg');}, 5000);
		
		return false;
	}
	
	var url = "internalFeedback.php";
	var queryString = "email=" + escape(a)+"&country=" + escape(b)+"&feedback="+ escape(c)+"&s=mini";
    request.open("POST", url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    request.send(queryString);
	
	msgElem.style.color = "green";
	msgElem.style.display = "block";
	msgElem.innerHTML = "Your feedback has been successfully sent. Thanks for sending us a feedback.";
	
	switchOff('a');switchOff('b');switchOff('c');switchOff('d');switchOff('e');
	setTimeout(function(){msgElem.innerHTML = "";msgElem.style.display = "";document.getElementById("email").value="";document.getElementById("country").value="0";document.getElementById("fd").value="";switchOff('f');switchOn('a');switchOn('b');switchOn('c');switchOn('d');switchOn('e');switchOff('fMsg');}, 5000);
    
	return false;
}

function displayIt(){
	//switch off the thank you panel if it is visible before showing the
	//next tell a friend panel
	if(v1['thankYou'])
		switchOff('thankYou');
		
	return switchOn('tellAFriend');
}

function submitFeedback(form){
	if(isNotEmpty(form.m_name)){
		//check to see if the telephone field contains only numbers
		if(!isNumber(form.m_tel)){
			alert("The telephone number field contains invalid characters");
			return false;
		}
		
		if(isNotEmpty(form.m_email)){
			//check to see if the email is valid
			if(!isEmailAddr(form.m_email)){
				alert("Please specify a valid email address.");
				return false;
			}
			
			if(isChosen(form.m_country)){
				if(isNotEmpty(form.m_msg)){
					return true;
				}else{
					alert("A message must be typed.");
				}
			}else{
				alert("The country you are in should be specified.");
			}
		}else{
			alert("The email field should be filled.");
		}
	}else{
		alert("The name field should be filled.");
	}
	
	return false;
}


function searchFocus(el, hasFocus){
	handleFocus(el, hasFocus, 'Search');
}

function emailFocus(el, hasFocus){
	handleFocus(el, hasFocus, 'Enter Email and Press ENTER');
}

//handles the focus and blur events detected on the element passed to it
function handleFocus(el, hasFocus, defaultText){
	var v = el.value;
	
	if(hasFocus){
		if(v == defaultText)
			el.value='';
	}else{
		if( v == '')
			el.value = defaultText;
	}
}