var errorStatus = null;
var currentErrorDisplayed = "";
var requiredFields = new Array();
var activationCodeCount = 0;
// Regular expressions used to validate certain elements
var alphaNumExp = /^[0-9a-zA-Z._-]+$/;
var alphaExp = /^[a-zA-Z]/;

var errorMessages = {
    empty_user : "Please use 6-12 characters and start with a letter. You may use letters and numbers only. No spaces allowed.",
    empty_pass : "Please use 6-12 characters, capitalization matters.",
    empty_phone : "Please enter valid mobile number.", // Registration & login
    empty_descriptioin : "Please enter a description.", // For Contact Us

    invalid_user : "Please use 6-12 characters and start with a letter. You may use letters and numbers only. No spaces allowed.",
    invalid_pass : "Please use 6-12 characters, capitalization matters.",
    invalid_email : "Please enter a valid E-mail address.",
    invalid_phone : "Please enter valid mobile number.",

    user_exists : "User already exists. Please choose another.",
    phone_exists : "This number has been recorded. Either you signed up already or you entered a wrong number.",

    choose_a_country : "Please choose a country from the list",
    passwords_do_not_match : "Passwords do not match.",
    agree_to_toc : "You must agree to the Terms and Conditions.",
    incorrect_activation : "The activation code you entered does not seem correct. Please try again.",

    whatIsUsername : "<ul style='text-align:left;'><li>User name should be 6-12 English characters or numbers.</li><li>It must start with a letter.</li><li>It may not contain any spaces</li></ul>",
    whatIsPassword : "<ul style='text-align:left;'><li>Password should be 6-12 English characters or numbers.</li><li>Capitalization matters</li></ul>",
    whatIsPhone : "To ensure your privacy, we need to verify your cell phone number by sending you a unique activation code which you will be asked to enter in the next step.",
    login_invalid_pass : "Please enter a password.",
    login_invalid_username : "Please enter a username.",
    wrong_user_password : "Invalid username or password.",
    user_suspended : "The user is suspended.",
    password_sent : "An SMS was sent to your phone with your username and password.",
    error_while_trying_login : "There was an error while trying to login.",
    number_dont_match_user : "Number doesn't match user name."
};

function displayError(element, message, extraLeft, extraTop) {
    // Get the top and left position of the field
    var infoDiv = $("#" + element).attr("info") + "InfoDiv";
    var errorDiv = element + "ErrorDiv";
    var checkMarkImg = element + "Success";
    $("#" + infoDiv).hide();
    $("#" + element + "ErrorText").html(message);

    if (element == "CountriesList")
        $("#PhoneNumberSuccess").css("visibility", "hidden");
    $("#" + checkMarkImg).css("visibility", "hidden");
    $("#" + errorDiv).show();

}
function displayNotice(element, message, extraLeft, extraTop) {
    // Get the top and left position of the field
    var NoticeDiv = element + "NoticeDiv";
    $("#" + element + "NoticeText").html(message);
    $("#" + NoticeDiv).show();
}


function errorOut(message, element) {
    if (element != '') {
        var errorDiv = $("#" + element).parents("div.inputDiv:first");
        errorDiv.css("border-top", "1px solid #005368");
        errorDiv.css("border-left", "1px solid #005368");
        errorDiv.css("border-right", "1px solid #005368");
        errorDiv.css("background", "#186D86")
        displayError(element, message);
    }

}

function getVal(element) {
    return $("#" + element).val();
}

// Functions to validate username
/**
 * @param element
 * @return True if all validation passed before the calling the CM
 */
function checkUsername(element) {
    var username = getVal(element);

    if (username == '') {
        errorOut(errorMessages.empty_user, element);
        setElementValidation(element, false);
        return false;
    } else if (username.length < 6 || username.length > 12 || !username.match(alphaNumExp) || !username.match(alphaExp)) {
        errorOut(errorMessages.invalid_user, element);
        setElementValidation(element, false);
        return false;
    } else {
        CM.sendRequest('isUserNameExist$AP', username);
        return true;
    }
}

function checkLoginUsername(element) {
    var username = getVal(element);
    if (username == '') {
        errorOut(errorMessages.login_invalid_username, element);
        return false;
    }
    return true;
}


function doUserNameExist(response, apiName) {
    var element = "Username";
    if (response) {
        errorOut(errorMessages.user_exists, element);
        setElementValidation(element, false);
    } else {
        setElementValidation(element, true);
    }
}

