﻿//we add this to request
var step = 0;

//how long to increase the form background
var increaseBgHeight;

//is it's not in code we have js error
var varLookupCityLinks;

//flag to send event7 to omniture when user starts fillind the form
var omnitureFlag = false;

//how much inputs for birthdate
var birthdateValidatorCounter = 3;


//capcha source var
var src = "";

function getUrlParams(url) {
    var queryString = url.split('?');
    if (queryString[1] != null)
        return queryString[1].split('&');
}

function getUrlParamsString(url) {
    var queryString = url.split('?');
    if (queryString[1] != null)
        return queryString[1];
    else {
        return "";
    }
}

function getUrlParam(url, paramName) {
    var params = getUrlParams(url);

    if (params == null)
        return null;

    for (i = 0; i < params.length; i++) {
        var param = params[i];

        if (param.indexOf(paramName + '=') == 0) {
            return param.substr(paramName.length + 1);
        }
    }

    return null;
}

function showLogin() {
    jQuery('#loginForm').animate({ opacity: 'toggle' }, 300);
}

//validate all input and select in form
function validateForm() {
    var validateFlag = true;
    jQuery("#one-page-reg-form input,#one-page-reg-form select").each(function () {
        if (validateElement(this, true)) {
            validateFlag = false;
        }

        raiseOmnitureEvent7(this);
    });
    //submit form if form is validate
    if (validateFlag) {
        submitForm();
    }
}

function raiseOmnitureEvent7(element) {
    if (!omnitureFlag && readCookie("event7Fired") == null) {
        s.events = "event7";
        s.t();
        omnitureFlag = true;
        createCookie("event7Fired", "true", 100);
    }
}



//validate element return false if on error
function validateElement(element, isValidateForm) {
    //if in Ynet iFrame - show password field
    //showPasswordField();

    if (jQuery(element).is(":visible")) {
        var elementErrorFlag = false;
        var name = jQuery(element).attr('name');
        if (jQuery(element).hasClass("select-birthdate")) {
            jQuery(".select-birthdate").each(function () {
                if (validator[jQuery(this).attr('name')]) {
                    name = jQuery(this).attr('name');
                    return false;
                }
            });
        }
        if (validator[name]) {
            for (key in validator[name]) {
                var value = jQuery(element).val();
                if (jQuery(element).is(':checkbox')) {
                    value = jQuery(element).is(':checked') ? "1" : "";
                }
                switch (validator[name][key].errorKey) {
                    case "required":
                        if (!validateRequired(value)) {
                            displayError(element, validator[name][key].message);
                            elementErrorFlag = true;
                        }
                        break;
                    case "email":
                        if (!validateEmail(value)) {
                            displayError(element, validator[name][key].message);
                            elementErrorFlag = true;
                        }
                        break;
                    case "minlength":
                        if (!validateMinLength(value, validator[name][key].value)) {
                            displayError(element, validator[name][key].message);
                            elementErrorFlag = true;
                        }
                        break;
                    case "maxlength":
                        if (!validateMaxLength(value, validator[name][key].value)) {
                            displayError(element, validator[name][key].message);
                            elementErrorFlag = true;
                        }
                        break;
                    case "wrongBirthDate":
                        if (!validateBirthDate(value, validator[name][key].value, isValidateForm)) {
                            displayError(element, validator[name][key].message);
                            elementErrorFlag = true;
                        }
                        break;
                    case "wrongCity":
                        var country = jQuery(".Region").children().find(".field").filter(":first").children().val();
                        if (!validateCity(value, validator[name][key].value) && (siteId == 4 || siteId == 15) && country == 105) {
                            displayError(element, validator[name][key].message);
                            elementErrorFlag = true;
                        }
                        break;
                    case "password":
                        if (!validatePassword(value, validator[name][key].value)) {
                            displayError(element, validator[name][key].message)
                            elementErrorFlag = true;
                        }
                        break;
                }
                if (elementErrorFlag) {
                    break;
                }
            }
            if (!elementErrorFlag) {
                clearError(element)
            }
        }
    }
    return elementErrorFlag;
}

//validate wrong password
function validatePassword(value, length) {
    var reg = /^[a-zA-Z0-9א-ת]{4,15}$/;
    if (reg.test(value) == false) {
        return false;
    }
    return true;
}

//validate city
function validateCity(value, length) {
    if (citiesArr[value]) {
        return true;
    }
    return false;

}

