﻿/// <reference name="MicrosoftAjax.js" />
/// <reference path="../../Scripts/UsersWebSrv.asmx" />
/// <reference path="../jquery/jquery-1.3.2.js" />
/// <reference path="scriptsConsts.js" />

var consts = new poweradeConsts();

//#region checkLength
function checkLength(o, n, min, max) {
    if (o.val().length >= min && o.val().length <= max) {
        return true;
    }
    else {
        o.addClass('ui-state-error');
        updateTips($("#validateTips"), "Długość pola '" + n + "' musi być większa od " + min + " i mniejsza od " + max + ".");
        return false;
    }
}
//#endregion

//#region checkRegexp
function checkRegexp(o, regexp, n) {
    if (regexp.test(o.val())) {
        return true;
    }
    else {
        o.addClass('ui-state-error');
        updateTips($("#validateTips"), n);
        return false;
    }
}
//#endregion

//#region prepareRegistrationDialog
var __registerDiv, __birthSelector = "#txtDateOfBirth";
$(function () { __registerDiv = $("#divRegistration").clone(); });
function prepareRegistrationDialog() {
    $log("prepareRegistrationDialog");
    var nick = $("#textNick");
    var birth = $("#txtDateOfBirth");
    var TOSAccept = $("#ckbTOSAccepted");
    var allFields = $([]).add(nick).add(birth).add(TOSAccept);
    prepareDialog(nick, birth, TOSAccept, allFields);
}
//#endregion

//#region prepareDialog
function prepareDialog(nick, birth, TOSAccept, allFields) {
    $("#divRegistration").dialog({
        position: 'center',
        bgiframe: true,
        autoOpen: false,
        width: 721,
        modal: true,
        top: 0,
        zIndex: 1000,
        open: function (event, id) {
            $(this).parent().appendTo("form");
            placeMediumAvatar('profiledetailsPopup', 'profilePicPopup');
            if ($("#profiledetailsPopup shape").length != 0) {
                $('#aprofilePicPopup').next().next().hide();
            }
        },
        buttons: {
            'Zarejestruj konto': function () { registerUser(nick, birth, TOSAccept, allFields); },
            'Anuluj': function () { $(this).dialog('close'); }
        },
        close: function () {
            //allFields.val('').removeClass('ui-state-error');
            $(__birthSelector).datepicker("hide", 0);
            var dp = $("#ui-datepicker-div").hide();
            var dd = $("#divRegistration");
            dd.remove().parent().remove();
            dd.dialog("destroy");
            $("form").append(__registerDiv.clone());
        }
    });
}

//#endregion

//#region registerUser
function registerUser(nick, birth, TOSAccept, allFields) {
    allFields.removeClass('ui-state-error');

    if (validateData(nick, birth, TOSAccept)) {
        K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.IsNickExists(
            nick.val(),
            function (exists, userContext, methodName) {
                if (exists == true) {
                    updateTips($("#validateTips"), "Podany nick jest zajęty. Spróbuj wpisać inny.");
                }
                else {
                    addUser(nick, birth);
                }
            },
        //#region function error
            function (error, userContext, methodName) {
                if (consts.debug)
                    alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "', w metodzie js '" + userContext.methodName + "': " +
                        "\n\nerror._exceptionType: " + error._exceptionType +
                        ",\n\n error._message: " + error._message +
                        ",\n\n error._stackTrace: " + error._stackTrace +
                        ",\n\n error._statusCode: " + error._statusCode +
                        ",\n\n error._timedOut: " + error._timedOut);
            },
        //#endregion
            {'methodName': "registerUser" }
        );
    }
}
//#endregion

//#region validateData
function validateData(nick, birth, TOUAccepted) {
    var bValid = checkLength(nick, "nick", 3, 15);

    bValid = bValid && checkRegexp(nick, /^[a-z]([0-9a-z_])+$/i,
        "Nick może zawierać litery, cyfry, podkreślenie i musi zaczynać się od litery. Nie może zawierać polskich liter.");

    //if (birth.val().length > 0) {
    bValid = bValid && checkLength(birth, "data urodzenia", 8, 10);
    bValid = bValid && checkRegexp(birth, /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/, "Wpisz datę w formacie RRRR-MM-DD");
    bValid = bValid && Is18YearsOld(birth, "Przepraszamy, nie możesz się zarejestrować. Serwis Powerade Bieganie jest przeznaczony dla osób powyżej 18. roku życia. Zapraszamy do zapoznania się z Regulaminem.");
    //}

    if (!TOUAccepted.attr("checked")) {
        TOUAccepted.addClass('ui-state-error');
        updateTips($("#validateTips"), "Akceptacja regulaminu jest wymagana");
        bValid = false;
    }
    return bValid;
}
//#endregion

