﻿$(document).ready(function() {
    //Signup related code
    $(".signup").click(function(e) {
        e.preventDefault();
        $("fieldset#signup_menu").toggle();
        $(".signin").toggleClass("menu-open");
        $("#singnupFields").show();
        $("#errorDiv").hide();
        $("#InfoDiv").hide();
        $("#ThanksDiv").hide();
        $("fieldset#regConfirmation").hide();
        $("fieldset#resetpwd_menu").hide();
        $("fieldset#login_menu").hide();
        document.getElementById("btnSignup").style.display = "block";
        document.getElementById("btnSignupDisable").style.display = "none";
        //        document.getElementById("signup-mask").style.height = document.getElementById("singnupFields").offsetHeight + "px";
        //        document.getElementById("signup-mask").style.width = document.getElementById("singnupFields").offsetWidth + "px";
        scrollTo(0, 0);
        ClearInputInformation();
        $("#txtDisplayName").focus();
    });

    $("#saveUploadFile").click(function() {
        onUploadClick();
    }
    );

    $("#btnSignup").click(function() {
        if (ValidateInputData()) {
            //document.getElementById("signup-mask").style.display = "block";
            document.getElementById("btnSignupDisable").style.display = "block";
            document.getElementById("btnSignup").style.display = "none";
            PageMethods.SignupUser($("#txtDisplayName").val().trim(), $("#txtEmail").val().trim(), $("#txtPassword").val(), OnCallSumComplete, OnCallSumError)
            return false;
        }
    }); //button signup end

    $("#btnCancel").click(function() {
        $("fieldset#signup_menu").hide();
        document.getElementById("btnSignup").style.display = "block";
        return false;
    });

    $("#logout").click(function() {
        PageMethods.UserLogout(OnLogoutComplete, OnLogoutError);
        HideAllDivs();
    });

    $("#help").click(function() {
        HideAllDivs();
    });

    $(".help").click(function() {
        HideAllDivs();
    });

    function HideAllDivs() {
        $("#singnupFields").hide();
        $("#ThanksDiv").hide();
        $("#loginSection").hide();
        $("#forgotPasswordSection").hide();
        $("#divForgotSuccessMessage").hide();
        $("#video-convertion-wrapper").hide();
        $("#uploadProgressDIV").hide();
        $("#uploadSuccessDIV").hide();
        $("fieldset#regConfirmation").hide();
        $("fieldset#resetpwd_menu").hide();
        $("fieldset#upload_menu").hide();
    }

    function trimString(str) {
        return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
    }

    function ValidateEmail(emailStr) {
        var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (!emailReg.test(emailStr)) {
            return false;
        } else {
            return true;
        }
    }

    function CheckForAlphaNumeric(firstChar) {
        var displayName = /^([a-z|A-Z|0-9|])$/;
        if (!displayName.test(firstChar)) {
            return false;
        } else {
            return true;
        }
    }

    function ValidateDisplayName(displaynameStr) {
        var displayName = /^([a-z|A-Z|0-9|]+[A-Za-z0-9_&quot;\-\@\*\#\?\,\$\!\(\)]+)$/;
        if (!displayName.test(displaynameStr)) {
            return false;
        } else {
            return true;
        }
    }

    function ValidateInputData() {
        var displayNameValue = $("#txtDisplayName").val().trim();
        var tempDisplayName = $("#txtDisplayName").val().trim();
        var emailValue = $("#txtEmail").val().trim();
        var passwordValue = $("#txtPassword").val();
        var termsCheckValue = $('#chkTerms:checked').val();

        var errorDiv = $("#errorDiv");
        var infoDiv = $("#InfoDiv");
        var errText = "";

        if (trimString(tempDisplayName) == "") {
            errText = errText + "<li>Please enter Display Name</li>"
        }
        else {

            while (tempDisplayName.indexOf("'") > 0) {
                tempDisplayName = tempDisplayName.replace("'", "");
            }

            if (!ValidateDisplayName(tempDisplayName)) {
                if (tempDisplayName.length == 1)
                    errText = errText + "<li>Display Name must be 2 characters minimum</li>"
                else
                    errText = errText + "<li>Please enter valid Display Name</li>"
            }
        }

        if (trimString(emailValue) == "") {
            errText = errText + "<li>Please enter Email</li>"
        }
        else if (!ValidateEmail(emailValue)) {
            errText = errText + "<li>Please enter a valid email address (Ex: your_name@domain.com)</li>"
        }

        if (trimString(passwordValue) == "")
            errText = errText + "<li>Please enter Password</li>"

        if (termsCheckValue == undefined)
            errText = errText + "<li>Please select Terms and Conditions</li>"

        if (errText != "") {
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html(errText);
            return false;
        }
        else {
            errorDiv.hide();
            infoDiv.hide();
            return true;
        }
    }

    function ClearInputInformation() {
        $("#txtDisplayName").val("");
        $("#txtEmail").val("");
        $("#txtPassword").val("");

        $("#txtLoginName").val("");
        $("#txtLoginPassword").val("");

        $("#txtPassword").val("");

        $('#chkLoginCheck').removeAttr('checked');
        $('#chkTerms').removeAttr('checked');

    }

    function OnCallSumComplete(result) {
        //document.getElementById("signup-mask").style.display = "none";
        document.getElementById("btnSignupDisable").style.display = "none";
        document.getElementById("btnSignup").style.display = "block";
        if (result == "Success") {
            ClearInputInformation();
            $("#singnupFields").hide();
            $("#ThanksDiv").show();
        }
        else if (result == "BothExists") {
            var errorDiv = $("#errorDiv");
            var infoDiv = $("#InfoDiv");
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html("<li> This Display Name and Email are not available. Please try different Display Name and Email</li>");
            document.getElementById("btnSignup").style.display = "block";
            return false;
        }
        else if (result == "DisplayNameExists") {
            var errorDiv = $("#errorDiv");
            var infoDiv = $("#InfoDiv");
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html("<li> This Display Name is not available. Please try a different Display Name</li>");
            document.getElementById("btnSignup").style.display = "block";
            return false;
        }
        else if (result == "EmailExists") {
            var errorDiv = $("#errorDiv");
            var infoDiv = $("#InfoDiv");
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html("<li> This Email is not available. Please try a different Email</li>");
            document.getElementById("btnSignup").style.display = "block";
            return false;
        }
        else {
            var errorDiv = $("#errorDiv");
            var infoDiv = $("#InfoDiv");
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html("<li> Error While sending the confirmation Email. Please try after some time</li>");
            return false;
        }
        return false;
        //$.unblockUI({ message: $('#SignupDiv') });
    }

    function OnCallSumError(result) {
        var errorDiv = $("#errorDiv");
        var infoDiv = $("#InfoDiv");
        errorDiv.show();
        infoDiv.hide();
        errorDiv.html("<li> Error While sending the confirmation Email. Please try after some time</li>");
        document.getElementById("btnSignupDisable").style.display = "none";
        document.getElementById("btnSignup").style.display = "block";
        return false;
        // alert("Failure:" + result);
    }

    $(".termscons").click(function() {
        var left = (window.innerWidth - 890) / 2;
        window.showModalDialog("/ui/TermsandConditions.aspx", "", "dialogWidth:890px; dialogHeight:390px; dialogTop:230px; resizable:no; status:no; dialogLeft:" + left + "px");
    });

    $(".uploadtextLinks").click(function() {
        var left = (window.innerWidth - 890) / 2;
        window.showModalDialog("/ui/TermsandConditions.aspx", "", "dialogWidth:890px; dialogHeight:390px; dialogTop:230px; resizable:no; status:no; dialogLeft:" + left + "px");
    });

    function termsconsInitializer() {
        var termsconsInitializer1 = {
            run: function() {
                // var oScrollTermsnConditions = $('#scrollTermsnConditions');
                var oScrollTermsnConditions = $('#scrollSignupTC');
                if (oScrollTermsnConditions.length > 0) {
                    oScrollTermsnConditions.tinyscrollbar({ size: 200 });
                }

                var oCon = document.getElementById('mcon');
                var oLink = document.createElement('a');
                var oText = document.createTextNode("me");
                var sPart0 = 'ma';
                var sPart1 = 'ilto:wie';
                var sPart2 = 'ringen';
                var sPart3 = '@gm';
                var sPart4 = 'ail.com';
                oLink.href = sPart0 + sPart1 + sPart2 + sPart3 + sPart4;
            }
        };
        termsconsInitializer1.run();
    }


    $("#ImgOk").click(function() {
        $("#singnupFields").show();
        $("#ThanksDiv").hide();
        return false;
    });

    $("#ImgThanksOk").click(function() {
        //        $("#singnupFields").hide();
        //        $("#termsconditions").hide();
        //        $("#ThanksDiv").hide();
        $("#signup_menu").hide();
        return false;
    });

    //Login buttion related code
    $(".signin").click(function(e) {
        e.preventDefault();
        $("fieldset#login_menu").toggle();
        $(".signin").toggleClass("menu-open");
        $("#forgotPasswordSection").hide();
        $("#divForgotSuccessMessage").hide();
        $("#loginSection").show();
        $("#loginErrorDiv").hide();
        $("#loginInfoDiv").hide();
        $("fieldset#regConfirmation").hide();
        $("fieldset#resetpwd_menu").hide();
        $("fieldset#signup_menu").hide();
        ClearInputInformation();
        $("#txtLoginName").focus();
        document.getElementById("btnLoginSubmit").style.display = "block";
        document.getElementById("btnLoginSubmitDisable").style.display = "none";
    });

    $("#btnLoginSubmit").click(function() {
        var errorDiv = $("#loginErrorDiv");
        var infoDiv = $("#loginInfoDiv");
        errorDiv.html("");
        //errorDiv.hide();
        //infoDiv.hide();
        if (ValidateLoginInputData()) {

            var keepmeloggedinCheckValue = $('#chkLoginCheck:checked').val();

            if (keepmeloggedinCheckValue == undefined)
                keepmeloggedinCheckValue = "0"
            else
                keepmeloggedinCheckValue = "1"

            $("#btnLoginSubmit").hide();
            $("#btnLoginSubmitDisable").show();

            var errorDiv = $("#loginErrorDiv");
            var infoDiv = $("#loginInfoDiv");

            errorDiv.hide();
            infoDiv.hide();

            var password = $("#txtLoginPassword").val();
            password = escape(password);

            $.ajax({
                type: "POST",
                async: false,
                url: "/ui/SynchronousPageMethods.aspx/UserLogin_Synchronous",
                data: "{userEmail:'" + $("#txtLoginName").val() + "',password:'" + password + "',keepLoggedinCheck:'" + keepmeloggedinCheckValue + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    OnCallLoginComplete(msg.d);
                }
            });

            return false;
        }
    }); //button login end

    $("#btnLoginCancel").click(function() {
        $("fieldset#login_menu").hide();
        //document.getElementById("btnLoginSubmit").style.display = "block";
        return false;
    });

    function OnCallLoginComplete(result) {

        $("#btnLoginSubmit").show();
        $("#btnLoginSubmitDisable").hide();

        if (result != "False") {
            //Load fav media and subscribed channels
            //PageMethods.GetUserFavoriteMediaAndChannelsInfo(onGetFavoriteVideosComplete);

            if (result == "invalid")
                showLoginFailureMessage("invalid");
            else if (result == "suspended")
                showLoginFailureMessage("suspended");
            else if (result == "inactive")
                showLoginFailureMessage("inactive");
            else if (result == "purge")
                showLoginFailureMessage("purge");
            else {
                //success case
                $("fieldset#login_menu").hide();

                $("#ctl00_lginStatus").show();
                $("#ctl00_ctl00_lginStatus").show();

                $("#ctl00_preLinks").hide();
                $("#ctl00_ctl00_preLinks").hide();

                var outputUrl = window.location.href;
                if ((outputUrl.toLowerCase().indexOf("reset") > 0) || (outputUrl.toLowerCase().indexOf("conf") > 0)) {
                    if (outputUrl.indexOf("?") > 0) {
                        var urls = outputUrl.split("?")
                        outputUrl = urls[0];
                    }
                }
                outputUrl = outputUrl.replace('#', '');
                if (outputUrl.indexOf("ChangeMailId.aspx") > 0) {
                    outputUrl = outputUrl.replace("ChangeMailId.aspx", "privatechannel.aspx");
                }

                window.location.href = outputUrl;

                //                if (($.browser.msie) && ($.browser.version == '9.0')) {
                //                    window.location.href = outputUrl;
                //                }
                //                else {
                //                    window.location.href = outputUrl;
                //                }
            }
        }
        else {
            //document.getElementById("btnLoginSubmit").style.display = "block";

            showLoginFailureMessage("invalid");
        }
        return false;
    }
    function onGetFavoriteVideosComplete(result) {
        window.location.reload(); //Refresh the page after login
    }
    function onNotificationCountCalcComplete(result) {
        if (result != "") {
            if (result > 0) {

                var className = GetProfileClassName(result);
                var currentClassName;

                if (document.getElementById('ctl00_notificationImg') != null) {
                    currentClassName = document.getElementById('ctl00_notificationImg').className;
                    $('#ctl00_notificationImg').attr("class", className);
                    if (result == 1) {
                        $('#ctl00_notificationImg').attr("title", "New Notification");
                    }
                    else if (result > 1)
                        document.getElementById('ctl00_notificationImg').setAttribute("title", " New Notifications");
                }
                else {
                    currentClassName = document.getElementById('ctl00_ctl00_notificationImg').className;
                    $('#ctl00_ctl00_notificationImg').attr("class", className);
                    if (result == 1)
                        document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", "New Notification");
                    else if (result > 1)
                        document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", " New Notifications");
                }
                if (className != currentClassName) {
                    if (document.location.href.toLowerCase().indexOf("privatechannel", 1) > 0) {
                        setTimeout('__doPostBack("ctl00$pnlLeftPlaceHolder$PrivateChannelVideos$btnRefresh", "");', 1000);
                        setTimeout('__doPostBack("ctl00$pnlLeftPlaceHolder$PrivateChannelPhotos$btnRefresh", "");', 6000);
                    }
                }
            }
            else {
                if (document.getElementById('ctl00_notificationImg') != null) {
                    $("#ctl00_notificationImg").attr("class", "profile");
                    document.getElementById('ctl00_notificationImg').setAttribute("title", "Notifications");
                }
                else {
                    $("#ctl00_ctl00_notificationImg").attr("class", "profile");
                    document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", "Notifications");
                }
            }
        }
    }

    function OnCallLoginError(result) {
        showLoginFailureMessage("invalid");
    }

    function showLoginFailureMessage(inputResult) {
        document.getElementById("btnLoginSubmit").style.display = "block";
        document.getElementById("btnLoginSubmitDisable").style.display = "none";

        var errorDiv = $("#loginErrorDiv");
        var infoDiv = $("#loginInfoDiv");

        var errText = "<li>Invalid User Name / Password</li>";

        if (inputResult == "invalid")
            errText = "<li>Invalid User Name / Password</li>";
        else if (inputResult == "suspended")
            errText = "<li> This account has been suspended. </li>";
        else if (inputResult == "inactive")
            errText = "<li> This account is inactive. </li>";
        else if (inputResult == "purge")
            errText = "<li> This account has been purged. </li>";
        else
            errText = "<li>Invalid User Name / Password</li>";

        if (errText != "") {
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html(errText);
            return false;
        }
        else {
            errorDiv.hide();
            infoDiv.hide();
            return true;
        }
    }

    function ValidateLoginInputData() {
        var loginNameValue = $("#txtLoginName").val().trim();
        var loginPasswordValue = $("#txtLoginPassword").val();
        var keepmeloggedinCheckValue = $('#chkLoginCheck:checked').val();

        var errorDiv = $("#loginErrorDiv");
        var infoDiv = $("#loginInfoDiv");
        var errText = "";

        if (trimString(loginNameValue) == "") {
            errText = errText + "<li>Please enter Email</li>"
        } else if (!ValidateEmail(loginNameValue)) {
            errText = errText + "<li>Please enter a valid email address (Ex: your_name@domain.com)</li>"
        }

        if (trimString(loginPasswordValue) == "")
            errText = errText + "<li>Please enter Password</li>"

        if (errText != "") {
            errorDiv.show();
            infoDiv.hide();
            errorDiv.html(errText);
            return false;
        }
        else {
            errorDiv.hide();
            infoDiv.hide();
            return true;
        }
    }

    $("#Forgotpassword").click(function() {
        $("#loginSection").hide();
        $("#forgotPasswordSection").show();
        //document.getElementById("forgotpwd-mask").style.height = document.getElementById("forgotPasswordSection").offsetHeight + "px";
        //document.getElementById("forgotpwd-mask").style.width = document.getElementById("forgotPasswordSection").offsetWidth + "px";
        //$("#forgotpwd-mask").hide();
        return false;
    });

    $("#ImgForgotCancel").click(function() {
        $("#loginSection").show();
        $("#forgotPasswordSection").hide();
        var errorDiv = $("#forgotErrDiv");
        errorDiv.html("");
        errorDiv.hide();
        document.getElementById("txtForgotUserName").value = '';
        $("#txtForgotEmail").val("");
        return false;
    });

    $("#ImgForgotSubmit").click(function() {
        if (ValidateLoginInput()) {
            //document.getElementById("forgotpwd-mask").style.display = "block";
            document.getElementById("ImgForgotSubmit").style.display = "none";
            document.getElementById("ImgForgotSubmitDisable").style.display = "block";

            PageMethods.ResetUserPassword($("#txtForgotUserName").val().trim(), $("#txtForgotEmail").val().trim(), OnCallForgotComplete, OnCallForgotError)

            return false;
        }
        else {
            document.getElementById("forgotpwd-mask").style.display = "none";
            $("#txtForgotEmail").val("");
            return false;
        }
    });

    $("#imgForgotSuccess").click(function() {
        $("#login_menu").hide();
        $("#txtForgotEmail").val("");
        //        $("#forgotPasswordSection").hide();
        //        $("#divForgotSuccessMessage").hide();
        //location.reload();
    });


    function OnCallForgotComplete(res) {

        document.getElementById("ImgForgotSubmit").style.display = "block";
        document.getElementById("ImgForgotSubmitDisable").style.display = "none";

        if (res == "Fail") {
            document.getElementById("forgotpwd-mask").style.display = "none";
            ShowForgotError("Fail");
        }
        else if (res == "EmailFailure") {
            document.getElementById("forgotpwd-mask").style.display = "none";
            ShowForgotError("EmailFailure");
        }
        else {
            //success
            $("#divForgotSuccessMessage").show();
            $("#forgotPasswordSection").hide();
            $("#loginSection").hide();
        }
    }

    function OnCallForgotError(res) {
        ShowForgotError(res);
    }

    function ShowForgotError(result) {

        document.getElementById("ImgForgotSubmit").style.display = "block";

        document.getElementById("ImgForgotSubmitDisable").style.display = "none";

        var errorDiv = $("#forgotErrDiv");
        var infoDiv = $("#forgotInfoDiv");
        var errText = "";

        if (result == "EmailFailure")
            errText = "<li> Error while sending the Email. Plase try after some time.</li>"
        else
            errText = "<li> Invalid Email. Please Enter your registered Account Email.</li>"

        if (errText != "") {
            infoDiv.hide();
            errorDiv.show();
            errorDiv.html(errText);
            return false;
        }
        else {
            errorDiv.hide();
            infoDiv.hide();
            return true;
        }
    }

    function ValidateLoginInput() {

        var errorDiv = $("#forgotErrDiv");
        var infoDiv = $("#forgotInfoDiv");
        var errText = ""

        var loginNameValue = $("#txtForgotUserName").val();
        var emailValue = $("#txtForgotEmail").val().trim();


        if (trimString(loginNameValue) == "") {
            if (trimString(emailValue) == "") {
                errText = errText + "<li>Please enter Account Email</li>"
            }
            else if (!ValidateEmail(emailValue)) {
                errText = errText + "<li>Please enter a valid email address (Ex: your_name@domain.com)</li>"
            }
        } else if (!ValidateDisplayName(loginNameValue)) {
            errText = errText + "<li>Please enter valid User Name</li>"
            if (trimString(emailValue) != "") {
                if (!ValidateEmail(emailValue)) {
                    errText = errText + "<li>Please enter a valid email address (Ex: your_name@domain.com)</li>"
                }
            }
        }

        if (errText != "") {
            infoDiv.hide();
            errorDiv.show();
            errorDiv.html(errText);
            return false;
        }
        else {
            errorDiv.hide();
            infoDiv.hide();
            return true;
        }
    }

    //Upload menu
    $(".upload").click(function(e) {
        e.preventDefault();
        if (document.getElementById('upload_menu').style.display == "block") {
            return false;
        }
        else {
            $("#video-convertion-wrapper").hide();
            ClearUploadInformation();
            $("fieldset#upload_menu").toggle();
            ChangeUploadImageClass();
            if (document.location.href.toLowerCase().indexOf("privatechannel", 1) > 0) {
                //document.getElementById('upload_menu').scrollIntoView(true);
                window.scrollTo(0, 0)
            }

            $("#saveUploadFile").show();
            $("ChooseFile").show();
            $("#progressWarn").hide();
            var errorDiv = $get('uploadErrorDiv');
            errorDiv.innerHTML = "";
            errorDiv.style.display = "none";
            $("#txtFileUploadLabel").focus();
            clearFiles();
            OnFileUploadClick();
            guidelinesinitializer();
        }
    });


    function guidelinesinitializer() {
        var Websiteuploadguidelines = {
            run: function() {
                var oScroll8 = $('#scroll-small');
                if (oScroll8.length > 0) {
                    oScroll8.tinyscrollbar({ size: 200 });
                }

                var oCon = document.getElementById('mcon');
                var oLink = document.createElement('a');
                var oText = document.createTextNode("me");
                var sPart0 = 'ma';
                var sPart1 = 'ilto:wie';
                var sPart2 = 'ringen';
                var sPart3 = '@gm';
                var sPart4 = 'ail.com';
                oLink.href = sPart0 + sPart1 + sPart2 + sPart3 + sPart4;
            }
        };
        Websiteuploadguidelines.run();
    }

    $("#cancelUploadFile").click(function() {
        cancelUpload();
    });

    //image upload status ok
    $("#imgUploadSuccessOK").click(function() {
        OnUploadFileComplete();
        ClearUploadInformation();
        clearFiles();
        OnFileUploadClick();
        $('#uploadImg').attr("class", "upload");
        return false;
    });

    function LogoutUser() {
        PageMethods.UserLogout(OnLogoutComplete, OnLogoutError);

    }

    function OnLogoutComplete(result) {


        $("fieldset#login_menu").hide();

        $("#ctl00_postLinks").hide();
        $("#ctl00_ctl00_postLinks").hide();

        $("#ctl00_preLinks").show();
        $("#ctl00_ctl00_preLinks").show();

        $("#ctl00_lblLoggedInUserName").text("");
        $("#ctl00_ctl00_lblLoggedInUserName").text("");

        HideAllDivs();

        if (document.location.href.toLowerCase().indexOf("privatechannel", 1) > 0)
            document.location.href = "../UI/ChannelsMain.aspx";
        else if (document.location.href.toLowerCase().indexOf("listing", 1) > 0)
            document.location.reload();

        //        DeleteCookie("ASP.NET_SessionId");
        //        DeleteCookie("UserName");
        //        DeleteCookie("UserId");
        DeleteAllCookies();
        return false;
    }

    function DeleteCookie(name) {
        var expires = new Date();
        expires.setUTCFullYear(expires.getUTCFullYear() - 1);
        document.cookie = name + '=; expires=' + expires.toUTCString() + '; path=/';
    }

    function DeleteAllCookies() {
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            var equals = cookies[i].indexOf("="),
            name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
            document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT" + '; path=/';
        }
    }

    function OnLogoutError(result) {
        $("fieldset#login_menu").hide();

        $("#ctl00_postLinks").hide();
        $("#ctl00_ctl00_postLinks").hide();

        $("#ctl00_preLinks").show();
        $("#ctl00_ctl00_preLinks").show();

        $("#ctl00_lblLoggedInUserName").text("");
        $("#ctl00_ctl00_lblLoggedInUserName").text("");

        HideAllDivs();
        return false;
    }



    $(document).mouseup(function(e) {
        if ($(e.target).parent("a.signin").length == 0) {
            $(".signin").removeClass("menu-open");
            $("fieldset#login_menu").hide();
        }

        if ($(e.target).parent("a.signup").length == 0) {
            $(".signup").removeClass("menu-open");
            $("fieldset#signup_menu").hide();
        }

        if ($(e.target).parent("a.searchmenu").length == 0) {
            $(".searchmenu").removeClass("menu-open");
            $("fieldset#search_menu").hide();
        }
    });




    function getFilesize($file) {
        if (is_file($file)) {
            $filePath = $file;
            if (!realpath($filePath)) {
                $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
            }
            $fileSize = filesize($filePath);
            $sizes = array("TB", "GB", "MB", "KB", "B");
            $total = count($sizes);
            while ($total-- && $fileSize > 1024) {
                $fileSize /= 1024;
            }
            return round($fileSize, 2);
        }
        return false;
    }

    /* Search related code */
    //    $('a.anc').bind('click', function() {
    //        var searchKeyword = $("#searchInput").val();
    //        if (searchKeyword == "Search")
    //            searchKeyword = "";

    //        $(this).attr("href", $(this).attr('href') + searchKeyword);
    //    });

    //search anchor click
    $("#searchAnchor").click(function() {
        var txtSearchInputValue = $("#searchInput").val();
        if (txtSearchInputValue == 'Search')
            txtSearchInputValue = "";
        $("#searchAnchor").attr('href', '../UI/SearchResults.aspx?SeachParm=' + txtSearchInputValue);
    });



    //search help button click
    $("#searchButAnchor").click(function() {
        var searchKeyword = $("#searchHelpField").val();
        if (searchKeyword == 'Search')
            searchKeyword = "";
        $(this).attr("href", $(this).attr('href') + searchKeyword);
    });


    //search help button click
    $("#searchChannelButAnchor").click(function() {
        var searchKeyword = $("#searchChannelField").val();
        if (searchKeyword == 'Search')
            searchKeyword = "";
        $(this).attr("href", $(this).attr('href') + searchKeyword);
    });
    /* Search related code */


    function OnSetSearchComplete(result) {
        return false;
    }

    function OnSetSearchError(result) {
        return false;
    }

    $("#imgResetPwdCancel").click(function() {
        $("fieldset#resetpwd_menu").hide();
    });

    $("#imgResetPwdSubmit").click(function() {
        var ResetnewpasswordValue = $("#txtResetNewPassword").val();
        var ResetRenewpasswordValue = $("#txtResetReNewPassword").val();
        var errorDiv = $("#resetPWDErrordiv");
        var infoDiv = $("#resetPWDInfodiv");
        var errText = "";

        ResetnewpasswordValue = trimString(ResetnewpasswordValue);
        ResetRenewpasswordValue = trimString(ResetRenewpasswordValue);

        if (ResetnewpasswordValue == "") {
            errText = "<li>Please Enter Password</li>";
        }
        else {
            if (ResetRenewpasswordValue == "") {
                errText = "<li>Please Enter Confirm Password</li>";
            }
            else {
                //if both values are not null
                if (ResetnewpasswordValue != ResetRenewpasswordValue)
                    errText = "<li>Passwords do not match</li>";
            }
        }

        if (errText != "") {
            infoDiv.hide();
            errorDiv.show();
            errorDiv.html(errText);
            return false;
        }
        else {
            infoDiv.hide();
            errorDiv.hide();
            hu = window.location.search.substring(1);
            PageMethods.ResetUserPasswordByTokenId(hu.split('=')[1], ResetnewpasswordValue, onResetPwdSuccess);
        }
        return true;

    });

    $("#regConfirmClose").click(function() {
        $("#regConfirmation").hide();
    });

    $("#regConfirmGotoChannel").click(function() {
        $("#regConfirmation").hide();
        window.location = '../UI/PrivateChannel.aspx'
    });


    $("#ctl00_notificationImg").click(function(e) {
        e.preventDefault();
        if (document.getElementById("ctl00_notificationImg") != null) {
            if (document.getElementById("ctl00_notificationImg").className != "profile")
                PageMethods.GetUserNotifications(OnGetNotificationComplete);
        }
    });

    $("#ctl00_ctl00_notificationImg").click(function(e) {
        e.preventDefault();
        if (document.getElementById("ctl00_ctl00_notificationImg").className != "profile")
            PageMethods.GetUserNotifications(OnGetNotificationComplete);
    });


    setInterval(
       function() {
           var userName = "";
           if (document.getElementById('ctl00_lblLoggedInUserName') != null)
               userName = document.getElementById('ctl00_lblLoggedInUserName').innerHTML;
           else
               userName = document.getElementById('ctl00_ctl00_lblLoggedInUserName').innerHTML;

           if (userName != "") {
               if (document.getElementById("progressWarn").style.display != "block") {
                   PageMethods.UserNotificationCount(onNotificationCountCalcComplete);
               }
           }
       }, 60000); //1 minutes
});                                                                                                                       //docuement end