// This function verifies that the user has agreed to the TOC

function checkTOC(element) {
    var agreed = $("#" + element).is(":checked");
    if (agreed == false) {
        errorOut(errorMessages.agree_to_toc, element);
    } else {
        return true;
    }
}

// Validate the description in the contact us page
function checkDescription(element) {
    var desc = getVal(element);
    if (desc == '') {
        errorOut(errorMessages.empty_descriptioin, element);
        return false;
    } else {
        return true;
    }
}

function checkUsernameQuestion(element) {
    displayError(element, errorMessages.whatIsUsername, 141);
    return true;
}
function checkPasswordQuestion(element) {
    displayError(element, errorMessages.whatIsPassword, 141);
    return true;
}
function checkPhoneQuestion(element) {
    displayError(element, errorMessages.whatIsPhone, 141);
    return true;
}

function checkLoginUsernameQuestion(element) {
    displayError(element, errorMessages.whatIsUsername, 140);
    return true;
}
function checkLoginPasswordQuestion(element) {
    displayError(element, errorMessages.whatIsPassword, 140);
    return true;
}


// This function validates the password

function checkPassword(element) {
    var password = getVal(element);
    if (password == '') {
        errorOut(errorMessages.empty_pass, element);
        return false;
    } else if (password.length < 5 || password.length > 12) {
        errorOut(errorMessages.invalid_pass, element);
        return false;
    } else {
        return true;
    }
}


function checkLoginPassword(element) {
    var password = getVal(element);
    if (password == '') {
        errorOut(errorMessages.login_invalid_pass, element);
        return false;
    }
    return true;
}


function checkRePassword(element) {
    var password = getVal("Password");
    var confirmPassword = getVal(element);

    if (!confirmPassword || password != confirmPassword) {
        errorOut(errorMessages.passwords_do_not_match, element);
        return false;
    } else {
        return true;
    }
}

/**
 * @param element
 * @return True if all validation passed before the calling the CM
 */
function checkPhoneNumber(element) {
    if (!checkCountriesList("CountriesList")) return false;

    var phone = getNumber(getVal(element));
    $("#" + element).val(phone);
    var errorMessage = validatePhoneNumber(phone);
    if (errorMessage != null) {
        errorOut(errorMessage, element);
        setElementValidation(element, false);
        return false;
    }

    CM.sendRequest('isNumberRegistered$AP', getNumber());
    return true;
}

function validatePhoneNumber(phoneNumber) {
    var trimmedVal = jQuery.trim(phoneNumber);
    if (trimmedVal == '') {
        return errorMessages.empty_phone;
    } else if (trimmedVal.match(/^\d{6,14}$/) == null) {
        return errorMessages.invalid_phone;
    }
    return null;
}

function doNumberRegistered(response) {
    var element = "PhoneNumber";
    if (response) {
        errorOut(errorMessages.phone_exists, element);
        setElementValidation(element, false);
    } else {
        setElementValidation(element, true);
    }
}

function fixedError(element) {
    var errorDivBG = $("#" + element).parents("div.inputDiv:first");
    errorDivBG.css("border", "0");
    errorDivBG.css("background", "");


    var infoDiv = $("#" + element).attr("info") + "InfoDiv";
    var errorDiv = element + "ErrorDiv";
    var checkMarkImg = element + "Success";
    $("#" + infoDiv).hide();
    if (element == "PhoneNumber")
        $("#CountriesListErrorDiv").hide();
    $("#" + errorDiv).hide();
    $("#" + checkMarkImg).css("visibility", "visible");
}

function checkCountriesList(element) {
    var country = getVal(element)
    if (country == '') {
        errorOut(errorMessages.choose_a_country, element);
        return false;
    } else {
        return true;
    }
}

function checkEmail(element) {
    var email = getVal(element);
    if (!isEmail(email)) {
        errorOut(errorMessages.invalid_email, element);

        return false;
    } else {
        return true;
    }
}

function isEmail(emailStr) {
    var checkTLD = 1;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailStr.match(emailPat);

    if (emailStr.indexOf("%") >= 0)
        return false;

    if (matchArray == null) {
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            return false;
        }
    }
    for (i = 0; i < domain.length; i++) {
        if (domain.charCodeAt(i) > 127) {
            return false;
        }
    }
    if (user.match(userPat) == null) {
        return false;
    }

    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return false;
            }
        }
        return true;
    }

    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;
    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            return false;
        }
    }

    if (checkTLD && domArr[domArr.length - 1].length != 2 &&
        domArr[domArr.length - 1].search(knownDomsPat) == -1) {
        return false;
    }

    if (len < 2) {
        return false;
    }
    return true;
}

