$(document).ready(function() {	
		
		$('#password_submit').click(function(e){
			//passwordReminder();
			validateLogin('lost');
	   	});
		$('#forgotPassword').click(function(e){
			passwordReminder();
	   	});
		$('#showSignIn').click(function(e){
			passwordReminder();
			updateTips('',	'#loginStatus');
	   	});
		
		$('#theLoginButton').click(function(e){
			if($.cookie("vPitchDomain") == null){
				$('#domain').val('');
				$('#username').val('');
				$('#password').val('');
			} else{
				$('#domain').val($.cookie("vPitchDomain"));
				$('#username').val($.cookie("vPitchEmail"));
			}
			if($.cookie("vPitchDomain") != null) {
				$('#rememberMe').attr('checked', true);
			}
		});
		$("#domain, #username, #password").keyup(function(e) {
			if(e.keyCode == 13) {
				submitForm();
			}
		});

        $("#domainZendesk, #usernameZendesk, #passwordZendesk").keyup(function(e) {
            if(e.keyCode == 13) {
                submitFormZendesk();
            }
        });
        
        $(".loginButton").click(function(e) {
            e.preventDefault();
            $("fieldset#signin_menu").toggle();
            $(".loginButton").toggleClass("toggle-color");
        });
		
		$("#signin_submit").click(function(e) {
			submitForm();
		});

        $("#signin_submit_zendesk").click(function(e) {
            submitFormZendesk();
        });
        
		//password reminder
		function passwordReminder(){
			$('#passwordField').toggle();
			$('#agreeToField').toggle();
			$('#rememberField').toggle();
			$('#forgotPassword').toggle();
			$('#showSignIn').toggle();
			
			$('#signin_submit').toggle();
			$('#password_submit').toggle();
			

		}//end password reminder
		
		function submitForm() {
			if($('#agreeTo').attr('checked')==true){
					if($('#rememberMe').attr('checked')==true){
						$.cookie("vPitchDomain", $('#domain').val(), { expires: 14 });
						$.cookie("vPitchEmail", $('#username').val(), { expires: 14 });
					} else {
						$.cookie("vPitchDomain", null);
						$.cookie("vPitchEmail", null);
					}
					validateLogin();
				}
				else{
					updateTips("Please agree to the Terms of Service.",	'#loginStatus');	
					return false;
				}
		}

		function submitFormZendesk() {
            validateLoginZendesk();
        }
        
		function updateTips(t,s){
			if ( s ){
				$(s).html(t);
			}else{		
				$('#formInstructions').html(t);
			}		
		}	

		function validateLoginZendesk(){
            var bValid = true;
            //$('.validationError').removeClass('validationError');

            //validate full name and mainemail
            bValid = bValid && checkRegexp($('#usernameZendesk'),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Please provide valid email address.", '#loginStatusZendesk');
            if ( bValid ){
                $.get('/app/admin/bin/php/tasks/verifyZendesklogin.php?client='+$('#domainZendesk').val()+'&email='+$('#usernameZendesk').val()+'&password='+$('#passwordZendesk').val(),
                    function(res){
                        var resp = eval('('+ res +')');
                        if ( resp.status == 'success' ){
                            var url = resp.zendesk_login_url;
                            url += 'name='+ resp.name;
                            url += '&email='+ resp.email;
                            url += '&external_id='+ resp.id;
                            url += '&organization='+ resp.organization;
                            url += '&timestamp='+ resp.timestamp;
                            url += '&hash='+ resp.hash;
                            window.location = url;
                        }else{
                            updateTips(resp.msg, '#loginStatusZendesk');
                        }
                    }
                );
            }
        }
        
		function validateLogin(lost){
			var bValid = true;
			//$('.validationError').removeClass('validationError');
			
			//validate full name and mainemail
			bValid = bValid && checkRegexp($('#username'),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Please provide valid email address.", '#loginStatus');
			if(lost){
				bValid = false;	
				$.get('/app/admin/bin/php/tasks/verifylogin.php?client='+$('#domain').val()+'&email='+$('#username').val()+'&password='+$('#password').val()+'&lostPassword=yes',
					function(res){
                        var res = eval('('+ res +')');
						updateTips(res.msg,	'#loginStatus');
					});
			}
			if ( bValid ){
				$.get('/app/admin/bin/php/tasks/verifylogin.php?client='+$('#domain').val()+'&email='+$('#username').val()+'&password='+$('#password').val(),
					function(res){
                        var res = eval('('+ res +')');
						if ( res.status == 'success' ){
							window.location='/app/admin/';
						}else{
							updateTips(res.msg,	'#loginStatus');					
						}
					}
				);
			}
		}
		
		function checkRegexp(o,regexp,n,s) {
			if ( !( regexp.test( o.val() ) ) ) {
				if ( n && s ){
					o.addClass('validationError');
					updateTips(n,s);
				}
				return false;
			} else {
				return true;
			}
		}
		
		//Cookies
		jQuery.cookie = function(name, value, options) {
			if (typeof value != 'undefined') { // name and value given, set cookie
				options = options || {};
				if (value === null) {
					value = '';
					options.expires = -1;
				}
				var expires = '';
				if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
					var date;
					if (typeof options.expires == 'number') {
						date = new Date();
						date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
					} else {
						date = options.expires;
					}
					expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
				}
				// CAUTION: Needed to parenthesize options.path and options.domain
				// in the following expressions, otherwise they evaluate to undefined
				// in the packed version for some reason...
				var path = options.path ? '; path=' + (options.path) : '';
				
				var domain = options.domain ? '; domain=' + (options.domain) : '';
				
				var secure = options.secure ? '; secure' : '';
				
				document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
				
			} else { // only name given, get cookie
				var cookieValue = null;
				if (document.cookie && document.cookie != '') {
					var cookies = document.cookie.split(';');
					for (var i = 0; i < cookies.length; i++) {
						var cookie = jQuery.trim(cookies[i]);
						// Does this cookie string begin with the name we want?
						if (cookie.substring(0, name.length + 1) == (name + '=')) {
							cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
							break;
						}
					}
				}
				return cookieValue;
			}
		};
		
		//$('#signin_submit').click(){
		//	alert("hi");
		//}
		//$(document).mouseup(function(e) {
        //if($(e.target).parent("a.loginButton").parent().html()== null) {
           // $(".loginButton").removeClass("menu-open");
           // $("fieldset#signin_menu").hide();
        //}
   // });   
	   
	   

});