//check if user entered birthdate
function validateBirthDate(value, length, isValidateForm) {
    errorFlag = true;
    counter = 0;
    jQuery(".select-birthdate").each(function () {
        if (isNaN(jQuery(this).val()) == true) {
            errorFlag = false;
            counter++;
        }
    });
    if (!isValidateForm) {
        if (birthdateValidatorCounter == counter && !errorFlag) {
            return false;

        }
        return true;
    }
    return errorFlag;

}

//validate max length
function validateMaxLength(value, length) {
    if (value.length > length) {
        return false;
    }
    return true;
}

//validate min length
function validateMinLength(value, length) {
    if (value.length < length) {
        return false;
    }
    return true;
}

//display element error
function displayError(currentElement, message) {
    var name = jQuery(currentElement).attr('name');

    //if it's region error find last visible field
    if (jQuery(currentElement).parent().parent().hasClass("Region")) {
        jQuery(currentElement).parent().parent().children().each(function () {
            if (jQuery(this).is(":visible")) {
                currentElement = jQuery(this).children(".field").children().filter(':last');
            }
        });
    }

    if (jQuery(currentElement).children("select,input").length) {
        currentElement = jQuery(currentElement).children("select:first-child,input:first-child,");
    }

    if (jQuery(currentElement).parent().children("div.error").length) {
        jQuery(currentElement).parent().children("div.error").html(message);
    }
    //if T&C & has already error
    else if (jQuery(currentElement).parent().filter(':last').attr('id') == "TNCInput" &&
                jQuery(currentElement).parent().next().children("div.error").length) {
        jQuery(currentElement).parent().next().children("div.error").html(message);
    }
    else {
        var isTNC = false;

        //if field is hidden add error to previous field
        if (!jQuery(currentElement).parent().filter(':last').is(":visible")) {

            var element = jQuery(currentElement).parent().filter(':last').prev();
            jQuery(element).children(".field").append("<div class=\"error\">" + message + "</div>");
        }
        //if field is TNC
        else if (jQuery(currentElement).parent().filter(':last').attr('id') == "TNCInput") {
            jQuery(currentElement).parent().filter(':last').next().append("<div class=\"error\">" + message + "</div>");
            isTNC = true;
        }
        else {
            jQuery(currentElement).parent().filter(':last').append("<div class=\"error\">" + message + "</div>");
        }
        if (!isTNC) {
            jQuery(currentElement).parent().children("div.error").hide().slideDown("fast", function () { jQuery("#one-page-reg-form-bg").height(increaseBgHeight + jQuery("#one-page-reg-form").height()); });
        }
        else {
            jQuery(currentElement).parent().filter(':last').next().children("div.error").hide().slideDown("fast", function () { jQuery("#one-page-reg-form-bg").height(increaseBgHeight + jQuery("#one-page-reg-form").height()); });
        }
    }

}

//clear ement error
function clearError(currentElement) {
    if (jQuery(currentElement).parent().filter(':last').attr('id') == "TNCInput") {
        jQuery(currentElement).parent().filter(':last').next().children("div.error").remove();
    }
    else {
        jQuery(currentElement).parent().children("div.error").remove();
    }
    jQuery("#one-page-reg-form-bg").height(increaseBgHeight + jQuery("#one-page-reg-form").height());
}

function clearAllErrors() {
    jQuery("#one-page-reg-form div.error").remove();
    jQuery("#one-page-reg-form-bg").height(increaseBgHeight + jQuery("#one-page-reg-form").height());
}

//validate required
function validateRequired(value) {
    if (value == "" || value.length == 0 || value == " ") {
        return false;
    }
    return true;
}

function validateEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (reg.test(email) == false) {
        return false;
    }
    return true;
}

