/**
* Script icludes all registration/login functionality, 
* cookies usage
*/

(function () {

	var 
		window = this,
		
		/**
		* Object contains script major functionality
		*/
		RG = window.RG = {
		
			signUpFormDisabled : false,
			loginFormDisabled : false,
			forgotPwdFormDisabled : false,
			
			ForgotPwd : function() {
				if (this.forgotPwdFormDisabled) return;
				
				var emailField = document.getElementById("forgotEmField"),
					email = trim(emailField.value),
					dataToSend;
					
				$("#regPanel span").css("display","none");	// reset error messages
				
				if (email=="") {
					$("#forgotEmLabel span[name='mandatory']").css("display","inline");
					emailField.focus();
					emailField.select();
					return;
				}

				if (!checkEmail( email )) {
					$("#forgotEmLabel span[name='notvalid']").css("display","inline");
					emailField.focus();
					emailField.select();
					return;
				}
				
				dataToSend = "{".concat("\"email\":\"",email,"\"}");
				
				this.signUpFormDisabled = true;
				
				$.ajax({
					type: "POST",
					url: "WCF/Header.svc/ForgotPassword",//"WCF/Header.svc/RegisterNewUser",//"WCF/Search.svc/StartSearching",//"WCF/PreviewImage.svc/ShowPreviewImages" //"YourPage.aspx/YourFunction",
					data: dataToSend,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					cache: false,
					success: function(result) {
						if (result.d.status == 0) { // success
							$("#regForgotPwdPanel").css("display","none");
							$("#regLogInPanel").css("display","block");
							document.getElementById("forgotPwdForm").reset();
							RG.ShowMessage('Email has been sent','A password have been e-mailed to you!');
						} else {
							switch(result.d.status)
							{
							case '1': // unspecified error
								$("#forgotPwdForm span[name='unspecifiederror']").css("display","inline");	
								break;
							case '2': // such email doesn't exist
								$("#forgotEmLabel span[name='doesntexist']").css("display","inline");
								emailField.focus();
								emailField.select();
								break;
							default:
							}
						}
						
						RG.signUpFormDisabled = false;
					},
					error: function(request, status, errorThrown) {
						RG.signUpFormDisabled = false;
						document.getElementById("forgotPwdForm").reset();
						$("#forgotPwdForm span[name='unspecifiederror']").css("display","inline");
					}
				})
			},
			
			LogIn : function () {
			
				if (this.loginFormDisabled) return;
				
				var	logField = document.getElementById("logField"),
					pwdField = document.getElementById("pwdField"),
					uname = trim(logField.value),
					pwd = trim(pwdField.value),
					dataToSend;
					
				$("#regPanel span").css("display","none");
				
				if (uname=="") {
					$("#logLabel span[name='mandatory']").css("display","inline");
					logField.focus();
					logField.select();
					return;
				}
				
				if (pwd=="") {
					$("#pwdLabel span[name='mandatory']").css("display","inline");
					pwdField.focus();
					pwdField.select();
					return;
				}
				
				if (pwd.length<6) { // at least 6 letters
					$("#pwdLabel span[name='letters']").css("display","inline");
					pwdField.value=pwd;
					pwdField.focus();
					pwdField.select();
					return;
				}
				
				dataToSend = "{".concat("\"userName\":\"",uname,"\",\"password\":\"",pwd,"\"}");
				
				this.loginFormDisabled = true;
				
				$.ajax({
					type: "POST",
					url: "WCF/Header.svc/LogMeIn", //"YourPage.aspx/YourFunction",
					data: dataToSend,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					cache: false,
					success: function(result) {
						
						if (result.d.status == 0) { // success
							$("#regClose").trigger("click");
							document.getElementById('regToggle').style.display = 'none';
							document.getElementById('logOutPlace').style.display = 'block';
							document.getElementById('unamecaption').innerHTML = 'Hello ' + result.d.email.split('@')[0] + '!';
							var days = (document.getElementById("rememberme").checked)? 365:0;
							createCookie('usemail', twiddleIn("" + result.d.email),days);
							document.getElementById("logInForm").reset();
						} else {
							switch(result.d.status)
							{
							case '1': // unspecified error
								$("#logInForm span[name='unspecifiederror']").css("display","inline");	
								break;
							case '2': // account not activated
								$("#logInForm span[name='account']").css("display","inline");	
								break;	
							case '3': // Username or password incorrect
								$("#logInForm span[name='uspwdincorrect']").css("display","inline");
								break;
							default:
							}
						}
						
						RG.loginFormDisabled = false;
					},
					error: function(request, status, errorThrown) {
						RG.loginFormDisabled = false;
						document.getElementById("logInForm").reset();
						$("#logInForm span[name='unspecifiederror']").css("display","inline");	
					}
				})
			},
			
			SignUp : function () {
				
				if (this.signUpFormDisabled) return;
				
				var signupEmField = document.getElementById("signupEmField"),
					signupPwdField = document.getElementById("signupPwdField"),
					termAgreeField = document.getElementById("termAgreeField"),
					blogplatform = $("#signUpForm select").val(),
					email = trim(signupEmField.value),
					pwd = trim(signupPwdField.value),
					dataToSend;
				
				$("#regPanel span").css("display","none");
					
				if (email=="") {
					$("#signupEmLabel span[name='mandatory']").css("display","inline");
					signupEmField.focus();
					signupEmField.select();
					return;
				}
				
				if (!checkEmail( email )) {
					$("#signupEmLabel span[name='notvalid']").css("display","inline");
					signupEmField.focus();
					signupEmField.select();
					return;
				}
				
				if (pwd=="") {
					$("#signupPwdLabel span[name='mandatory']").css("display","inline");
					signupPwdField.focus();
					signupPwdField.select();
					return;
				}
				
				if (pwd.length<6) { // at least 6 letters
					$("#signupPwdLabel span[name='letters']").css("display","inline");
					signupPwdField.value=pwd;
					signupPwdField.focus();
					signupPwdField.select();
					return;
				}
				
				if (blogplatform=='0'){
					$("#blogplatformLabel span[name='mandatory']").css("display","inline");
					$("#signUpForm select").focus();
					return;
				}
				
				if (!termAgreeField.checked){
				    $("#termAgreeLabel span[name='mandatory']").css("display","inline");
				    return;
				}
				
				dataToSend = "{".concat("\"email\":\"",email,"\",\"pwd\":\"",pwd,"\",\"blogUrl\":\"",blogplatform,"\"}");
				
				this.signUpFormDisabled = true;
				
				$.ajax({
					type: "POST",
					url: "WCF/Header.svc/RegisterNewUser", //"YourPage.aspx/YourFunction",
					data: dataToSend,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					cache: false,
					success: function(result) {
					
						if (result.d.status == 0) { // success
							document.getElementById("signUpForm").reset();
							RG.ShowMessage('Success','SignUp Successfull, please check your email to activate account!');
							GoogleTrack('/registration/successcomplete.html');
						} else {
							switch(result.d.status)
							{
							case '1': // unspecified error
								$("#signUpForm span[name='unspecifiederror']").css("display","inline");	
								break;
							case '2':
							case '3': // email already exists
								$("#signupEmLabel span[name='exist']").css("display","inline");
								signupEmField.focus();
								signupEmField.select();
								break;
							default:
							}
						}
						
						RG.signUpFormDisabled = false;
					},
					error: function(request, status, errorThrown) {
						RG.signUpFormDisabled = false;
						document.getElementById("signUpForm").reset();
						$("#signUpForm span[name='unspecifiederror']").css("display","inline");
					}
				})
				
				GoogleTrack('/registration/regsubmit.html');

			},
			
			LogOut : function () {
				eraseCookie('usemail');
				document.getElementById('unamecaption').innerHTML = 'Hello Guest!';
				document.getElementById('regToggle').style.display = 'block';
				document.getElementById('logOutPlace').style.display = 'none';
			},
			
			ShowMessage : function (head, mes) {
	
				if (document.getElementById('mesWin')) {
					this.DisplayMesWindow(head, mes);
				} else {
					this.BuildMesWindow();
					setTimeout(function (){ RG.DisplayMesWindow(head,mes)},1000); // delay for images preloading 
				}
				
			},
			
			DisplayMesWindow : function (head, mes) {
			
				var left = 0;
				var top = 0;
				var mesWin = document.getElementById('mesWin');
				
				document.getElementById('mesWinHead').innerHTML = head;
				document.getElementById('mesWinBody').innerHTML = mes;
				
				document.getElementById('mesWin').style.display = "block";
				
				if (screen.availWidth && screen.availHeight)
				{
					left = ($(window).width() - mesWin.offsetWidth) / 2;
					top = ($(window).height() - mesWin.offsetHeight) / 2;    
				}
				
				mesWin.style.top = top + 'px';
				mesWin.style.left = left + 'px';
				
				document.getElementById('mesWin').style.visibility = "visible";

			},
			
			HideMesWindow : function () {
				document.getElementById('mesWin').style.visibility = "hidden";
				document.getElementById('mesWin').style.display = "none";
			},
			
			BuildMesWindow : function () {
			
				var theBody = document.getElementsByTagName('body')[0] || document.body;
				
				if (!theBody) return;
				
				var html = "<div id=\"mesWinTop\"></div>" +
							"<div id=\"mesWinCont\">" +
								"<p id=\"mesWinHead\"></p>" +
								"<p id=\"mesWinBody\"></p>" +
								"<p id=\"mesWinFoot\"><input type=\"button\" name=\"Close\" value=\"Close\" onclick=\"RG.HideMesWindow()\" /></p>" +
							"</div>" +
							"<div id=\"mesWinBot\"></div>";
							
				var container = document.createElement('div');
				
				container.id='mesWin';
				
				container.innerHTML = html;
				
				theBody.appendChild(container);
			},
			
			GetUserEmail : function() {
				var email = readCookie('usemail');
				
				if (email) email = twiddleOut(email);
				
				return email?email:'';
			},
						
			Init : function () {

				if (typeof activationSuccess!='undefined' && activationSuccess=='true'){ // for activationSuccess.aspx
					createCookie('usemail', twiddleIn(window.activatedUserEmail), 365);
				}
				
				var uname = readCookie('usemail');
				
				if (uname){
					document.getElementById('unamecaption').innerHTML = 'Hello ' + twiddleOut(uname).split('@')[0] + '!';
					document.getElementById('regToggle').style.display = 'none';
					document.getElementById('logOutPlace').style.display = 'block';
				}
				
			}
		}
		
		/**
		* Initialization code
		*/
		$(document).ready(function() {
	
			// Expand Panel
			$("#regLogIn,#regRegister").click(function(){
			
				document.getElementById("forgotPwdForm").reset();
				document.getElementById("logInForm").reset();
				document.getElementById("signUpForm").reset();
				
				document.getElementById("logo").style.zIndex = 1;
				
				$("#regPanel span").css("display","none");
				$("#regPanel").slideDown("slow");
				
				GoogleTrack('/registration/openpanel.html');
				
				return false;
			});	
			
			// Collapse Panel
			$("#regClose").click(function(){
				$("#regPanel").slideUp("slow",function(){document.getElementById("logo").style.zIndex = 21});	
				return false;
			});		
			
			// Switch buttons from "Log In | Register" to "Close Panel" on click
			$("#regToggle a").click(function () {
				$("#regToggle div").toggle();
			});
			
			// Log Out
			$("#regLogout").click(function(){
				RG.LogOut();	
				return false;
			});
			
			$("#regLostPwdLink").click(function(){
				$("#regLogInPanel").css("display","none");
				$("#regForgotPwdPanel").css("display","block");
				return false;
			});
			
			$("#regBackLink").click(function(){
				$("#regForgotPwdPanel").css("display","none");
				$("#regLogInPanel").css("display","block");
				return false;
			});
			
			
			// Set onSubmit event listeners
			$("#regPanel form").submit(function(){
			
					switch(this.name)
					{
					case 'logInForm':
					  RG.LogIn(); break;
					case 'signUpForm':
					  RG.SignUp();break;
					case 'forgotPwdForm':  
					   RG.ForgotPwd();break;
					default:
					 
					}
					
					return false;
				}
				
			);


			RG.Init();
			
		});
		
		function twiddleOut(s){
			var arr = [];
			s = s.split("-");
			for(i=0;i<s.length;i++) { 
				arr.push(String.fromCharCode(s[i]-(i+1)*5));
			}
			return arr.join('');
		}

		function twiddleIn(s){
			var arr = [];
			for(i=0;i<s.length;i++) { 
				arr.push(s.charCodeAt(i)+(i+1)*5); 
			}
			return arr.join('-');
		}
		
		
		/*
		function PreloadImages(a) {
			var pi=[];
			
			for(var i=0; i<a.length; i++) { pi[i]=new Image;pi[i].src=a[i];	}
			
		}
		*/

		
  
})();

function GoogleTrack(url) {
	try { //GOOGLE-ANALYTICS
		pageTracker._trackPageview(url);
	} catch (e) {
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = /  /g;
   while (temp.match(obj)) { temp = temp.replace(obj, " "); }
   return temp;
}

function checkEmail(inputvalue){	
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	if(pattern.test(inputvalue)){         
		return true;   
	}else{   
		return false;
	}
}