function Is18YearsOld(o, n) {
    try {
        var dateParts = o.val().split('-');
        var now = new Date();

        if (now.getFullYear() - dateParts[0] > 18) return true;
        else if (now.getFullYear() - dateParts[0] == 18) {
            if (now.getMonth() - dateParts[1] > 0) return true;
            else if (now.getMonth() + 1 - dateParts[1] == 0)
                if (now.getDate() - dateParts[2] <= 0) return true;
        }

        o.addClass('ui-state-error');
        updateTips($("#validateTips"), n);
        return false;
    }
    catch (err) { return false; }
}

//#region addUser
function addUser(nick, birth) {
    //console.log('scriptsMain : addUser');

    FB.getLoginStatus(function (response) {
        if (response && response.authResponse) {
            K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.GetUser(
				response.authResponse.userID,
				function (result, userContext, methodName) {
				    if (result != null) {
				        $redirect(consts.poweradePages.newsPage, "GetUser, addUser");
				    }
				    else {
				        var user = new K2.Powerade.Common.Models.Running.UserModel();
				        var userData = new K2.Powerade.Common.Models.Running.UserDataModel();

				        user.UserId = userData.UserId = response.authResponse.userID;

				        var dateOfBirth = birth.val();

				        if (dateOfBirth != null && dateOfBirth != undefined && dateOfBirth.length > 0) {
				            var dates = dateOfBirth.split("-", 3);
				            var d = new Date();
				            d.setUTCFullYear(dates[0], dates[1] - 1, dates[2]);
				            d.setUTCHours(0, 0, 0, 0);
				            userData.DateOfBirth = d;
				        }

				        var isMale = $("#selectSex").val();
				        if (isMale != null && isMale != undefined && isMale.length > 0) {
				            userData.IsMale = (isMale == "mężczyzna");
				        }

				        user.Nick = nick.val();

				        K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.AddUser(
							user, userData,
							function (result, userContext, methodName) {
							    if (result > 0) {
							        $log("AddUser, GetUser, addUser, result: " + result);

							        addFriends(result, getRedirectUrl());
							    }
							    else {
							        updateTips($("#validateTips"), "Podany nick jest zajęty. Spróbuj wpisać inny.");
							    }
							},
				        //#region function error
							function (error, userContext, methodName) {
							    if (consts.debug)
							        alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "'" +
											", w metodzie js '" + userContext.methodName + "': " +
										"\n\nerror._exceptionType: " + error._exceptionType +
										",\n\n error._message: " + error._message +
										",\n\n error._stackTrace: " + error._stackTrace +
										",\n\n error._statusCode: " + error._statusCode +
										",\n\n error._timedOut: " + error._timedOut);
							},
				        //#endregion
							{'methodName': 'addUser' }
						);
				    }
				},
            //#region function error
				function (error, userContext, methodName) {
				    if (consts.debug)
				        alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "'" +
								", w metodzie js '" + userContext.methodName + "': " +
							"\n\nerror._exceptionType: " + error._exceptionType +
							",\n\n error._message: " + error._message +
							",\n\n error._stackTrace: " + error._stackTrace +
							",\n\n error._statusCode: " + error._statusCode +
							",\n\n error._timedOut: " + error._timedOut);
				},
            //#endregion
				{'methodName': 'addUser' }
			);
        } else {
            $("#divRegistration").dialog('close');
        }
    });



    /*
    FB.ensureInit(function() {
    FB.Connect.get_status().waitUntilReady(function(status) {
    if (status != FB.ConnectState.connected) {
    $("#divRegistration").dialog('close');
    }
    else {
    K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.GetUser(
    FB.Connect.get_loggedInUser(),
    function(result, userContext, methodName) {
    if (result != null) {
    $redirect(consts.poweradePages.newsPage, "GetUser, addUser");
    }
    else {
    var user = new K2.Powerade.Common.Models.Running.UserModel();
    var userData = new K2.Powerade.Common.Models.Running.UserDataModel();

    user.UserId = userData.UserId = FB.Connect.get_loggedInUser();

    var dateOfBirth = birth.val();

    if (dateOfBirth != null && dateOfBirth != undefined && dateOfBirth.length > 0) {
    var dates = dateOfBirth.split("-", 3);
    var d = new Date();
    d.setUTCFullYear(dates[0], dates[1] - 1, dates[2]);
    d.setUTCHours(0, 0, 0, 0);
    userData.DateOfBirth = d;
    }

    var isMale = $("#selectSex").val();
    if (isMale != null && isMale != undefined && isMale.length > 0) {
    userData.IsMale = (isMale == "mężczyzna");
    }

    user.Nick = nick.val();

    K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.AddUser(
    user, userData,
    function(result, userContext, methodName) {
    if (result > 0) {
    $log("AddUser, GetUser, addUser, result: " + result);
                                        
    addFriends(result, getRedirectUrl());
    }
    else {
    updateTips($("#validateTips"), "Podany nick jest zajęty. Spróbuj wpisać inny.");
    }
    },
    //#region function error
    function(error, userContext, methodName) {
    if (consts.debug)
    alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "'" +
    ", w metodzie js '" + userContext.methodName + "': " +
    "\n\nerror._exceptionType: " + error._exceptionType +
    ",\n\n error._message: " + error._message +
    ",\n\n error._stackTrace: " + error._stackTrace +
    ",\n\n error._statusCode: " + error._statusCode +
    ",\n\n error._timedOut: " + error._timedOut);
    },
    //#endregion
    {'methodName': 'addUser' }
    );
    }
    },
    //#region function error
    function(error, userContext, methodName) {
    if (consts.debug)
    alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "'" +
    ", w metodzie js '" + userContext.methodName + "': " +
    "\n\nerror._exceptionType: " + error._exceptionType +
    ",\n\n error._message: " + error._message +
    ",\n\n error._stackTrace: " + error._stackTrace +
    ",\n\n error._statusCode: " + error._statusCode +
    ",\n\n error._timedOut: " + error._timedOut);
    },
    //#endregion
    {'methodName': 'addUser' }
    );
    }
    });
    });
    */
}
//#endregion