function showPasswordField() {
    //if in Ynet iFrames
    if (typeof ShowLabelInsideInput === 'undefined') {
        //do nothing
    } else {
        if (ShowLabelInsideInput == true && jQuery('#password_text').css('display') == 'block') {
            jQuery('#password_text').css('display', 'none');
            jQuery('#_ctl0__ctl2__ctl0__ctl0_idPassword_AttributeTextControl').css('display', 'block');
        }
    }
}
function documentReady() {
    //if in Ynet iFrames
    if (typeof ShowLabelInsideInput === 'undefined') {
        //do nothing
    } else {
        if (ShowLabelInsideInput == true) {
            jQuery('#logo_link').css('display', 'block');
            jQuery('#logo_link').click(function () { window.location.href = "http://www.jdate.co.il"; });

            var pwdInput = '#_ctl0__ctl2__ctl0__ctl0_idPassword_AttributeTextControl';
            var pwdText = jQuery.trim(jQuery(pwdInput).parent().prev().text());
            jQuery(pwdInput).after('<input type="text" value="' + pwdText + '" name="password_text" id="password_text" style="display:block;"/>');
            jQuery(pwdInput).css('display', 'none');
            jQuery('#password_text').focus(function () {
                showPasswordField();
                jQuery(pwdInput).focus();
            });

            //if input value is default - set value to empty string
            jQuery('.mandatory').focus(function () {
                var defaultVals = jQuery(this).val();
                if (defaultVals == jQuery.trim(jQuery(this).parent().prev().text())) {
                    jQuery(this).val("");
                }
            });
        }
    }

    readCookiesData();
    setIncreaseBgHeight();

    jQuery('#email_login,#password_login').keypress(function (e) {
        if (e.keyCode == 13) {
            login();
        }
    });

    jQuery('#one-page-reg-form .mandatory,#one-page-reg-form .optional').keypress(function (e) {
        if (e.keyCode == 13) {
            hideCityList();
            validateForm();
        }
    });

    //jQuery("#one-page-reg-form input,#one-page-reg-form select").change(function() { validateElement(this); });

    jQuery("#one-page-reg-form input,#one-page-reg-form select").focusout(function () { isValidateForm = false; validateElement(this, false); });
    jQuery("#one-page-reg-form input:checkbox").click(function () { isValidateForm = false; validateElement(this, false); });
    jQuery("#one-page-reg-form input,#one-page-reg-form select").focusin(function () { raiseOmnitureEvent7(this); });

    jQuery(".submit-btn").click(function () { hideCityList(); validateForm(); });

    //jQuery(".autocomplete").focusout(function() { hideCityList(); });

    //hide city list when focusin on countries list
    jQuery(".Region").children("div").filter(":first").children(".field").children("select").focusin(function () { hideCityList(); });

    jQuery(".autocomplete").autocompleteArray(
		    citiesArr,
		{
		    delay: 10,
		    minChars: 1,
		    matchSubset: 1,
		    onItemSelect: selectItem,
		    onFindValue: findValue,
		    autoFill: true,
		    maxItemsToShow: 6,
		    regionIdInput: "regionid",
		    selectWidth: "143px",
		    selectHeight: "130px"
		}
	);

    jQuery("#one-page-reg-form-bg").height(increaseBgHeight + jQuery("#one-page-reg-form").height());

    jQuery("#ajax-loader").height(jQuery("#one-page-reg-form").height());


    /***** refresh capcha ******/
    jQuery(".refresh-capcha").click(function () {
        jQuery.ajax({
            type: "POST",
            url: "/Applications/API/Captcha.asmx/RefreshCaptcha",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            timeout: 10000,
            success: function (msg) {
                var tempSrc;
                if (src == "") {
                    src = jQuery(".capcha-image").attr("src");
                }
                tempSrc = src;
                var rand_no = Math.random();
                rand_no = rand_no * 999999;

                tempSrc += "&" + rand_no;
                jQuery(".capcha-image").attr("src", tempSrc);
            }
        });
    });
}

//set increaseBgHeight var
function setIncreaseBgHeight() {
    //if in Ynet iFrames
    if (typeof ShowLabelInsideInput === 'undefined') {
        switch (siteId) {
            case 4:
                increaseBgHeight = 43;
                break;
            case 105:
            case 107:
                increaseBgHeight = 40;
                break;
            default:
                increaseBgHeight = 66;
                break;
        }
    } else {
        increaseBgHeight = 23;
    }
}

jQuery(document).ready(function () {
    setTimeout("documentReady()", 400);

});

//if cities list is visible hide it and choose current city
function hideCityList() {
    if (jQuery(".ac_results").is(":visible")) {
        jQuery(".regionid").val(citiesArr[jQuery(".autocomplete").val()]);

        jQuery(".ac_results").hide();
    }
}

