﻿
var loggingin = false;
var _loadFunctions = new Array();
//var pageTracker = null;

function AddOnWindowLoaded(func) {
	if (typeof (func) == 'function')
		_loadFunctions.push(func);
}

function ShowSignIn() {
	signInDiv.style.display = 'block';
	document.getElementById('txtSignInEmail').focus();
}

function ForceHideSignIn() {
	signInDiv.style.display = '';
}

function HideSignIn(event) {
	if (window.event) {
		ev = window.event.srcElement;
	}
	else {
		ev = event.target;
	}
	var itSelf = false;

	parent_div = ev;
	while (parent_div.parentNode && !itSelf) {
		if (parent_div.className == 'dSignin') {
			itSelf = true;
		}
		parent_div = parent_div.parentNode;
	}

	if (!itSelf) {
		if (signInDiv.style.display == 'block') {
			ForceHideSignIn();
		}
	}
}

function getCodeByEvent(event) {
	var code;
	if (!e) var e = event;
	if (!e) var e = window.event;

	if (e.keyCode) {
		code = e.keyCode;
	}
	else if (e.which) {
		code = e.which;
	}
	return code;
}

function PageTrack(key) {
	if (pageTracker != null) {
		pageTracker._trackPageview(key);
	}
}

function PageEvent(category, key) {
	if (pageTracker != null) {
		pageTracker._trackEvent(category, key);
	}
}
function ProcessTagCloudTrack() {
	var divs = document.getElementsByTagName('DIV');
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == "cloudArea")
			FindTagsCloud(divs[i]);
	}

}

function FindTagsCloud(obj) {
	var childs = obj.childNodes;
	if (childs.length == 0) {
		return;
	}
	var child;
	for (var i = 0; i < childs.length; i++) {
		child = childs[i];
		if (child.tagName == 'A') {
			child.onmouseup = TagCloudTrack;
		}
		else {
			FindTagsCloud(child);
		}
	}
}


function TagCloudTrack(event) {
	var id = this.id;
	id = id.replace(/.+_hl(.+)/gi, '$1');
	PageEvent('tag', id);
	PageTrack('tag_' + id);
}

function LoginToPortal() {  
	var oPgrs = document.getElementById('divSigninProgress');
	if (oPgrs != null && oPgrs.style.display != '') {
		return;
	}
	PageTrack('singin');
	SignInPortal.SignIn('txtSignInEmail', 'txtSignPassword');
}

function LoginToPortalForPremium() {
    
    if ($('#divSigninPremiumProgress').is(':visible'))        
        return;    
    
    PageTrack('singin_forPremium');    
    SignInPortal.SignInForPremium('txtSignInPremiumEmail', 'txtSignInPremiumPassword');
}

var signInDiv = null;

window.onload = function() {
    signInDiv = document.getElementById(iSignInIdent);
    signInDiv.onclick = function(event) {
        
        var ev = null;
        if (window.event)
            ev = window.event.srcElement;        
        else
            ev = event.target;

        return (ev.tagName == 'A' || ev.tagName == 'a');
        
    };
    document.onclick = HideSignIn;
    for (var i = 0; i < _loadFunctions.length; i++) {
        _loadFunctions[i]();
    }
    ProcessTagCloudTrack();
    //pageTracker = _gat._getTracker("UA-12442749-5");
}

//_____________________//



var Poster = new function() {
    this.OnComplete = null;

    this.Unsubsribe = function(oEM, onComplete) {
        if (typeof (onComplete) == 'function') {
            this.OnComplete = onComplete;
        }
        $.ajax({
            type: "POST",
            url: "post.ashx",
            data: "type=unsubscribe&email=" + oEM,
            success: function(response) {
                if (onComplete != null) {
                    onComplete(eval("(" + response + ")"));
                }
            }
        });
    };

    this.PostRegister = function(oFN, oLN, oEM, oPN, onComplete) {
        if (typeof (onComplete) == 'function') {
            this.OnComplete = onComplete;
        }

        $.ajax({
            type: "POST",
            url: "post.ashx",
            data: "type=register&firstName=" + oFN + "&lastName=" + oLN + "&email=" + oEM + "&portalName=" + oPN,
            success: function(response) {
                if (onComplete != null) {
                    onComplete(eval("(" + response + ")"));
                }
            }
        });
    };

    this.PostSignin = function(oEM, oPV, onComplete) {
        if (typeof (onComplete) == 'function') {
            this.OnComplete = onComplete;
        }

        $.ajax({
            type: "POST",
            url: "post.ashx",
            data: "type=signin&email=" + oEM + "&password=" + oPV,
            success: function(response) {
                if (onComplete != null) {
                    onComplete(eval("(" + response + ")"));
                }
            }

        });
    };

    this.PostSigninForPremium = function(email, pwd, onComplete)
    {
        if (typeof (onComplete) == 'function') {
            this.OnComplete = onComplete;
        }

        $.ajax({
            type: "POST",
            url: "post.ashx",
            data: "type=signinpremium&email=" + email + "&password=" + pwd,
            success: function(response) {
                if (onComplete != null) {
                    onComplete(eval("(" + response + ")"));
                }
            }
        });
    }

    this.CheckDomainName = function(portalName, onComplete) {
        if (typeof (onComplete) == 'function') {
            this.OnComplete = onComplete;
        }

        $.ajax({
            type: "POST",
            url: "post.ashx",
            data: "type=checkdomain&portalName=" + portalName,
            success: function(response) {
                if (onComplete != null) {
                    onComplete(eval("(" + response + ")"));
                }
            }

        });
    };



};