function yourAjaxCall1() {
    if((document.getElementById("<%=lblLoggedInUserName.ClientID >") != null) && (document.getElementById('<%= lblLoggedInUserName.ClientID >').value != "") && (document.getElementById("notificationImg").className != "profile"))
        PageMethods.UserNotificationCount(onNotificationCountCalcComplete);
}

function OnGetNotificationComplete(result) {
    if (result != ",,,0,") {
        ShowNotificationMessage(result);
    }
    else {
        if (document.getElementById('ctl00_notificationImg') != null) {
            //document.getElementById('ctl00_notificationImg').setAttribute("class", "profile");
            $("#ctl00_notificationImg").attr("class", "profile");
            document.getElementById('ctl00_notificationImg').setAttribute("title", "Notifications");
        }
        else {
            //document.getElementById('ctl00_ctl00_notificationImg').setAttribute("class", "profile");
            $("#ctl00_ctl00_notificationImg").attr("class", "profile");
            document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", "Notifications");
        }
    }
        
    return false;
}

function onResetPwdSuccess(result) {
    var errorDiv = $("#resetPWDErrordiv");
    var infoDiv = $("#resetPWDInfodiv");
    var errText = "";
    
    if (result == "InvalidToken")
        errText = "<li>Invalid Token / Token is expried</li>";
    else if(result == "Fail")
        errText = "<li>Error while trying to reset your password. Plase try after some time.</li>";

    if (errText != "") {
        infoDiv.hide();
        errorDiv.show();
        errorDiv.html(errText);
        return false;
    }
    else {
        $("fieldset#resetpwd_menu").hide();
        window.location = '../UI/HomeMain.aspx'
    }
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function checkCookie() {
    var username = getCookie("username");
    if (username != null && username != "") {
        alert("Welcome again " + username);
    }
    else {
        username = prompt("Please enter your name:", "");
        if (username != null && username != "") {
            setCookie("username", username, 365);
        }
    }
}

function ValidateResetPasswordUserInput() {
    var errText = "";
    if (document.getElementById("ctl00_ctl00_pnlLeftPlaceHolder_pnlLeftPlaceHolder_txtNewPassword").value == "") {
        errText = "<li>Please Enter Password</li>";
    }
    else {
        if (document.getElementById("ctl00_ctl00_pnlLeftPlaceHolder_pnlLeftPlaceHolder_txtConfirmPassword").value == "") {
            errText = "<li>Please Enter Confirm Password</li>";
        }
        else {
            //if both values are not null
            if(document.getElementById("ctl00_ctl00_pnlLeftPlaceHolder_pnlLeftPlaceHolder_txtNewPassword").value != document.getElementById("ctl00_ctl00_pnlLeftPlaceHolder_pnlLeftPlaceHolder_txtConfirmPassword").value)
                errText = "<li>Confirm password is not matched with the new password</li>";
        }
    }
    
    if (errText != "") {
        document.getElementById("ctl00_ctl00_pnlLeftPlaceHolder_pnlLeftPlaceHolder_errorDiv").style.display = "block";
        document.getElementById("ctl00_ctl00_pnlLeftPlaceHolder_pnlLeftPlaceHolder_errorDiv").innerHTML = errText;
        return false;
    }
    return true;
}

function ClearUploadInformation() {

    $("fieldset#upload_menu").hide();
    $('#uploadErrorDiv').hide();

    $('#txtFileUploadLabel').val("");

    $('#txtFileUploadTags').val("");

    $('#ctl00_txtFileUploadDescription').val("")
    $('#ctl00_spnMediaDescLimit').html("750/750 Characters")
    
    $('#ctl00_ctl00_txtFileUploadDescription').val("")
    $('#ctl00_ctl00_spnMediaDescLimit').html("750/750 Characters")

    if(document.getElementById("ctl00_ddlcategory") != null)
        $('#ctl00_ddlcategory')[0].selectedIndex = 0;
     else    
        $('#ctl00_ctl00_ddlcategory')[0].selectedIndex = 0;

    $('#ddlPrivacy')[0].selectedIndex = 0;

    var errorDiv = $get('uploadErrorDiv');
    errorDiv.style.display = "none";
    errorDiv.innerHTML = "";

    $("#uploadImg").attr("class", "upload");
    
    document.getElementById("ChooseFile").style.display = "block";
    document.getElementById("saveUploadFile").style.display = "block";
    //CancelCurrentUpload();
}

function ShowConfirmationMessage(inputMsg) {

    $("fieldset#regConfirmation").show();
    
    if (inputMsg === "Fail") {
        $("#regConfirmSuccess").hide();
        $("#refConfirmFailure").show();
        $("#regConfirmGotoChannel").hide();
    }
    else {
        $("#regConfirmSuccess").show();
        $("#refConfirmFailure").hide();
        $("#regConfirmGotoChannel").show();
    }
}

function GetProfileClassName(notCount) {
    if (notCount == 0)
        return "profile";
    else if (notCount <= 9)
        return "profile1-active" + notCount;
    else if (notCount >= 10)
        return "profile1-active10";
    else
        return "profile";
}

function ShowNotificationMessage(messageType) {
    if (messageType != "") {
    
        var inputValues = messageType.split(',');
        var messageText = "";
        
        messageText = inputValues[4];
        $("#lblNoteMessage").text(messageText);

        if (inputValues[0].toLowerCase() == "ok") {
            $("#NoteSuccessButtions").hide();
            $("#NoteFailureButtions").show();
        }
        else if (inputValues[0].toLowerCase() == "nonot") {
            $("#NoteSuccessButtions").hide();
            $("#NoteFailureButtions").show();
        }
        else if (inputValues[0] != "") {
            $("#notificationSuccessURL").attr("href", inputValues[2]);
            $("#NoteSuccessButtions").show();
            $("#NoteFailureButtions").hide();
        }
        if (inputValues[3] > 0) {
        
            var className = GetProfileClassName(inputValues[3]);
            
            if (document.getElementById('ctl00_notificationImg') != null) {

                $("#ctl00_notificationImg").attr("class", className);
                
                //document.getElementById('ctl00_notificationImg').setAttribute("class", "profile menu-open");
                
                if(inputValues[3] == 1)
                    document.getElementById('ctl00_notificationImg').setAttribute("title", "New Notification");
                else if(inputValues[3] > 1)
                    document.getElementById('ctl00_notificationImg').setAttribute("title", " New Notifications");
            }
            else {
                //document.getElementById('ctl00_ctl00_notificationImg').setAttribute("class", "profile menu-open");
                $("#ctl00_ctl00_notificationImg").attr("class", className);
                
                if (inputValues[3] == 1)
                    document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", "New Notification");
                else if (inputValues[3] > 1)
                    document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", " New Notifications");
            }
        }
        else {
            if (document.getElementById('ctl00_notificationImg') != null) {
                //document.getElementById('ctl00_notificationImg').setAttribute("class", "profile");
                $("#ctl00_notificationImg").attr("class", "profile");
                document.getElementById('ctl00_notificationImg').setAttribute("title", "Notifications");
            }
            else {
                //document.getElementById('ctl00_ctl00_notificationImg').setAttribute("class", "profile");
                $("#ctl00_ctl00_notificationImg").attr("class", "profile");
                document.getElementById('ctl00_ctl00_notificationImg').setAttribute("title", "Notifications");
            }
        }
    
        $("#noteConfirm-wrapper").show();

       // $("#noteConfirm-wrapper").delay(5000).fadeOut(5000);
    }
    
    return false;
}
function CloseNotification() {
    $("#noteConfirm-wrapper").hide();
    return false;
}

function ShowUploadStatus(inputMsg1, inputMsg2) {
    if (inputMsg1.indexOf("Success") != -1) {
        $("fieldset#upload_menu").hide();
        $("#video-convertion-wrapper").show();

        var inputValue = inputMsg1.replace("Success|", "");

        if (inputValue != "")
            inputValue = inputValue + " We will notify you when it is available to view.";
        else
            inputValue = "Your media is being processed. We will notify you when it is available to view.";

        document.getElementById('fileUploadStatusresult').innerHTML = inputValue;
    }
    else if (inputMsg1 == "Fail") {
        $("fieldset#upload_menu").show();
        $("#video-convertion-wrapper").hide();
        $("#divUploadInfo").hide();
        var errorDiv = $get('uploadErrorDiv');
        var errText = " <li> Your media file was unreadable. Please try a different file. </li>";
        if (errText != "") {
            errorDiv.style.display = "block";
            errorDiv.innerHTML = errText;
            $("#ChooseFile").show();
            $("#saveUploadFile").show();
            $('#uploadImg').attr("class", "upload menu-open");
            return false;
        }
    }
    else if (inputMsg1 == "donotshow") {
        $("fieldset#upload_menu").hide();
        $("#video-convertion-wrapper").hide();
        $("#divUploadInfo").hide();
        $('#uploadImg').attr("class", "upload");
    }
    else {
        $("fieldset#upload_menu").show();
        $("#video-convertion-wrapper").hide();
        $("#divUploadInfo").hide();
        var errorDiv = $get('uploadErrorDiv');
        var errText = inputMsg1;
        if (errText != "") {
            errorDiv.style.display = "block";
            errorDiv.innerHTML = errText;
            $("#ChooseFile").show();
            $("#saveUploadFile").show();
            $('#uploadImg').attr("class", "upload menu-open");
            return false;
        }
    }
}

function ShowResetPWDDiv(inputMsg) {
    $("fieldset#resetpwd_menu").show();
    if (inputMsg === "InValid") {
        $("#resetTokenSuccess").hide();
        $("#resetTokenFailure").show();
    }
    else {
        $("#resetTokenSuccess").show();
        $("#resetTokenFailure").hide();
    }
}

function CheckSpace(e) {
    var unicode = e.charCode ? e.charCode : e.keyCode
    
    if (unicode != 8) //if the key isn't the backspace key (which we should allow)
    {
        if (unicode == 32) //if not a number
            return false //disable key press
    }
}

function CheckLogin(obj, evt) {
    if (evt.keyCode == 13) {
        $("#btnLoginSubmit").click();
        return false;
    }
    else {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode == 32)
            return false;   
    }
}