//submit form
function submitForm() {
    var data = buildRequest();
    var param = "checkstep=1";
    displayLoader();
    jQuery("#general-error").hide();
    jQuery.ajax({
        type: "POST",
        url: window.location.pathname + "?" + param + "&" + getUrlParamsString(location.href),
        data: data,
        success: function (response) {
            var obj = jQuery.parseJSON(response);
            if (obj.status == "errors") {
                jQuery("#ajax-loader").hide();
                handelErrors(obj);
            }
            else if (obj.status == "complete") {
                //if in Ynet iframe
                if (typeof RegCompleteDivID === 'undefined') {
                    if (obj.OpenRegCompleteInNewWindow == "True") {
                        window.open(obj.url, "spark_reg");
                    }
                    else {
                        window.location = obj.url;
                    }
                } else {
                    //hide the main registration div and show after registration div
                    jQuery('#one-page-reg-content').html(jQuery('#' + RegCompleteDivID).html());
                    //hide main div background image on facebook iframe
                    if (RegCompleteDivID == 'fbiframe_after_reg_cont') {
                        jQuery('#one-page-reg-content').css('background','#fff');
                    }
                }
            }
            else {
                jQuery("#ajax-loader").hide();
            }
        },
        error: function (response, status, e) {
            jQuery("#ajax-loader").hide();
            jQuery("#general-error").show();
        }
    });
}

function displayLoader() {
    jQuery("#ajax-loader").height(jQuery("#one-page-reg-form").height());
    jQuery("#ajax-loader").show();
}

//handel ajax response errors
function handelErrors(obj) {
    clearAllErrors();
    for (var key in obj.errors) {
        var element = jQuery("#one-page-reg-form").find("#" + obj.errors[key].id);
        if (jQuery(element).attr("class") == "TermsAndConditions") {
            displayError(jQuery("#TNCText"), obj.errors[key].msg);
        }
        else {
            displayError(jQuery("#one-page-reg-form").find("#" + obj.errors[key].id + " .field"), obj.errors[key].msg);
        }
    }
}

//build data to send to server
function buildRequest() {
    curentStepId = "step_" + step;
    var data = {};
    jQuery('#one-page-reg-form .mandatory,#one-page-reg-form .optional').each(function () {
        if (jQuery(this).is(':checkbox')) {
            if (jQuery(this).is(':checked')) {
                data[jQuery(this).attr('name')] = jQuery(this).val();
            }
        }
        else if (jQuery('#one-page-reg-form.aboutme .steptip').html() != null && jQuery('#one-page-reg-form.aboutme .steptip').html().indexOf(jQuery('#one-page-reg-form textarea').val()) != -1) {
            data[jQuery(this).attr('name')] = "";
        }
        else if (jQuery(this).children().is(':checkbox')) {
            jQuery(this).children().each(function () {
                if (jQuery(this).is(':checkbox')) {
                    if (jQuery(this).is(':checked')) {
                        data[jQuery(this).attr('name')] = jQuery(this).val();
                    }
                }
            });
        }
        else if (jQuery(this).val() != null && jQuery(this).val() != "") {

            var val = jQuery(this).val();
            if (jQuery(this).not('multiple') && jQuery.isArray(val)) {
                val = val[0];
            }
            data[jQuery(this).attr('name')] = val;
        }
        else {
            data[jQuery(this).attr('name')] = ""
        }
    });

    data["stepID"] = step;

    return data;
}