var TeamLabPortal =
{
	LoadScript: function(scriptPathFromSource) {
		document.write('<script type="text/javascript" src="js/' + scriptPathFromSource + '"><\/script>');
	},
	Trim: function(str) {
		return str.replace(/^\s+|\s+$/g, '');
	},
	//EmailRegex: /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
	EmailRegex: /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
};

var SignInPortal =
{   
    erroMsg: null,
    oPrgs: null,
    InitMsg: function() {        
        if (this.erroMsg == null) {
            this.erroMsg = document.getElementById('divSigninError');
        }
        if (this.oPrgs == null) {
            this.oPrgs = document.getElementById('divSigninProgress');
        }
    },

    InitPremiumMsg: function() {        
        if (this.erroMsg == null) {
            this.erroMsg = document.getElementById('divSigninPremiumError');
        }
        if (this.oPrgs == null) {
            this.oPrgs = document.getElementById('divSigninPremiumProgress');
        }
    },

    SignIn: function(iEM, iPWD) {
        this.InitMsg();
        var oEM = document.getElementById(iEM);
        var oPWD = document.getElementById(iPWD);
        this.ClearErrors();
        var result = this.Verify(oEM, oPWD);
        if (result != null) {
            this.PrintErrors(result);
            return;
        }
        this.oPrgs.style.display = 'block';
        Poster.PostSignin(TeamLabPortal.Trim(oEM.value), TeamLabPortal.Trim(oPWD.value), this.OnComplete)
    },

    SignInForPremium: function(iEM, iPWD) {
        this.InitPremiumMsg();
        var oEM = document.getElementById(iEM);
        var oPWD = document.getElementById(iPWD);
        this.ClearErrors();
        var result = this.Verify(oEM, oPWD);
        if (result != null) {
            this.PrintErrors(result);
            return;
        }
        this.oPrgs.style.display = 'block';
        Poster.PostSigninForPremium(TeamLabPortal.Trim(oEM.value), TeamLabPortal.Trim(oPWD.value), this.OnComplete)
    },

    OnComplete: function(response) {
        if (response.status != '') {
            SignInPortal.oPrgs.style.display = '';
            var errors = new Array();
            errors.push({ error: response.message, message: errorMessage.GetMessageByType(response.message) });
            SignInPortal.PrintErrors(errors);
            return;
        }
        else {
            if (response.rs1 == 'morethatone') {
                PortalChooseController.DisplayPortalChooseController(response.rs2);
            } else {
                SignInPortal.oPrgs.innerHTML = errorMessage.GetMessageByType("forwardingInfo");               
                window.open(response.rs2, '_self');
               
            }
        }
    },

    Verify: function(oEM, oPWD) {
        var results = new Array();
        if (TeamLabPortal.Trim(oEM.value) == '') {
            results.push({ error: 'emailEmpty', message: errorMessage.GetMessageByType('emailEmpty') });
        }
        else if (TeamLabPortal.Trim(oEM.value).match(TeamLabPortal.EmailRegex) == null) {
            results.push({ error: 'emailIncorrect', message: errorMessage.GetMessageByType('emailIncorrect') });
        }
        if (TeamLabPortal.Trim(oPWD.value) == '') {
            results.push({ error: 'passwordEmpty', message: errorMessage.GetMessageByType('passwordEmpty') });
        }

        if (results.length == 0) {
            results = null;
        }

        return results;
    },
    ClearErrors: function() {
        this.erroMsg.style.display = '';
    },

    PrintErrors: function(errors) {
        this.ClearErrors();
        if (errors == null)
            return;

        var result = '';
        for (var i = 0; i < errors.length; i++) {
            if (errors[i].error == 'emailEmpty' || errors[i].error == 'emailIncorrect') {
                result = errors[i].message;
                break;
            }
        }
        if (result == '') {
            result = errorMessage.GetMessageByType('emailOrPasswordIncorrect');
        }

        this.erroMsg.style.display = 'block';
        this.erroMsg.innerHTML = result;
    }
};