function setElementValidation(fieldId, isValid) {
    if (isValid) {
        fixedError(fieldId);
        errorStatus = null;
        ;
    } else {
        var element = document.getElementById(fieldId);
        errorStatus = fieldId;
    }
}

function checkFunc(id) {
    var func = "check" + id;
    if (!errorStatus || errorStatus == id) {
        var resp = window[func](id);
        // Check for phone number and username are done async. The return method handles the errors.
        // Although if the script had detected an error before doing the sync call, the method will return false. We will display the error msg then.
        if (id == "PhoneNumber" || id == "Username" && resp) return;

        setElementValidation(id, resp);
    }
}

function validateAll() {
    if (errorStatus) return false;
    $.each(requiredFields, function(key, value) {
        checkFunc(value);
    });

    return errorStatus == null;


}

function getNumber(number) {
    countryCode = getVal("CountriesList");
    var phone = "";
    if (!number) {

        phone = getVal("PhoneNumber");

    } else {
        phone = number;
    }
    phone = phone.replace(/[()+\-\. ]/g, '');

    if (phone.length >= 11) {
        var pattern = '^' + countryCode;
        phone = phone.replace(new RegExp(pattern), '');
    }

    phone = phone.replace(/^0/, '');

    if (countryCode == "1") {
        phone = phone.replace(/^1/, "");
    }
    if (number) {
        return phone;
    } else if (phone) {
        return countryCode + phone;
    } else {
        return "";
    }

}

function doCheckActivationCode(response, apiName) {
    var element = "activationCode";

    if (response != true) {
        errorOut(errorMessages.incorrect_activation, element);
        errorStatus = element;
        return false;
    } else {
        var username = getVal("Username");
        var password = getVal("Password");
        var firstName = getVal("FirstName");
        var lastName = getVal("LastName");
        var email = getVal("Email");
        var phoneNumber = getNumber();
        var activationCode = getVal("activationCode");
        if (firstName == "First Name")
            firstName = "";
        if (lastName == "Last Name")
            lastName = "";
        if (!application)
            application = 2;

        document.getElementById("submitStepTwo").style.display = "none";
        document.getElementById("submitStepTwoDisabled").style.display = "inline";

        CM.sendRequest('triplayRegistration$AP', username, phoneNumber, password, activationCode, firstName, lastName, email, application);
    }
}


function showComposer(application) {
    var dialogHeight = 358;
    var dialogWidth = 272;

    var dialogParams = "width=" + dialogWidth + ",height=" + dialogHeight;
    var screenXOffset = window.screenX;
    var screenYOffset = window.screenY;
    var screenWidth = window.outerWidth;
    var screenHeight = window.outerHeight;

    if ((screenXOffset != null) && ((screenYOffset != null) && (screenWidth != null))) {
        var dialogLeft = (screenWidth / 2) - (272 / 2);
        if (dialogLeft + dialogWidth > screen.width - 10) {
            dialogLeft = screen.width - 10 - dialogWidth;
        }
        dialogParams += ",left=" + dialogLeft + ",top=" + ((screenHeight / 4) - (307 / 2));
    }
    dialogParams += ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no";
    var win = window.open("_dialog", "TriplayComposer", dialogParams);
    win.location = "/WebGW/pages/triplay/tConnectComposer.html?applicationId=" + application;;
    win.focus();
}

function doRegister(status) {
    var succeeded = "";
    if (status == "OK") {
        succeeded = "3";
        sendReport(succeeded);
        setTimeout(function() {
            if (application == 7 ) {
                var data = '{"isLoadedFromCookie": true, "lang": "en", "username": "' + getVal("Username") + '", "password": "' + hex_md5(getVal("Password")) + '", "rememberMe": true}';
                createCookie("TriplayUserFFMode", data, 30);
                showComposer(application);
                window.location = "/thank_you.php?msg=FIREFOX_REG";
            } else if(application == 101){
                var data = '{"isLoadedFromCookie": true, "lang": "en", "username": "' + getVal("Username") + '", "password": "' + hex_md5(getVal("Password")) + '", "rememberMe": true}';
                createCookie("TriplayUserFFMode", data, 30);
                showComposer(application);
                window.location = "/thank_you.php?msg=FIREFOX_REG&affiliate=1";

            } else if (application == 6) {
                window.location = "/thank_you.php?msg=TSTYLE_REG";
            } else {
                var data = "username=" + getVal("Username") + "&password=" + hex_md5(getVal("Password"));
                createCookie("REMEMBER_COOKIE", data, 30);
                window.location = "/WebGW/albums/triplay/login";
            }
        }, 1000);
    } else {
        succeeded = "4";
        sendReport(succeeded);
    }

}

