<%@ Page Title="New Contact" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="new-contact.aspx.cs" Inherits="NewContact" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link rel="stylesheet" href="Styles/newContact.css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FolderContent" runat="Server">
    <nav:FolderNavigationControl runat="server" ID="FolderNavigationControl" Category="Contacts" />
    <nav:MobileNavigation runat="server" ID="MobileNavigation" Category="Contacts" BreadCrumbText="Groups"></nav:MobileNavigation>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="Server">

    <telerik:RadNavigation ID="RadNavigation1" runat="server" CssClass="secondaryMenu" Skin="BlackMetroTouch" OnClientNodeClicked="nodeClicked">
        <Nodes>
            <telerik:NavigationNode Text="New" NavigateUrl="new-contact.aspx" SpriteCssClass="icon icon-Add-Circle"></telerik:NavigationNode>
        </Nodes>
    </telerik:RadNavigation>

    <div class="content">
        <h3>Add new contact</h3>
        <div class="inputs">
            <div class="row">
                <label>Folder</label>
                <telerik:RadDropDownList runat="server"
                    ID="rddlContactsFolders"
                    OnClientItemsRequested="clientItemsRequested"
                    DefaultMessage="Choose Contact's Category"
                    ClientDataSourceID="rcdsContactsFolders"
                    DataTextField="Name" DataValueField="Id">
                </telerik:RadDropDownList>
                <telerik:RadClientDataSource runat="server" ID="rcdsContactsFolders">
                    <DataSource>
                        <WebServiceDataSourceSettings BaseUrl="api/">
                            <Select RequestType="Get" Url="folders/contacts" DataType="JSON" />
                        </WebServiceDataSourceSettings>
                    </DataSource>
                </telerik:RadClientDataSource>
            </div>
            <div class="row">
                <label>Title</label>
                <telerik:RadTextBox runat="server" ID="rtbContactTitle"></telerik:RadTextBox>
            </div>
            <div class="row">
                <label>Name</label>
                <telerik:RadTextBox runat="server" ID="rtbContactName">
                    <ClientEvents OnBlur="contactNameBlur" />
                </telerik:RadTextBox>
            </div>
            <div class="row">
                <label>Company</label>
                <telerik:RadTextBox runat="server" ID="rtbCompany"></telerik:RadTextBox>
            </div>
            <div class="row">
                <label>City</label>
                <telerik:RadTextBox runat="server" ID="rtbCity"></telerik:RadTextBox>
            </div>
            <div class="row">
                <label>Country</label>
                <telerik:RadTextBox runat="server" ID="rtbCountry"></telerik:RadTextBox>
            </div>
            <div class="row">
                <label>Phone</label>
                <telerik:RadTextBox runat="server" ID="rtbPhone"></telerik:RadTextBox>
            </div>
            <div class="row">
                <label>Email</label>
                <telerik:RadTextBox runat="server" ID="rtbEmail"></telerik:RadTextBox>
            </div>
            <div class="footer">
                <telerik:RadButton runat="server" Text="Save" AutoPostBack="false" OnClientClicked="saveContactClicked" />
                <telerik:RadButton runat="server" Text="Cancel" AutoPostBack="false" OnClientClicked="cancelContactClicked" />
            </div>
        </div>
        <div class="photo">
            <img src="Images/contacts/no-photo.png" alt="contact photo" width="100" height="100" />
            <telerik:RadAsyncUpload runat="server" ID="rtbContactPhoto" MaxFileInputsCount="1" OnClientFileSelected="fileSelected"
                OnClientFileUploading="fileUploading" AllowedFileExtensions=".jpg,.png" HttpHandlerUrl="~/Handlers/ContactsUploadHandler.ashx">
            </telerik:RadAsyncUpload>
        </div>
    </div>

    <script>
        var contactId = null;
        var imageName = null;

        function nodeClicked(sender, args) {
            var command = args.get_node().get_text();

            switch (command) {
                case "Save":
                    saveContact();
                    break;
                default:
            }
        }

        function clientItemsRequested(sender, args) {
            if (sender.getItem(0) != null) {
                sender.getItem(0).select();
            }
        }

        function fileSelected(sender, args) {
            var file = args.get_fileInputField().files.item(args.get_rowIndex());
            if (file) {
                showThumbnail(file);
            }
        }

        function showThumbnail(file) {
            var image = $('.photo img')[0];
            image.file = file;

            var reader = new FileReader()
            reader.onload = (function (aImg) {
                return function (e) {
                    aImg.src = e.target.result;
                };
            }(image))
            var ret = reader.readAsDataURL(file);
            var canvas = document.createElement("canvas");

            ctx = canvas.getContext("2d");
            image.onload = function () {
                ctx.drawImage(image, 100, 100);
            }
        }

        function fileUploading(sender, args) {
            contactId = generateId();
            var fileExtention = args.get_fileName().substring(args.get_fileName().lastIndexOf('.'), args.get_fileName().length);
            imageName = contactId + fileExtention;

            args.set_queryStringParams({ contactID: contactId });
        }

        function cancelContactClicked(sender, args) {
            window.location.href = 'contacts.aspx';
        }

        function saveContactClicked(sender, args) {
            saveContact();
        }

        function saveContact() {
            var ddl = $find("<%= rddlContactsFolders.ClientID %>").get_selectedItem();

            var contact = {
                Id: contactId != null ? contactId : generateId(),
                Name: $find("<%= rtbContactName.ClientID %>").get_value(),
                Title: $find("<%= rtbContactTitle.ClientID %>").get_value(),
                Country: $find("<%= rtbCountry.ClientID %>").get_value(),
                City: $find("<%= rtbCity.ClientID %>").get_value(),
                Company: $find("<%= rtbCompany.ClientID %>").get_value(),
                Phone: $find("<%= rtbPhone.ClientID %>").get_value(),
                Email: $find("<%= rtbEmail.ClientID %>").get_value(),
                ImageUrl: imageName !== null ? imageName : "no-photo.png",
                FolderId: ddl !== null ? ddl.get_value() : 11
            };

            $(".error").remove();
            if (contact.Name === "") {
                var name = $find("ctl00_MainContent_rtbContactName");
                $(name.get_element()).parent().after("<span class='error'> * Name is required!</span>")
                name.focus();
            } else {
                $.ajax({
                    type: "POST",
                    data: JSON.stringify(contact),
                    url: "api/contacts/",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        window.location.href = "contacts.aspx";
                    }
                });
            }
        }

        function contactNameBlur(sender, args) {
            if (sender.get_element().value !== "") {
                $(".error").remove();
            }
        }

        function generateId() {
            var text = "";
            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            for (var i = 0; i < 5; i++)
                text += possible.charAt(Math.floor(Math.random() * possible.length));

            return text;
        }
    </script>

</asp:Content>