/** *******Gor Gasparyan*********** */
/*
 * this document have a dependency with 
 * cookie.js,prototype.js, effects.js,and stylesheet.css
 * so do not forget to include following lines before the usage
 * 
<link type="text/css" href="./css/stylesheet.css" rel="stylesheet" />
<script src="./javascript/prototype.js"></script>
<script src="./javascript/effects.js"></script>
<script src="./javascript/cookie.js"></script>
<script src="./javascript/popup.js"></script>
 * 
 * before using this document
 */


/*
 * HTML part need to be added to the aspx file where should it appear.
 * 
<div id="header-middle">
<div class="form-login" id="form-login" style="display: none;">
                    	<div class="closeform"><a href="javascript:void(0)" onclick="subscribeForNewsletterFromPopup('postpone');"><img src="./img/close.jpg" alt="" /></a></div>
                        <!--  <form name="subscribeViaEmailForm" id="signinform" method="post" action="$siteRoot/Authentication/login.rails" >-->
                            <center><div class="content-form-login">
                            	<div class="form-login-username">
                                	Email
                                </div>
                                <div class="clear"></div> 
                                <div class="form-login-email">
                                	<input type="text"  size="70" name="emailsubscribtion" id="emailsubscribtion" value="" validators="blank" />
                                </div>
                                <div class="clear"></div>
                                <div class="form-subscribe-buton">
                                	<span><input onclick="subscribeForNewsletterFromPopup('subscribe', document.getElementById('emailsubscribtion').value);" type="image" src="./img/subscribe.png" /></span>
                                	<span><input onclick="subscribeForNewsletterFromPopup('reject');" type="image" src="./img/reject.png" value="reject" /></span>
                                	<input onclick="subscribeForNewsletterFromPopup('postpone');" type="image" src="./img/postpone.png" value="postpone" />
                                </div>
                                </center>
                                <div class="clear"></div>
                            </div>
                        <!--</form>-->
                    </div>
        </div>
 */

// time interval befor showing popup in miliseconds
var timeInterval = 1 * 10000;

// flag to indicate does the time intervall pass
var isTimeIntervalPassed = false;

// this variable sets when first time user enter the site.
var startOfPopUpTimePeriod = null;
var startOfPopUpTimePeriodReadFromCookie = null;


var showPopupTimeOut = null;

//variable need to be set from back end code. indicates whether the user is logged in or no.
var isUserLoggedIn = false;

//variable need to be set from back end code. indicates whether the user is subscribed or no.
var isUserSubscribed = false;

//The url where the subscribtion should be implemented
var subscriptionURL = '';


//this function should be called in onload event of the body to start timer.
function checkAndShowPopup(name)
{
	if(ckeckTimeInterval())
	{
		clearTimeout(showPopupTimeOut);
		
		if(isUserLoggedIn && isUserSubscribed)
		{
			return;
		}
		
		var newsletterSubscriptionInfo = readCookie("newsletterSubscriptionInfo"); 
		if(newsletterSubscriptionInfo != null)
		{
			eval("newsletterSubscriptionInfo = " + newsletterSubscriptionInfo + ";");
			
			if(newsletterSubscriptionInfo.rejected == true || newsletterSubscriptionInfo.subscribed == true)
			{
				return;
			}
			else
			{
				if(!isUserLoggedIn && isUserSubscribed)
				{
					return;
				}
				else if(newsletterSubscriptionInfo.subscribed == true)
				{
					return;
				}
				else
				{
					//Effect.BlindDown(name);
					$("#form-subscribe").animate({opacity: 'toggle'}, 'slow', 'swing');
					return;			
				}
			}
		}
		else
		{
			//Effect.BlindDown(name);
			$("#form-subscribe").animate({opacity: 'toggle'}, 'slow', 'swing');
			return;
		}
	}
	
	showPopupTimeOut = setTimeout("checkAndShowPopup('" + name + "');", 2000);
}

// checks does the time interval pass, and sets the isTimeIntervalPassed true if
// it does
function ckeckTimeInterval()
{
	startOfPopUpTimePeriodReadFromCookie = readCookie("startOfPopUpTimePeriod");
	if(startOfPopUpTimePeriodReadFromCookie == null)
	{
		createCookie("startOfPopUpTimePeriod", new Date().getTime(), 0.0006);
		startOfPopUpTimePeriod = new Date().getTime();
	}
	else
	{
		startOfPopUpTimePeriod = startOfPopUpTimePeriodReadFromCookie;
	}
	
	if (startOfPopUpTimePeriod != null && startOfPopUpTimePeriod != "")
	{
		var bigDate = new Date().getTime();
		
		if(startOfPopUpTimePeriod < bigDate)
		{
			if((bigDate - startOfPopUpTimePeriod) > timeInterval)
			{
				isTimeIntervalPassed = true;
				return isTimeIntervalPassed;
			}
		}
		else
		{
//			if((startOfPopUpTimePeriod - bigDate) > timeInterval)
//			{
//				isTimeIntervalPassed = true;
//				return isTimeIntervalPassed;
//			}
		}
		
	}
	else
	{
		alert("Please specify startOfPopUpTimePeriod variable!!")
	}
}


//The function is called when user pushes "subscribe", "reject" or postpone buttons. 
function subscribeForNewsletterFromPopup(action, email)
{
	if(action == "subscribe")
	{
		var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	    if (email.search(emailRegEx) == -1) {
			alert("Va rugam introduceti o adresa de email valida!");
			document.getElementById('emailsubscribtion').focus();
			return false;
	    }	
		else if(email && trim(email) != "" && email != "e-mail")
		{
			/* new Ajax.Request(subscriptionURL, 
					{ 	method:'post',
						parameters: {action: action, email: email},
					  	onSuccess: function(transport)
					  	{
							createCookie("newsletterSubscriptionInfo", '{postpone:false,rejected:false,subscribed:true,email:"' + email + '"}', null);
					    }
					  }); */
			$.ajax({
				type: "post",
				url: location.href,
				data: "Action=subscribe&NewsletterCategories=72&FirstName=numele&LastName=prenumele&Email="+email,
				success: function(msg){
					createCookie("newsletterSubscriptionInfo", '{postpone:false,rejected:false,subscribed:true,email:"' + email + '"}', null);
				}
			});
		evenimentTracker._trackEvent('Abonare', 'Popup');
		}
		else
		{
			alert("Va rugam introduceti o adresa de email!");
			return;
		}
	}
	else if(action == "reject")
	{
		createCookie("newsletterSubscriptionInfo", '{postpone:false,rejected:true,subscribed:false,email:""}', null);
	}
	else if(action == "postpone")
	{
		createCookie("newsletterSubscriptionInfo", '{postpone:true,rejected:false,subscribed:false,email:""}', null);
		createCookie("startOfPopUpTimePeriod", new Date().getTime() + 10 * 60 * 1000, 0.0006);
		//createCookie("startOfPopUpTimePeriod", new Date().getTime() + 10 * 1000, 0.0006);
		startOfPopUpTimePeriodReadFromCookie = readCookie("startOfPopUpTimePeriod"); 
		showPopupTimeOut = setTimeout("checkAndShowPopup('form-subscribe');", 2000);
	}
	
	//Effect.BlindUp('form-subscribe');
	$("#form-subscribe").animate({opacity: 'toggle'}, 'slow', 'swing');
}


/**
 * 
 * Javascript trim, ltrim, rtrim
 * 
 */
 
function trim(str, chars) 
{
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) 
{
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) 
{
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