function sendReport(succeeded) {
    var username = getVal("Username");
    //"Password: "+password+"\n" +
    //"Confirmed Password: "+rePassword+"\n" +
    var country = $("#CountriesList option:selected").text();
    var password = getVal("Password");
    var rePassword = getVal("RePassword");
    var firstName = getVal("FirstName");
    var lastName = getVal("LastName");
    var email = getVal("Email");
    var phone = getNumber();
    var errorMessage = $("#" + errorStatus + "ErrorText").text();
    var agreed = $("#TOC").is(":checked");
    if (!application)
        application = 2;

    var reportBody = username + ',' + password + ',' + rePassword + ',' + firstName + ',' + lastName + ',' + email + ',' + phone + ',' + errorStatus + ',' + errorMessage + ',' + agreed + ',' + succeeded + ',' + application + ',' + country;
    $.post("registration.php", { body: reportBody }, function(data) {
        return;
    });
    return reportBody;
}

function sendActivationCode() {
    if (activationCodeCount < 3) {
        var phone = getNumber();
        $("#submitStepOne").css("cursor", "default");
        document.getElementById("submitStepOne").disabled = true;
        $("#submitStepOne").attr("src", "images/BUTTON_SEND_ACTIVE_OFF_DISABLED.gif");
        $("#activationCodeDiv").show("slow");
        CM.sendRequest('sendRegistrationCode$AP', phone);
        setTimeout(function() {
            $('html,#activationCode').animate({ scrollTop: 800}, 1500);
            $("#activationCode").focus();
        }, 1000);

        activationCodeCount++;

        if (activationCodeCount >= 3) {
            $("#resedActivationDiv").hide();

        }
    }
    return false;
}


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 = ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function doLogin() {
    validateAll();
    if (!errorStatus) {
        var signInForm = $('signInForm');
        if (!signInForm) return;
        var loginUsername = getVal('LoginUsername');
        var loginPassword = getVal('LoginPassword');
    } else {
        return false;
    }
}

function sendPassword() {
    var phonenumberVal = getVal('msisdn');
    var errorMessage = validatePhoneNumber(phonenumberVal);
    if (errorMessage != null) {
        displayError('msisdn', errorMessage);
        return false;
    }
    return true;
}

function initLoadPage() {
    var token = getURLParam('loginResp').toUpperCase();
    if (!token) {
        token = getURLParam('token').toUpperCase();
    }
    switch (token) {
        case 'ILLEGAL_PASS':
            displayError("LoginPassword", errorMessages.wrong_user_password);
            break;
        case 'USER_SUSPENDED':
            displayError("LoginPassword", errorMessages.user_suspended);
            break;
        case 'SMS_SENT':
            document.getElementById("passwordSent").style.display = 'block';
            break;
        case 'WRONG_NUMBER_ENTERED':
            displayforgotPassword();
            displayError("msisdn", errorMessages.number_dont_match_user);
            break;
        case 'GENERAL_ERROR':
            displayError("LoginPassword", errorMessages.error_while_trying_login);
            break;
        case 'FORGOT_PASSWORD':
            displayforgotPassword();
            document.getElementById("msisdn").focus();
    }
}

function displayforgotPassword() {
    document.getElementById("forgotPasswordDiv").style.display = "";
}

function getURLParam(strParamName) {
    var strReturn = '';
    var strHref = window.location.href;
    if (strHref.indexOf('?') > -1) {
        var strQueryString = strHref.substr(strHref.indexOf('?')).toLowerCase();
        var aQueryString = strQueryString.split('&');
        for (var i = 0, j = aQueryString.length; i < j; i++) {
            if (aQueryString[i].indexOf(strParamName.toLowerCase() + '=') > -1) {
                var aParam = aQueryString[i].split('=');
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

function gebi(elem) {
    return document.getElementById(elem);
}