var Subscriptions =
{
	erroEM: null,
	oEM: null,
	postfix: '_errorArea',
	oPrgs: null,
	oUnsubscribSbmt: null,

	InitMsgs: function(oEM) {
		if (this.erroEM == null) {
			this.erroEM = document.getElementById(oEM.id + this.postfix);
		}

		if (this.oPrgs == null) {
			this.oPrgs = document.getElementById('divUnsubscribProgress');
		}

		if (this.oUnsubscribSbmt == null) {
			this.oUnsubscribSbmt = document.getElementById('sbmtUnsubscrib');
		}
	},

	Unsubscribe: function (idEM) {
		this.oEM = document.getElementById(idEM);

		this.InitMsgs(this.oEM);

		if (this.oUnsubscribSbmt.style.display != '') {
			return undefined;
		}

		this.ClearErrors();
		var result = this.Verify(this.oEM);
		if (result != null) {
			this.PrintErrors(result);
			return undefined;
		}

		Poster.Unsubsribe(TeamLabPortal.Trim(this.oEM.value), this.OnComplete);

		this.oUnsubscribSbmt.style.display = 'none';
		this.oPrgs.style.display = 'block';
	},

	OnComplete: function(response) {
		Subscriptions.oPrgs.style.display = '';
		Subscriptions.oUnsubscribSbmt.style.display = '';
		if (response.status == 'error') {
			var errors = [];
			errors.push({ error: response.message, message: errorMessage.GetMessageByType(response.message) });
			Subscriptions.PrintErrors(errors);
			return undefined;
		}
		else if (response.status == 'success') {
			Subscriptions.showDisplayDialog();
		}
	},

	closeDisplayBlock: function () {
		if ($('#successMessageBox').is(':visible')) {
			$.unblockUI();
		}
	},

	showDisplayDialog: function () {
		$.blockUI({
			message: $('#successMessageBox'),
			css: {
				border: 'none',
				backgroundColor: 'Transparent',
				border: 'none',
				padding: '0',
				cursor: 'default',
				top: '50%',
				left: '50%',
				marginLeft: '-200px',
				marginTop: '-25px'
			},
			overlayCSS: {
				backgroundColor: 'black',
				cursor: 'default',
				opacity: '0.2'
			},
			focusInput: false,
			fadeIn: 0,
			fadeOut: 0
		});
		setTimeout(Subscriptions.closeDisplayBlock, 3000);
	},

	Verify: function(oEM) {
		var results = new Array();

		if (TeamLabPortal.Trim(oEM.value) == '') {
			results.push({ error: 'emailEmpty', message: errorMessage.GetMessageByType('emailEmpty') });
		}
		else if (TeamLabPortal.Trim(oEM.value).match(TeamLabPortal.EmailRegex) == null) {
			results.push({ error: 'emailIncorrect', message: errorMessage.GetMessageByType('emailIncorrect') });
		}
        
		if (results.length == 0) {
			results = null;
		}

		return results;
	},

	ClearErrors: function() {
		this.erroEM.style.display = '';

		this.oEM.className = this.oEM.className.replace(/\s*error/gi, '');
	},

	PrintErrors: function(errors) {
		this.ClearErrors();

		if (errors == null)
			return undefined;

		for (var i = 0; i < errors.length; i++) {
			switch (errors[i].error) {
				case 'firstNameEmpty':
					this.erroFN.innerHTML = errors[i].message;
					this.erroFN.style.display = 'block';
					this.oFN.className += ' error';
					break;
				case 'lastNameEmpty':
					this.erroLN.innerHTML = errors[i].message;
					this.erroLN.style.display = 'block';
					this.oLN.className += ' error';
					break;
				case 'emailUnregistered':
				case 'emailUnsubscribed':
				case 'emailEmpty':
				case 'emailIncorrect':
					this.erroEM.innerHTML = errors[i].message;
					this.erroEM.style.display = 'block';
					this.oEM.className += ' error';
					break;
				case 'portalNameEmpty':
				case 'portalNameExisit':
				case 'portalNameIncorrect':
				case 'tooShortError':
					this.erroPN.innerHTML = errors[i].message;
					this.erroPN.style.display = 'block';
					this.oPN.className += ' error';
					break;
			}
		}
	}
}