//login
function login() {
    var amEmail = document.getElementsByName("email_login")[0].value;
    var amPass = document.getElementsByName("password_login")[0].value;

    var chkRememberMe = document.getElementById("remember");
    if (chkRememberMe.checked) {
        createCookie("username2", document.getElementById("email_login").value, 100);
        createCookie("remember", "yes", 100);
    }
    else {
        eraseCookie("username2");
        eraseCookie("remember");
    }
    amAddToUrl();
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

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 readCookiesData() {
    var rem = readCookie("remember");
    if (rem == "yes") {
        //check if this elements exists
        if (document.getElementById("remember")) {
            document.getElementById("remember").checked = true;
        }
        if (document.getElementById("email_login")) {
            document.getElementById("email_login").value = readCookie("username2");
        }
    }
}

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 amAddToUrl() {
    var amEmail = document.getElementsByName("email_login")[0].value;
    var amPass = document.getElementsByName("password_login")[0].value;

    var newUrl = window.location.href.substring(0, window.location.href.lastIndexOf('/') + 1) + "applications/logon/logon.aspx?emailaddress=";
    newUrl = newUrl + amEmail + "&password=" + amPass;
    window.location = newUrl;
}


/****** autocomplete *******/
function findValue(li) {
    if (li == null) return false;

    // if coming from an AJAX call, let's use the CityId as the value
    if (!!li.extra) var sValue = li.extra[0];

    // otherwise, let's just display the value in the text box
    else var sValue = li.selectValue;

}

function selectItem(li) {
    findValue(li);
}

function formatItem(row) {
    return row[0] + " (id: " + row[1] + ")";
}

function lookupLocal() {
    var oSuggest = jQuery("#CityLocal")[0].autocompleter;
    oSuggest.findValue();

    return false;
}


//callback from change country/region
function autocompleteCities() {
    documentReady();
}
//before callback from change country/region
function BeforeRegionCallback() {
    displayLoader();
}

var citiesArr = {};

/****** Basic functions *****/
function launchWindow(strURL, strName, intWidth, intHeight, strProperties) {
    // just create a window with the given properties and don't return the handle
    // to the window. (for inline javascript: calls in hrefs)
    var w = createWindow(strURL, strName, intWidth, intHeight, strProperties);
    // make sure created window has focus. In case a popup profile was in background
    // or minimized, bring it to front.
    w.focus();
}

function createWindow(strURL, strName, intWidth, intHeight, strProperties) {
    var mywin;
    var intVersion;
    var dummyDate = new Date();

    var strPoundURL;
    var intPoundPos;

    intVersion = navigator.appVersion.substring(0, 1);
    if (strURL != "") {
        intPoundPos = strURL.indexOf("#");
        if (intPoundPos != -1) {
            strPoundURL = strURL.substring(intPoundPos);
            strURL = strURL.substring(0, intPoundPos);
        }

        if (strURL.indexOf("?") != -1) {
            strURL = strURL + "&rnd="
        } else {
            strURL = strURL + "?rnd="
        }

        strURL = strURL + dummyDate.getTime();

        if (strPoundURL != null) {
            strURL = strURL + strPoundURL;
        }

        strURL = Replace(strURL, "@", "%40");
    }

    if (strProperties == "") {
        strProperties = "scrollbars=yes,resizable=yes,menubar=no,location=no,directories=no,toolbar=no";
    }

    strProperties = "status=yes,height=" + intHeight + ",width=" + intWidth + "," + strProperties;

    // replace all non-alphacharacters with X
    if (strName.replace)
        strName = strName.replace(/\W/g, "X");

    // lower case the string
    strName = strName.toLowerCase();

    //try to open a pop-up window
    mywin = window.open(strURL, strName, strProperties);


    // POP-BLOCKER OVERRIDE SECTION
    // try to load the link in the current window, unless this is a view profile request from IM.
    // If it is a view profile request from IM, try to show the profile in window.opener or else give up
    if (mywin == null)//i.e., pop-up blocker
    {
        mywin = self; // set to self so we don't return null reference

        // We are changing the template here to show nav and header 
        // since we can't open a pop-up window
        strURL = strURL.replace("LayoutTemplateID=2", "LayoutTemplateID=1");
        strURL = strURL.replace("LayoutTemplateID=4", "LayoutTemplateID=8");
        strURL = strURL.replace("LayoutTemplateID=11", "LayoutTemplateID=1"); //Open profile in same window if popup blockers are enabled.

        // If the current window is an IM window, we will allow the popup blocker to notify the user that
        // the window couldn't be opened, otherwise, we load the link in the current window.
        if (window.location.href.indexOf("/upInstantCommunicator.aspx") == -1) {
            window.document.location = strURL;
        }
        else {
            // if this is an IM window request for a profile, check if window.opener is still open
            var IsWindowOpenerClosed = false;
            try {	//Attempt to access a property on the window.opener object
                //Using 'window.opener.closed' is not consistent on all browser implementations.
                var temp = window.opener.location.href;
            }
            catch (e) {
                IsWindowOpenerClosed = true;
            }
            if (!IsWindowOpenerClosed) {

                //do not persist the layout template (bug: 15532) (or else all subsequent requests will have nav and header around them)
                strURL = strURL.replace("PersistLayoutTemplate=1", "")
                window.opener.location = strURL;
            }
            else {
                //do nothing. let the pop-up blocker work TODO: resource in other languages
                //alert("to view member's profile requires pop-up blocker to be disabled.");
            }

        }
    }

    // return handle to caller
    return mywin;
}

function Replace(str, substring, newstring) {
    if (str.length <= 0)
        return "";

    temp = "" + str;

    while (temp.indexOf(substring) > -1) {
        pos = temp.indexOf(substring);
        temp = "" + (temp.substring(0, pos) + newstring + temp.substring((pos + substring.length), temp.length));
    }
    return temp;
}

function ReplaceSingle(str, substring, newstring) {
    if (str.length <= 0)
        return "";

    temp = "" + str;

    if (temp.indexOf(substring) > -1) {
        pos = temp.indexOf(substring);
        temp = "" + (temp.substring(0, pos) + newstring + temp.substring((pos + substring.length), temp.length));
    }
    return temp;
}
