﻿function Share() {
    /* PUBLIC FUNCTIONS */
    this.Render = AddScripts;
    this.Show = ShowShare;
    this.Close = CloseShare;

    /* PRIVATE VARIABLES */
    var IsLoggedIn = true;
    var ItemID = -1;
    var SiteID = -1;
    var ItemType = -1;
    var UserID = -1;
    var SharedURL = '';
    var IsLoggedIn = false;
    var mainUploadDiv = "";
    var buttonFooter = "";
    var popupContent = "";
    var statusDiv = "";
    var submitButton = "";
    var closeLink = "";
    var baseURL = "http://www.copperstrings.com";
    var recipientList = new Array();
    var addTextBoxData = true;
    var recipientlistDiv = "";
    var shareImg = "";
    var shareTitle = "";
    var shareDescription = "";
    var shareImgDiv = "";
    var divRowText = "";

	function AddScripts(LoggedIn) 
    {
        loadCss([baseURL + "/CommonScripts/jquery.autocomplete.css", baseURL + "/CommonScripts/share.css"]);
        loadImages([baseURL + "/CommonScripts/images/popup_top.png", baseURL + "/CommonScripts/images/popup_middle.png", baseURL + "/CommonScripts/images/popup_bottom.png", baseURL + "/CommonScripts/images/close.png"]);
        LoadAutoComplete();
   }

   function LoadAutoComplete(LoggedIn) {
       loadScript(baseURL + "/CommonScripts/jquery.autocomplete.js", function (){ LoadJsonP(LoggedIn) });
   }

   function LoadJsonP(LoggedIn) {
       loadScript(baseURL + "/CommonScripts/jquery.jsonp.js", function (){ LoadEmailValidator(LoggedIn)});
   }

   function LoadEmailValidator(LoggedIn) {
       loadScript(baseURL + "/CommonScripts/EmailValidator.js", function (){ LoadPopupJs(LoggedIn)});
   }

   function LoadPopupJs(LoggedIn) {
       loadScript(baseURL + "/CommonScripts/jquery.bpopup.js", function (){ LoadJson(LoggedIn)});
   }

   function LoadJson(LoggedIn) {
       loadScript(baseURL + "/CommonScripts/json2.js", function () { CreatePopup(LoggedIn) });
   }
   /* function AddScripts(LoggedIn) {
        loadCss([baseURL + "/CommonScripts/jquery.autocomplete.css", baseURL + "/CommonScripts/share.css"]);
        loadImages([baseURL + "/CommonScripts/images/popup_top.png", baseURL + "/CommonScripts/images/popup_middle.png", baseURL + "/CommonScripts/images/popup_bottom.png", baseURL + "/CommonScripts/images/close.png"]);
        loadScripts
        (
            [
                baseURL + "/CommonScripts/jquery.autocomplete.js",
                baseURL + "/CommonScripts/jquery.jsonp.js",
                baseURL + "/CommonScripts/EmailValidator.js",
                baseURL + "/CommonScripts/jquery.bpopup.js",
                baseURL + "/CommonScripts/json2.js"
            ]
           ,
            function () 
            {
                CreatePopup(LoggedIn);
            }
        );
    }*/


    function CreatePopup(LoggedIn) {

        IsLoggedIn = LoggedIn;

        mainUploadDiv = $(document.createElement('div')).addClass("sharewidget");
        mainUploadDiv.append($(document.createElement('div')).addClass("top"));

        var popupcenter = $(document.createElement('div')).addClass("center");
        var popupcontentarea = $(document.createElement('div')).addClass("popupcontentarea");

        popupcenter.append(popupcontentarea);

        var tmpHeading = $(document.createElement('div')).addClass("pageheading");

        popupcontentarea.append(tmpHeading);
        tmpHeading.append($(document.createElement('span')).text("Share"));
        Thanksbutton = $(document.createElement('input')).addClass("formsecondarybutton")
        closeLink = $(document.createElement('a')).html('<img src="' + baseURL + '/UploadHelper/images/cross.gif" border="0" alt="Close"/>').attr({ id: 'uploadClose' }).bind("click", CloseShare);
        tmpHeading.append(closeLink);

        popupContent = $(document.createElement('div')).addClass("popupContent");

        statusDiv = $(document.createElement('div')).addClass("popupContent").hide();

        popupcontentarea.append(popupContent);
        popupcontentarea.append(statusDiv);

        popupContent.append($(document.createElement('div')).addClass("errorbox").attr({ id: 'divError' }).hide());

        var divRow = $(document.createElement('div')).addClass("row");

        divRow.append($(document.createElement('span')).addClass("label").html("To:<span class='required'>*</span>"));

        recipientlistDiv = $(document.createElement('span')).addClass("textbox recipientlist").attr({ id: 'recipientlist' });
        var autoTextBox = $(document.createElement('input')).addClass("contenttextbox").attr({ id: 'txtRecipientName', type: 'text' });
        recipientlistDiv.append(autoTextBox);
        divRow.append(recipientlistDiv);

        popupContent.append(divRow);

        var divRow1 = $(document.createElement('div')).addClass("row");
        divRow1.append($(document.createElement('span')).addClass("label").html("Message:")).css("vertical-align", "top");
        divRow1.append($(document.createElement('span')).append($(document.createElement('textarea')).addClass("textbox textarea").attr({ id: 'txtMessage', rows: '2' })));
        popupContent.append(divRow1);
       
        shareImg = $(document.createElement('img')).attr({ id: 'imgShare'});
        shareTitle = $(document.createElement('span')).attr({ id: 'lblTitle' }).addClass("lblShareTitle lblShare");
        shareDescription = $(document.createElement('span')).attr({ id: 'lblDescription' }).addClass("lblShare");

        var divRow2 = $(document.createElement('div')).addClass("row");
        divRowText = $(document.createElement('div')).addClass("divText");
        divRowText.append(shareTitle);
        divRowText.append(shareDescription);
        shareImgDiv = $(document.createElement('div')).append(shareImg).addClass("imgShare");
        divRow2.append(shareImgDiv);
        divRow2.append(divRowText);

        popupContent.append(divRow2);

        if (!IsLoggedIn) {
            var divRowName = $(document.createElement('div')).addClass("row");
            divRowName.append($(document.createElement('span')).addClass("label").html("Your Name:<span class='required'>*</span>"));
            divRowName.append($(document.createElement('span')).append($(document.createElement('input')).addClass("textbox userinfotextbox").attr({ id: 'txtName', type: 'text' })));

            popupContent.append(divRowName);
            var divRowEmail = $(document.createElement('div')).addClass("row");
            divRowEmail.append($(document.createElement('span')).addClass("label").html("Your Email:<span class='required'>*</span>"));
            divRowEmail.append($(document.createElement('span')).append($(document.createElement('input')).addClass("textbox userinfotextbox").attr({ id: 'txtEmail', type: 'text' })));
            popupContent.append(divRowEmail);
        }



        buttonFooter = $(document.createElement('div')).addClass("formbuttonarea");

        Thanksbutton = $(document.createElement('input')).addClass("formsecondarybutton").attr({ id: 'btnClose', type: 'button', value: 'Close' }).bind("click", CloseShare);
        submitButton = $(document.createElement('input')).addClass("formbutton").attr({ id: 'btnSubmit', type: 'button', value: 'Send Message' }).bind("click", SubmitForm);
        buttonFooter.append(Thanksbutton);
        buttonFooter.append(submitButton);
        popupcontentarea.append(buttonFooter);
        mainUploadDiv.append(popupcenter);
        mainUploadDiv.append($(document.createElement('div')).addClass("bottom"));
        $(mainUploadDiv).hide();
        RegisterForAutoComplete(autoTextBox);
        RegisterDefaults(autoTextBox);
    }

    function RegisterForAutoComplete(objTextBox) {
        if (IsLoggedIn) {
            $(objTextBox).autocomplete(baseURL + "/InternalServices/SearchUserFriends.ashx",
            {
                dataType: 'jsonp',
                parse: function (data) {
                    var rows = new Array();
                    data = data.Result;
                    for (var i = 0; i < data.length; i++) {

                        rows[i] = { data: data[i], value: data[i].Name, result: data[i].Name };
                    }
                    return rows;
                },
                formatItem: function (row, i, n) {
                    return row.Name;
                },
                width: 150
            }
        );
        }

        $(objTextBox).keyup(function (event) { if (event.keyCode == 13) { AddCustomData(); } });

        $(objTextBox).result(function (event, data, formatted) 
            {
                addTextBoxData = false;
                AddRecipient(data, formatted);
                addTextBoxData = true;
            }
        );
    }

    function RegisterDefaults(objTextBox) {
        $('.sharewidget .item a').live('click', function () {
            var email = $(this).next().val();
            RemoveRecipient(email);
            $(this).parent().remove();
        }
        );
        $(objTextBox).focusout(function () {
            setTimeout(AddCustomData, 100);
        });

        $(objTextBox).keydown(function (event) {
            if (event.which == '8') {
                if ($(this).val().length == 0) {
                    var lastItem = $(".sharewidget .item:last");
                    if (lastItem.length > 0) {
                        var email = lastItem.find("input:hidden").val();
                        RemoveRecipient(email);
                        $(lastItem).remove();
                    }
                }
            }
        });
    }

    function AddCustomData() {
        if (addTextBoxData) {
            AddRecipient($('#txtRecipientName').val(), $('#txtRecipientName').val());
        }
    }

    function ClearAll() {
        $(".sharewidget .item").remove();
        recipientList = new Array();
    }

    function RemoveRecipient(Email) {
        var objNewList = new Array();
        var removeCtr = 0;
        for (removeCtr = 0; removeCtr < recipientList.length; removeCtr++) {
            var prop = recipientList[removeCtr];
            if (prop.Email != Email) {
                objNewList[objNewList.length] = recipientList[removeCtr];
            }
        }
        recipientList = objNewList;
        
        if (recipientList.length == 0) {
            $(recipientlistDiv).css("padding-bottom", "2px");
        }
    }

    function AddRecipient(TotalInfo, Name) {
        var objRecipient = CreateRecipient(TotalInfo);
        if (objRecipient != null) {
            recipientList[recipientList.length] = objRecipient;
            var newItem = $(document.createElement('span')).addClass("item").html(Name + "<a class='close'></a><input type='hidden' value='" + objRecipient.Email + "' />");
            $("#txtRecipientName").before(newItem);
        }
        if (recipientList.length == 1) {
            $(recipientlistDiv).css("padding-bottom", "0px");
        }
        
        $("#txtRecipientName").val("");
    }

    function IsEmailAdded(EmailID) {
        var FriendCtr = 0;
        for (FriendCtr = 0; FriendCtr < recipientList.length; FriendCtr++) {
            if (recipientList[FriendCtr].Email == EmailID)
                return true;
        }
        return false;
    }

    function isArray(obj) {
        if (obj == undefined)
            return false;
        if (obj.constructor == undefined)
            return false;

        return (obj.constructor.toString().indexOf("Array") != -1);
    }

    function CreateRecipient(TotalInfo) {
        var objRecipient = new ShareRecipientData();
        if (jQuery.isPlainObject(TotalInfo)) {
            objRecipient  = TotalInfo;
        }
        else {
            objRecipient.Name = TotalInfo;
            objRecipient.Email = TotalInfo;
            objRecipient.UserID = -1;
        }
        if (checkEmailAddress(objRecipient.Email).isValid) {
            if (!IsEmailAdded(objRecipient.Email))
                return objRecipient;
            else
                return null;
        }
        else
            return null;
    }

    function ValidateForm() {
        $("#divError").empty();
        var errorMessages = new Array();

        if (recipientList.length == 0) {
            var msg = "Please enter atleast one receipient";
            errorMessages[errorMessages.length] = msg;
        }

        if (SharedURL == '') {
            var msg = "No url supplied for sharing";
            errorMessages[errorMessages.length] = msg;
        }

        if (ItemID == -1) {
            var msg = "No item found for sharing";
            errorMessages[errorMessages.length] = msg;
        }

        if (ItemType == -1) {
            var msg = "No item type found for sharing";
            errorMessages[errorMessages.length] = msg;
        }

        if (!IsLoggedIn) {
            var txtName = $("#txtName").val();
            var txtEmail = $("#txtEmail").val();

            if (txtName.length == 0) {
                var msg = "Please enter your name";
                errorMessages[errorMessages.length] = msg;
            }
            else if (txtName.length > 50) {
                var msg = "Name cannot exceed 50 characters";
                errorMessages[errorMessages.length] = msg;
            }
            if (txtEmail.length == 0) {
                var msg = "Please enter your email address";
                errorMessages[errorMessages.length] = msg;
            }
            else if (txtEmail.length > 50) {
                var msg = "Email address cannot exceed 50 characters";
                errorMessages[errorMessages.length] = msg;
            }
            else {
                var emailVerify = checkEmailAddress(txtEmail);
                if (!emailVerify.isValid) {
                    errorMessages[errorMessages.length] = emailVerify.ErrorMessage;
                }
            }
        }
        var errorCtr = 0;
        if (errorMessages.length > 0) {
            $("#divError").append($(document.createElement('span')).addClass("errortitle").text("Some information seems to be missing or incorrect."));
            $("#divError").show();
            for (errorCtr = 0; errorCtr < errorMessages.length; errorCtr++)
                $("#divError").append($(document.createElement('span')).addClass("error").text(errorMessages[errorCtr]));
            return false;
        }
        else {
            $("#divError").hide();
            return true;
        }
    }

    function ToggleForm(Mode) {
        // 1- Before Post
        // 2 - After
        // 3 - Error From call
        if (Mode == 1) {
            $(statusDiv).empty();
            $(popupContent).hide();
            $(buttonFooter).hide();
            $(closeLink).hide();
            $(statusDiv).append($(document.createElement('span')).addClass("staticmessage").html('Processing'));
            $(statusDiv).show();
        }
        if (Mode == 2) {
            $(statusDiv).show();
            $(statusDiv).empty();
            $(statusDiv).append($(document.createElement('span')).addClass("staticmessage").text("Your message has been sent."));
            $(buttonFooter).show();
            $(submitButton).hide();
            $(closeLink).show();
        }
        if (Mode == 3) {
            $(closeLink).show();
            $(statusDiv).show();
            $(buttonFooter).show();
            $(submitButton).hide();
        }
    }

    function PostForm() {
        ToggleForm(1);
        var requestbody = JSON.stringify(recipientList);
        var url = baseURL + "/InternalServices/Share.ashx?Message=" + encodeURIComponent($('#txtMessage').val()) + "&Recipients=" + requestbody + "&ItemID=" + ItemID + "&SiteID=" + SiteID + "&ItemType=" + ItemType + "&UserID=" + UserID + "&SharedURL=" + SharedURL;
        if (!IsLoggedIn)
            url = url + "&SenderName=" + encodeURIComponent($('#txtName').val()) + "&SenderEmailAddress=" + encodeURIComponent($('#txtEmail').val());

        $.jsonp({
            "url": url + "&callback=?",
            "success": function (response, textStatus) {
                ToggleForm(2);
            },
            "error": function (xOptions, textStatus) {
                $(statusDiv).empty();
                $(statusDiv).append($(document.createElement('span')).addClass("staticmessage").text(textStatus));
                ToggleForm(3);
            }
        });
    }

    function SubmitForm(e) {
        if (!ValidateForm())
            return false;
        PostForm();
    }

    function ShowShare(ImageURL, Title, Description, nItemID, nSiteID, nItemType, nUserID, nSharedURL) {
        ClearAll();
        $("#divError").empty();
        $("#divError").hide();

        if (ImageURL == '') {
            $(shareImgDiv).hide();
            $(divRowText).removeClass("divText").addClass("divTextWithoutImage");
        }
		else {
            $(shareImgDiv).show();
            $(divRowText).removeClass("divTextWithoutImage").addClass("divText");
        }
        $(shareImg).attr("src", ImageURL);
        $(shareDescription).text(Description);
        $(shareTitle).text(Title);

        ItemID = nItemID;
        SiteID = nSiteID;
        ItemType = nItemType;
        UserID = nUserID;
        SharedURL = nSharedURL;

        $(popupContent).show();
        $(submitButton).show();
        $(statusDiv).hide();
        $(mainUploadDiv).bPopup({ opacity: 0.2, modalClose: false, fadeSpeed: 'slow' });
        centerPopup();
    }

    function CloseShare() {
        $(mainUploadDiv).bPopup().close();
    }

    function centerPopup() {
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $(mainUploadDiv).height();
        var popupWidth = $(mainUploadDiv).width();

        var LeftPosition = (windowWidth) ? (windowWidth - popupWidth) / 2 : 0;
        var TopPosition = (windowHeight) ? (windowHeight - popupHeight) / 2 : 0;

        $(mainUploadDiv).css({
            "position": "absolute",
            "top": TopPosition,
            "left": LeftPosition
        });
    }
}

function ShareRecipientData() {
    this.Name = "";
    this.Email = "";
    this.UserID = "";
}


var objShare = new Share();


function OpenShare(ImageURL, Title, Description, ItemID, SiteID, ItemType, UserID, SharedURL) {
    objShare.Show(ImageURL, Title, Description, ItemID, SiteID, ItemType, UserID, SharedURL);
}

function CloseShare() {
    objShare.Close();
}

$(document).ready(function () {
    loadScripts(["http://www.copperstrings.com/CommonScripts/ShareInit.aspx"],null);
});