var RegisterPortal =
{
    erroFN: null,
    erroLN: null,
    erroEM: null,
    erroPN: null,
    oFN: null,
    oLN: null,
    oEM: null,
    oPN: null,
    postfix: '_errorArea',
    oPrgs: null,
    oSignUpSbmt: null,

    InitMsgs: function(oFN, oLN, oEM, oPN) {

        if (this.erroFN == null) {
            this.erroFN = document.getElementById(oFN.id + this.postfix);
        }

        if (this.erroLN == null) {
            this.erroLN = document.getElementById(oLN.id + this.postfix);
        }

        if (this.erroEM == null) {
            this.erroEM = document.getElementById(oEM.id + this.postfix);
        }

        if (this.erroPN == null) {
            this.erroPN = document.getElementById(oPN.id + this.postfix);
        }

        if (this.oPrgs == null) {
            this.oPrgs = document.getElementById('divSignUpProgress');
        }

        if (this.oSignUpSbmt == null) {
            this.oSignUpSbmt = document.getElementById('sbmtSignUp');
        }
    },


    CreatePortal: function(idFN, idLN, idEM, isPN, trackTag) {
        this.oFN = document.getElementById(idFN);
        this.oLN = document.getElementById(idLN);
        this.oEM = document.getElementById(idEM);
        this.oPN = document.getElementById(isPN);
        this.InitMsgs(this.oFN, this.oLN, this.oEM, this.oPN);

        if (this.oSignUpSbmt.style.display != '') {
            return;
        }

        PageTrack(trackTag);
        this.ClearErrors();
        var result = this.Verify(this.oFN, this.oLN, this.oEM, this.oPN);
        if (result != null) {
            this.PrintErrors(result);
            return;
        }

        Poster.CheckDomainName(TeamLabPortal.Trim(this.oPN.value), this.OnComplete);

        this.oSignUpSbmt.style.display = 'none';
        this.oPrgs.style.display = 'block';

    },

    OnComplete: function(response) {
        RegisterPortal.oPrgs.style.display = '';
        RegisterPortal.oSignUpSbmt.style.display = '';
        if (response.status != '') {
            var errors = new Array();
            errors.push({ error: response.message, message: errorMessage.GetMessageByType(response.message) });
            RegisterPortal.PrintErrors(errors);
            return;
        }
        else {
            RecaptchaController.DisplayRecaptcha();
        }
    },

    Verify: function(oFN, oLN, oEM, oPN) {
        var results = new Array();
        if ((TeamLabPortal.Trim(oFN.value) == '') || (TeamLabPortal.Trim(oFN.value) == 'First Name') || (TeamLabPortal.Trim(oFN.value) == "Vorname") ||
             (TeamLabPortal.Trim(oFN.value) == "Nombre") || (TeamLabPortal.Trim(oFN.value) == "Prénom") || (TeamLabPortal.Trim(oFN.value) == "Имя") ||
             (TeamLabPortal.Trim(oFN.value) == "Vārds") || (TeamLabPortal.Trim(oFN.value) == "Nome")) {
            results.push({ error: 'firstNameEmpty', message: errorMessage.GetMessageByType('firstNameEmpty') });
        }
        if ((TeamLabPortal.Trim(oLN.value) == '') || (TeamLabPortal.Trim(oLN.value) == 'Last Name') || (TeamLabPortal.Trim(oLN.value) == "Nachname") ||
            (TeamLabPortal.Trim(oLN.value) == 'Apellidos') || (TeamLabPortal.Trim(oLN.value) == 'Nom') || (TeamLabPortal.Trim(oLN.value) == 'Фамилия') ||
            (TeamLabPortal.Trim(oLN.value) == 'Uzvārds') || (TeamLabPortal.Trim(oLN.value) == 'Cognome')) {
            results.push({ error: 'lastNameEmpty', message: errorMessage.GetMessageByType('lastNameEmpty') });
        }
        if (TeamLabPortal.Trim(oEM.value) == '') {
            results.push({ error: 'emailEmpty', message: errorMessage.GetMessageByType('emailEmpty') });
        }
        else if (TeamLabPortal.Trim(oEM.value).match(TeamLabPortal.EmailRegex) == null) {
            results.push({ error: 'emailIncorrect', message: errorMessage.GetMessageByType('emailIncorrect') });
        }
        
        var oPNValue = TeamLabPortal.Trim(oPN.value);
        if ((oPNValue == '') || (TeamLabPortal.Trim(oPN.value) == 'Portal-Adresse')) {
            results.push({ error: 'portalNameEmpty', message: errorMessage.GetMessageByType('portalNameEmpty') });
        }
        else if (oPNValue.length < 6)
        {
            results.push({ error: 'tooShortError', message: errorMessage.GetMessageByType('tooShortError') });
        }
        else if (!oPNValue.match(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/gi))
        {
            results.push({ error: 'portalNameIncorrect', message: errorMessage.GetMessageByType('portalNameIncorrect') });
        }

        if (results.length == 0) {
            results = null;
        }

        return results;
    },

    ClearErrors: function() {
        this.erroFN.style.display = '';
        this.erroLN.style.display = '';
        this.erroEM.style.display = '';
        this.erroPN.style.display = '';

        this.oFN.className = this.oFN.className.replace(/\s*error/gi, '');
        this.oLN.className = this.oLN.className.replace(/\s*error/gi, '');
        this.oEM.className = this.oEM.className.replace(/\s*error/gi, '');
        this.oPN.className = this.oPN.className.replace(/\s*error/gi, '');


    },

    PrintErrors: function(errors) {
        this.ClearErrors();

        if (errors == null)
            return;

        for (var i = 0; i < errors.length; i++) {
            switch (errors[i].error) {
                case 'firstNameEmpty':
                    this.erroFN.innerHTML = errors[i].message;
                    this.erroFN.style.display = 'block';
                    this.oFN.className += ' error';
                    break;
                case 'lastNameEmpty':
                    this.erroLN.innerHTML = errors[i].message;
                    this.erroLN.style.display = 'block';
                    this.oLN.className += ' error';
                    break;
                case 'emailEmpty':
                case 'emailIncorrect':
                    this.erroEM.innerHTML = errors[i].message;
                    this.erroEM.style.display = 'block';
                    this.oEM.className += ' error';
                    break;
                case 'portalNameEmpty':
                case 'portalNameExisit':
                case 'portalNameIncorrect':
                case 'tooShortError':
                    this.erroPN.innerHTML = errors[i].message;
                    this.erroPN.style.display = 'block';
                    this.oPN.className += ' error';
                    break;
                //default:                              
                //alert(errors[i].error);                              
            }
        }
    }
};