//#region prepareRegistration
function prepareRegistration() {
    //console.log('scriptsMain : prepareRegistration');

    FB.getLoginStatus(function (result) {
        if (result && result.authResponse) {

            var userId = result.authResponse.userID;
           
            K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.GetUser(
                    userId,
                    function (user, userContext, methodName) {
                     
                        if (user != null) {
                            logOnUser(user.UserId, getRedirectUrl());
                        }
                        else {                            
                            FB.api({
                                    method: 'fql.query'
                                    , query: 'SELECT name, username, sex, birthday_date, pic_big_with_logo FROM user WHERE uid = ' + userId
                                }
                                , function(result) { 
                                    if (result.error) $('FBapiMe: Wystąpił błąd krytyczny pobierania danych');
                                    else {
                                        var result = result[0];
                                        $("#selectSex").val(result['sex']);
                                        var birth = $(__birthSelector);
                                        if (result['birthday_date']) {
                                            var birthDate = result['birthday_date'].split("/", 3);
                                            birth.val(birthDate[2] + "-" + birthDate[0] + "-" + birthDate[1]);
                                        }
                                        $.datepicker.setDefaults($.datepicker.regional['pl']);
                                        birth.datepicker({
                                            defaultDate: "1950-01-01",
                                            changeMonth: true,
                                            changeYear: true,
                                            yearRange: '1950:2010',
                                            beforeShow: function () { $('#ui-datepicker-div').maxZIndex(); },
                                            onSelect: function (dateText, inst) { }
                                        });
                                        var userName = result['username'];
                                        var nick = $("#textNick");
                                        nick.val(userName == null ? result['name'] : userName);
                                        var profilePic = $("img#profilePic");
                                        if (result['pic_big_with_logo']) {
                                            profilePic.attr("src", result['pic_big_with_logo'].replace(/&amp;/gi, "&"));
                                            profilePic.attr("alt", nick.val());
                                            profilePic.attr("title", nick.val());
                                        }
                                        prepareRegistrationDialog();
                                        $("#divRegistration").dialog('open');
                                        $("#ui-datepicker-div").removeClass("ui-helper-clearfix");
                                        $("#divRegistration").siblings().filter('.ui-dialog-titlebar,.ui-dialog-buttonpane').addClass("fix");
                                        $('.ui-dialog .ui-state-default, .ui-dialog .ui-state-hover').css({
                                            font: "12px tahoma",
                                            border: "1px solid #CCCCCC"
                                        });
                                        $('.ui-dialog .ui-dialog-buttonpane').css({
                                            backgroundPosition: "0 100%",
                                            height: "37px"
                                        });
                                    }
                                }
                            );
                        }
                    },
            //#region function error
                    function (error, userContext, methodName) {
                        if (consts.debug)
                            alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "'" +
                                    ", w metodzie js '" + userContext.methodName + "': " +
                                "\n\nerror._exceptionType: " + error._exceptionType +
                                ",\n\n error._message: " + error._message +
                                ",\n\n error._stackTrace: " + error._stackTrace +
                                ",\n\n error._statusCode: " + error._statusCode +
                                ",\n\n error._timedOut: " + error._timedOut);
                    },
            //#endregion
                    {'userId': userId, 'methodName': 'prepareRegistrationForm' }
                );
        } else {
            $("#divRegistration").dialog('close');
        }
    });


    /*
    $log("prepareRegistration");
    FB.ensureInit(function() {
    FB.Connect.get_status().waitUntilReady(function(status) {
    if (status != FB.ConnectState.connected) {
    $("#divRegistration").dialog('close');
    } else {
    var userId = FB.Connect.get_loggedInUser();
    K2.Powerade.Web.Bieganie.Scripts.UsersWebSrv.GetUser(
    userId,
    function(user, userContext, methodName) {
    if (user != null) {
    logOnUser(user.UserId, getRedirectUrl());
    }
    else {
    FB.Facebook.apiClient.fql_query(
    "SELECT name, username, sex, birthday_date, pic_big_with_logo FROM user WHERE uid = "
    + FB.Connect.get_loggedInUser(),
    function(results, ex) {
    var result = results[0];
    $("#selectSex").val(result['sex']);
    var birth = $(__birthSelector);
    if (result['birthday_date']) {
    var birthDate = result['birthday_date'].split("/", 3);
    birth.val(birthDate[2] + "-" + birthDate[0] + "-" + birthDate[1]);
    }
    $.datepicker.setDefaults($.datepicker.regional['pl']);
    birth.datepicker({
    defaultDate : "1950-01-01", 
    changeMonth: true,
    changeYear: true,
    yearRange: '1950:2010',
    beforeShow: function() { $('#ui-datepicker-div').maxZIndex(); },
    onSelect: function(dateText, inst) { }
    });
    var userName = result['username'];
    var nick = $("#textNick");
    nick.val(userName == null ? result['name'] : userName);
    var profilePic = $("img#profilePic");
    if (result['pic_big_with_logo']) {
    profilePic.attr("src", result['pic_big_with_logo'].replace(/&amp;/gi, "&"));
    profilePic.attr("alt", nick.val());
    profilePic.attr("title", nick.val());
    }
    prepareRegistrationDialog();
    $("#divRegistration").dialog('open');
    $("#ui-datepicker-div").removeClass("ui-helper-clearfix");
    $("#divRegistration").siblings().filter('.ui-dialog-titlebar,.ui-dialog-buttonpane').addClass("fix");
    $('.ui-dialog .ui-state-default, .ui-dialog .ui-state-hover').css({
    font: "12px tahoma",
    border: "1px solid #CCCCCC"
    });
    $('.ui-dialog .ui-dialog-buttonpane').css({
    backgroundPosition: "0 100%",
    height: "37px"
    });
    }
    );
    }
    },
    //#region function error
    function(error, userContext, methodName) {
    if (consts.debug)
    alert("Wystąpił błąd w metodzie WebServisu '" + methodName + "'" +
    ", w metodzie js '" + userContext.methodName + "': " +
    "\n\nerror._exceptionType: " + error._exceptionType +
    ",\n\n error._message: " + error._message +
    ",\n\n error._stackTrace: " + error._stackTrace +
    ",\n\n error._statusCode: " + error._statusCode +
    ",\n\n error._timedOut: " + error._timedOut);
    },
    //#endregion
    {'userId': userId, 'methodName': 'prepareRegistrationForm' }
    );
    }
    });
    });
    */
}
//#endregion
function getValueFromURL(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function getRedirectUrl() {
    var redirectUrl = getValueFromURL('redirectUrl');
    if (redirectUrl != '')
        redirectUrl = urlDecode(unescape(redirectUrl));
    else
        redirectUrl = consts.poweradePages.newsPage;

    return redirectUrl;
}

function urlDecode(utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while (i < utftext.length) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if ((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i + 1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i + 1);
            c3 = utftext.charCodeAt(i + 2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