function CheckSignup(obj, evt) {
    if (evt.keyCode == 13) {
        $("#btnSignup").click();
        return false;
    }
    else {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode == 32)
            return false;
    }
}

function CheckForgotPwd(obj, evt) {
    if (evt.keyCode == 13) {
        $("#ImgForgotSubmit").click();
    }
    else {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode == 32)
            return false;
    }
}

function CheckUpload(obj, evt) {
    if (evt.keyCode == 13) {
        onUploadClick();
    }
}

function CloseResetTokenFailure() {
    $("fieldset#resetpwd_menu").hide();
}

function SearchEvent(obj, evt) {
    if (evt.keyCode == 13) {
        if (obj.id == "searchInput") {
            var txtSearchInputValue = $("#searchInput").val();
            document.location.href='../UI/SearchResults.aspx?SeachParm=' + txtSearchInputValue;
        }
        else if (obj.id == "searchHelpField")
        {
            var searchKeyword = $("#searchHelpField").val();
            if (searchKeyword == "Search")
                searchKeyword = "";
            document.location.href = '../UI/SearchResultsMore.aspx?MediaType=63&TextsearchFor=' + searchKeyword;
        }
        else if (obj.id == "searchChannelField") {
        var searchKeyword = $("#searchChannelField").val();
            if (searchKeyword == "Search")
                searchKeyword = "";
            document.location.href = '../UI/SearchResultsMore.aspx?MediaType=1205400&TextsearchFor=' + searchKeyword;
        }
        return false;
      }
  }

  function numbersonly(obj, evt) {
      if (evt.keyCode == 13) {
          var inputObjectId = obj.id;
          
          while(inputObjectId.indexOf('_') > 0)
              inputObjectId = inputObjectId.replace('_', '$');

          var replaceText = inputObjectId.substring(inputObjectId.lastIndexOf('$') + 1, inputObjectId.length);
            
          if(inputObjectId.indexOf('Bot') == -1)
              inputObjectId = inputObjectId.replace(replaceText, 'btnGo')
          else
              inputObjectId = inputObjectId.replace(replaceText, 'btnGoBot')

          var outputUrl = window.location.href;
            if ((outputUrl.toLowerCase().indexOf("privatechannel.aspx")!=-1) || (outputUrl.toLowerCase().indexOf("/user/")!=-1))
            {
                __doPostBack(inputObjectId, "");
            }
            else {
                changeFilter('PG', obj);
            }
          return false;
      }
      else {
          var unicode = evt.charCode ? evt.charCode : evt.keyCode
          
          if (unicode != 8) //if the key isn't the backspace key (which we should allow)
          {
              if (evt.which == 0)
                  return true;
              else if (unicode < 48 || unicode > 57) //if not a number
                  return false;  //disable key press
          }
      }
  }


  function DisableRightClick(event) {
      //For mouse right click 
      if (event.button == 2) {
          return false;
      }
  }

    //Event to handle the messge away popup at the time of upload
    window.onbeforeunload = function() { 
        if (document.getElementById('upload_menu').style.display == "block") {
                if (document.getElementById("progressWarn").style.display == "block") {
                    return "If you navigate away now your upload will be lost. Do you wish to cancel your upload?"; 
                    //if (checkParent(e.target.parentNode)) 
                }
        }  
    }

    function checkParent(obj) {
        if (obj.id == "upload_menu")
            return true;

        if ((obj.parentNode == null) || (obj.parentNode == "undefined"))
            return false;

        return checkParent(obj.parentNode);
    }
    /* Used in all Sort n Filter pages */
    function hideMenu() {
        $("#menuMask").show();
        $(".byDefaultMenu").hide();
        $(".allTopicsMenu").hide();
        $(".allTimeMenu").hide();
        $(".allCategoriesMenu").hide();
        $(".allPropsMenu").hide();
    }

    function changeFilter(type, item) {
        var page = 0;
        //            if (document.getElementById("<%= txtStartPage.ClientID %>") != null) {
        //                page = parseInt(document.getElementById("<%= txtStartPage.ClientID %>").value) - 1;
        //            }
        if (type == 'PGP' || type == 'PGN') {
            page = parseInt(document.getElementById(item.id.substring(0, item.id.lastIndexOf('_')) + "_txtStartPage").value);
        }
        else if (type == 'PG') {
            page = parseInt(document.getElementById(item.id).value);
            if (page < 0)
                page = 1;
        }

        var count = 0;
        var newFilter = "";
        var currentUrl = window.location.href;
        currentUrl = currentUrl.replace('#', '');
        var queryString = "";
        queryString = currentUrl.split('?');
        var leftPart = queryString[0];
        var result = queryString[1].split('&');
        for (var i = 0; i < result.length; i++) {
            if (type == 'C') {
                if (result[i].indexOf('CategoryId') != -1) {
                    result[i] = 'CategoryId=' + item.className;
                    count++;
                }
            }
            if (type == 'P') {
                if (result[i].indexOf('PropType') != -1) {
                    result[i] = 'PropType=' + item.className;
                    count++;
                }
            }
            if (type == 'T') {
                if (result[i].indexOf('Topic') != -1) {
                    result[i] = 'Topic=' + item.className;
                    count++;
                }
            }
            if (type == 'PD') {
                if (result[i].indexOf('Period') != -1) {
                    result[i] = 'Period=' + item.className;
                    count++;
                }
            }
            if (type == 'SO') {
                if (result[i].indexOf('SOrder') != -1) {
                    result[i] = 'SOrder=' + item.className;
                    count++;
                }
            }
            if (type != 'PGP' || type != 'PGN' || type != 'PG') {
                if (result[i].indexOf('Page') != -1) {
                    result[i] = 'Page=1';
                }
            }
            if (type == 'PGP') {
                if (result[i].indexOf('Page') != -1) {
                    result[i] = 'Page=' + (page - 1);
                    count++;
                }
            }
            if (type == 'PGN') {
                if (result[i].indexOf('Page') != -1) {
                    result[i] = 'Page=' + (page + 1);
                    count++;
                }
            }
            if (type == 'PG') {
                if (result[i].indexOf('Page') != -1) {
                    result[i] = 'Page=' + page;
                    count++;
                }
            }
        }
        if (count == 0) {
            if (type == 'C') {
                newFilter = '&CategoryId=' + item.className;
            }
            if (type == 'P') {
                newFilter = '&PropType=' + item.className;
            }
            if (type == 'T') {
                newFilter = '&Topic=' + item.className;
            }
            if (type == 'PD') {
                newFilter = '&Period=' + item.className;
            }
            if (type == 'SO') {
                newFilter = '&SOrder=' + item.className;
            }
            if (type == 'PGP') {
                result[i] = '&Page=' + (page - 1);
            }
            if (type == 'PGN') {
                result[i] = '&Page=' + (page + 1);
            }
            if (type == 'PG') {
                result[i] = '&Page=' + page;
            }
        }

        newQueryString = "";
        for (var i = 0; i < result.length; i++) {
            if (i == 0) {
                newQueryString = result[i];
            }
            else {
                newQueryString += '&' + result[i];
            }
        }

        var newUrl = leftPart + '?' + newQueryString + newFilter;
        window.location.href = newUrl;
        // get the Href
        // find the type in query string
        // case 1: not found -- append new param
        // case 2: exists -- replace the value (split with '&')            
    }