function expandElement(element) {
	var hEl = $(element);
	var el = $('#' + element.id.replace(/_headdiv$/i, '') + '_sectiondiv');
	var hideFlag = 'hide';
	if (!el.hasClass('expand')) {
		hideFlag = 'show';
	}

	if (hEl.hasClass('exp')) {
		hEl.removeClass('exp');
	}
	else {
		hEl.addClass('exp');
	}

	el.animate({ height: hideFlag, opacity: hideFlag }, 'fast');

	if (el.hasClass('expand')) {
		el.removeClass('expand');
	} else {
		el.addClass('expand');
	}
}

//Adds keydown events to the sign in inputs
AddOnWindowLoaded(function() {
	$('#txtSignInEmail').keydown(
		function(event) {
			return SignInByEnterHit(event);
		}
	);

	$('#txtSignPassword').keydown(
		function(event) {
			return SignInByEnterHit(event);
		}
	);
});


function SignInByEnterHit(event) {
	//Enter key was pressed
	if (event.keyCode == 13) {
		LoginToPortal();
		return false;
	}
	return true;
};


var PremiumController = new function() {
    this.GoPremium = function(isTop) {
       
        if(isTop)
            PageTrack('buynow_btn_top');
        else 
            PageTrack('buynow_btn_bottom');
      
        var url = $('#shoppingUrl').val();
        if (url != "") {
            window.open(url, "_self");
            return;
        }

        this.ShowSignInDialog();
    }
    this.ShowSignInDialog = function() {
        displayModalPanel('signInForShoppingContainer');
    }

    this.CloseSignInDialog = function() {
        if ($('#signInForShoppingContainer').is(':visible')) {
            $('#signInForShoppingContainer').hide();
            $.unblockUI();
        }
    };
}

//--------Send Feedback------//


//function SendMassage() {
//        var name = $("#UserName").val();
//        var eMail = $("#EMail").val();
//        var massage = $("#Massage").val();
//        
//}



