﻿var productId = 0;
         
    // handles the login from the add to MyProjects tool tip
    function loginTT()
    {
        var username = $get('txtUsernameTT').value;
        var password = $get('txtPasswordTT').value;
        var userBox = $get('txtUsernameTT');
        var pwdBox = $get('txtPasswordTT');
        var valUser = $get('valUsernameTT');
        var valPassword = $get('valPwdTT');
        var errorRow = $get('loginErrRowTT');
        var errorMsg = $get('loginErrTT');
        
        // ttlogin is passed to the userContext to allow the add to MyProject control display after login
        login(username, userBox, password, pwdBox, valUser, valPassword, errorRow, errorMsg, '', 'ttlogin');

        return false;
    }
    
    function loginSmall()
    { 
        var username = $get('txtUsernameSm').value;
        var password = $get('txtPasswordSm').value;
        var userBox = $get('txtUsernameSm');
        var pwdBox = $get('txtPasswordSm');
        var valUser = $get('valUsernameSm');
        var valPassword = $get('valPwdSm');
        var errorRow = $get('loginErrRowSm');
        var errorMsg = $get('loginErrSm');
        
        // ttlogin is passed to the userContext to allow the add to MyProject control display after login
        login(username, userBox, password, pwdBox, valUser, valPassword, errorRow, errorMsg, '', 'smlogin');

        return false;
    }
    
     
        function falied(result)
        {
            var btn = $get('addToProject');
            if (btn != null)
            {
            btn.value = 'Add to MyProjects';
            btn.disabled = false;
            }
            var msg = String.format('ERROR :: \r\n' + result.get_message());
            alert(msg);
        }
        


        // Opens the add to MyProjects tool tip
        function openAddtoProject(id)
        {
            productId = 0;
            
            if (!isNaN(id))
            {
                 productId = id;
                
                // Show the modal add to my project window
                ShowToolTip();
                
                // determine if the user is authenticated
                myProjectsAuth();
            }
            else
            {
                // The project id supplied is not a valid number
                alert('An error has occured. \n\nThe product id is invalid.');
            }
        }

        function openAddExternaltoProject(id) {
            productId = 0;
            if (!isNaN(id)) {
                productId = id;
                // show the modal add to my project window
                showExternalTT();
                // The user is logged in
                $get('ttAddProduct').style.display = 'block';
                
                // Get the product image id and display the product image
                Productspec.Services.MyProjectsService.GetExtProductImgId(productId, getExtImageSuccess, falied, '');

                // Get the available projects for the user
                Productspec.Services.MyProjectsService.GetProjects(getAvailProjectsSuccess, falied, '');

                // Get the available categories for the product
                Productspec.Services.MyProjectsService.GetExternalCategories(productId, getExtCategoriesSuccess, falied, ''); 
            }
        }

        function getExtCategoriesSuccess(result, context) {
            if (result != null) {
                // Clear any old items from the categoris drop down list
                $get('categories').options.length = 0;

                for (var i = 0; i < result.length; i++) {
                    AddToCategoryList(result[i].Name, result[i].Id);
                }
            }
        }

        function getExtImageSuccess(result, context) {
            if (result != null) {
                if (result > 0) {
                    $get("productImage").style.display = 'inline';
                    $get("productImage").innerHTML = '<img src="http://www.productspec.net/images.ashx?epid=' + result + '" alt="" />'
                }
                else {
                    $get("productImage").style.display = 'none';
                }
            }
        }
        
        // Determines which view to display on the add to MyProjects tool tip
        // if the user is authenticated then show the add to my project control
        // else show the login screen
        function myProjectsAuth()
        {
            // Get the projects header
            var ttHeader = $get("ttProjectsHeader");
            
            if (isAuth())
                {
                    // The user is logged in    
                    $get('ttAddProduct').style.display = 'block';
                    $get('ttLogin').style.display = 'none';                  
                    
                    
                    
                    // show the product and project information
                    displayAddtoMyProjects(); 
                }
                else
                {
                    // The user is not logged in
                    $get('ttAddProduct').style.display = 'none';
                    $get('ttLogin').style.display = 'block';
                    
                    // Set the header for the tool tip
                    //ttHeader.innerHTML = 'Please Sign-In';
                    ttHeader.style.display = 'none';
                }
        }
        
        // display the add to my projects control
        // showing the available projects to the user
        // and the categories available to this product
        function displayAddtoMyProjects()
        {
           if (!isNaN(productId))
           {
              // Get and set the product title for the add to MyProject control
              Productspec.Services.MyProjectsService.GetProductTitle(productId, getTitleSuccess, falied, '');

              // Get the product image id and display the product image
              Productspec.Services.MyProjectsService.GetProductImageMainId(productId, getProductImageSuccess, falied, '');
              
              // Get the available projects for the user
              Productspec.Services.MyProjectsService.GetProjects(getAvailProjectsSuccess, falied, '');
              
              // Get the available categories for the product
              Productspec.Services.MyProjectsService.GetAvailCategories(productId, getAvailableCategoriesSuccess, falied, '');         
              
           }
           else
           {
                // the product id is not valid
              
           }
       }

       // Gets the properties that are associated with this product
       // i.e. Floor Levels, Space Names
       function getProjectProperties() {
           var projectId = $get("projects").value;
           if (!isNaN(projectId)) {
               if (projectId > 0) {
                   // Get the available floor levels for this project
                   Productspec.Services.MyProjectsService.GetFloorsByProject(projectId, getFloorsSuccess, falied, '');
                   // Get the available space names for this project
                   Productspec.Services.MyProjectsService.GetSpaceNamesByProject(projectId, getSpaceNameSuccess, falied, '');
               }
               else {
                   $get('divFloor').style.display = 'none';
                   $get('divSpace').style.display = 'none';
               }
           }

       }

       // Displays the floor levels returned
       // as checkboxes
       function getFloorsSuccess(result, userContext) {
           if (result != null) {
               if (result.length > 0) {
                   // Loop through the floor types and display them
                   var r = Math.ceil(result.length / 2);
                   var divLt = $get('divChkFloorLt');
                   var divRt = $get('divChkFloorRt');
                   var divCont = $get('divFloor');
                   var txtLt = '';
                   var txtRt = '';
                   var x = 1;
                   for (i = 0; i < result.length; i++) {
                       if (x <= r) {
                           txtLt = txtLt + '<div><input type="checkbox" name="chk_floor" value="' + result[i].Id + '" fname="' + result[i].FloorLevel + '">' + result[i].FloorLevel + '</div>';
                       }
                       else {
                           txtRt = txtRt + '<div><input type="checkbox" name="chk_floor" value="' + result[i].Id + '" fname="' + result[i].FloorLevel + '">' + result[i].FloorLevel + '</div>';
                       }
                       x = x + 1;
                   }
                 
                   divCont.style.display = 'block';
                   divLt.innerHTML = txtLt;
                   divRt.innerHTML = txtRt;
               }
           }
       }

       // Displays the returned space names availble for a project
       // as checkboxes
       function getSpaceNameSuccess(result, userContext) {
           if (result != null && result.length > 0) {
               // Loop through the space names and display them
               var r = Math.ceil(result.length / 2);
               var divLt = $get('divChkSpaceNameLt');
               var divRt = $get('divChkSpaceNameRt');
               var divCont = $get('divSpace');
               var txtLt = '';
               var txtRt = '';
               var x = 1;
               for (i = 0; i < result.length; i++) {
                   if (x <= r) {
                       txtLt = txtLt + '<div><input type="checkbox" name="chk_space" value="' + result[i].Id + '" fname="' + result[i].SpaceName + '">' + result[i].SpaceName + '</div>';
                   }
                   else {
                       txtRt = txtRt + '<div><input type="checkbox" name="chk_space" value="' + result[i].Id + '" fname="' + result[i].SpaceName + '">' + result[i].SpaceName + '</div>';
                   }
                   x = x + 1;
               }

               divCont.style.display = 'block';
               divLt.innerHTML = txtLt;
               divRt.innerHTML = txtRt;
           }
       }
        
        
        // returns the product title from the callback
        function getTitleSuccess(result, userContext)
        {
             if (result != null)
             {
                // set the title of the product on the add to MyProject control
                $get("addProductTitle").innerHTML = result;
             }
             else
             {
                // show error as the product title
                 $get("addProductTitle").innerHTML = 'ERROR';  
             }
        }
        
        //  Returns the image url for the product from the callback
        function getProductImageSuccess(result, userContext)
        {
           if (result != null)
           {
            // show the image of the product
              $get("productImage").innerHTML =  '<img src="' + result + '" alt="" />';
           }
           else
           { 
                // no image to display
                
           }
        }
         
         // returns the available projects for the current user
         // json format
        function getAvailProjectsSuccess(result, userContext)
        {
            if (result != null)
            {
                eval("var objResults =" + result);
                // clear all options from the project list drop down
                $get('projects').options.length = 0;
                AddToProjectList('Select Project', 0);
                for (var i = 0; i < objResults.Results.project.length; i++)
                {
                    AddToProjectList(objResults.Results.project[i].ProjectName, objResults.Results.project[i].ProjectId);
                }
            }
        }
        
        // returns the availabe categories for the 
        // product selected
        function getAvailableCategoriesSuccess(result, userContext)
        {
             if (result != null)
             {
                 eval("var objResults =" + result);

                // Clear any old items from the categoris drop down list
                $get('categories').options.length = 0;

                for (var i = 0; i < objResults.Results.category.length; i++) {
                    AddToCategoryList(objResults.Results.category[i].CatName, objResults.Results.category[i].CatId);
                }
             }
             else
             {
                 // result is null
                 HideActiveToolTip();
                 alert('The product does not belong to a secondary category.\nThis product cannot be added to MyProjects at this time.');
             }
        }
        
        // adds an option with a name and value
        // to the project select control
        function AddToProjectList(text, value) {
            var opt = document.createElement("option");

            $get('projects').options.add(opt);
            opt.text = text;
            opt.value = value;
        }

        // adds an option with a name and value 
        // to the category select control
        function AddToCategoryList(text, value) {
            var opt = document.createElement("option");
            $get('categories').options.add(opt);
            opt.text = text;
            opt.value = value;
        }
        
        // handles the click event for adding a product
        // to a project and category from within the add to MyProject control        
        function addToMyProjectNew()
        {
             // check the product id
            if (!isNaN(productId))
            {
               var projectId = $get("projects").value;
               var categoryId = $get("categories").value;
               var note = $get("txtNote").value;

               if (projectId > 0) {
                   // Disable the submit button
                   // show saving text on the button
                   var btn = $get("addToProject");
                   btn.disabled = true;
                   btn.value = 'Saving...';

                   // Find the values for space name check boxes
                   chkS = document.forms[0].chk_space;
                   var spaceUn = new Array();
                   var spaces = new Array();
                   var x = 0;
                   var y = 0;
                   for (i = 0; i < chkS.length; i++) {
                       if (chkS[i].checked) {
                           if (chkS[i].value == 0) {
                               // value equals zero
                               // this value does not exist yet for this project
                               // Add the name of the space to the Array
                               spaceUn[x] = chkS[i].getAttribute('fname');
                               x = x + 1;
                           }
                           else {
                               // This is a known space name for this project
                               // Add this id to the known names array                                
                               spaces[y] = chkS[i].value;
                               y = y + 1;
                           }
                       }
                   }

                  var otherSpace = $get('txtSpaceName');
                   if (otherSpace.value != '') {
                       spaceUn[x] = otherSpace.value;
                   }

                   // Find the values for floor levels
                   chkF = document.forms[0].chk_floor;
                   var floorUn = new Array();
                   var floors = new Array();
                   var a = 0;
                   var b = 0;
                   for (i = 0; i < chkF.length; i++) {
                       if (chkF[i].checked) {
                           if (chkF[i].value == 0) {
                               //  This is an unknown value
                               // Add this name to the unkown floor levels array                           
                               floorUn[a] = chkF[i].getAttribute('fname');
                               a = a + 1;
                           }
                           else {
                               //This is a known floor level for this project
                               // Add this id to the known floor names array
                               floors[b] = chkF[i].value;
                               b = b + 1;
                           }
                       }
                   }
                   
                   var otherFloor = $get('txtFloorLevel');                   
                   if (otherFloor.value != '') {
                       floorUn[a] = otherFloor.value;
                   }


                   Productspec.Services.MyProjectsService.AddToProjectNew(productId, projectId, categoryId, floors, floorUn, spaces, spaceUn, note, addToMyProjectSuccess, falied, '');

               }
               else {
                   alert('Please select a project to add this project to.\r\nIf you do not have a project please go to MyProjects to set one up.');
               }
               
            }
            else
            {   
                // the product id is not valid
                alert('Can not add this product to the selected project.  \r\nThe Product Id is invalid');
            }
        }

        // handles the click event for adding a product
        // to a project and category from within the add to MyProject control        
        function addToMyProjectExternal() {
            // check the product id
            if (!isNaN(productId)) {
                var projectId = $get("projects").value;
                var categoryId = $get("categories").value;
                var note = $get("txtNote").value;

                if (projectId > 0) {
                    // Disable the submit button
                    // show saving text on the button
                    var btn = $get("addToProject");
                    btn.disabled = true;
                    btn.value = 'Saving...';

                    // Find the values for space name check boxes
                    chkS = document.forms[0].chk_space;
                    var spaceUn = new Array();
                    var spaces = new Array();
                    var x = 0;
                    var y = 0;
                    for (i = 0; i < chkS.length; i++) {
                        if (chkS[i].checked) {
                            if (chkS[i].value == 0) {
                                // value equals zero
                                // this value does not exist yet for this project
                                // Add the name of the space to the Array
                                spaceUn[x] = chkS[i].getAttribute('fname');
                                x = x + 1;
                            }
                            else {
                                // This is a known space name for this project
                                // Add this id to the known names array                                
                                spaces[y] = chkS[i].value;
                                y = y + 1;
                            }
                        }
                    }

                    var otherSpace = $get('txtSpaceName');
                    if (otherSpace.value != '') {
                        spaceUn[x] = otherSpace.value;
                    }

                    // Find the values for floor levels
                    chkF = document.forms[0].chk_floor;
                    var floorUn = new Array();
                    var floors = new Array();
                    var a = 0;
                    var b = 0;
                    for (i = 0; i < chkF.length; i++) {
                        if (chkF[i].checked) {
                            if (chkF[i].value == 0) {
                                //  This is an unknown value
                                // Add this name to the unkown floor levels array                           
                                floorUn[a] = chkF[i].getAttribute('fname');
                                a = a + 1;
                            }
                            else {
                                //This is a known floor level for this project
                                // Add this id to the known floor names array
                                floors[b] = chkF[i].value;
                                b = b + 1;
                            }
                        }
                    }

                    var otherFloor = $get('txtFloorLevel');
                    if (otherFloor.value != '') {
                        floorUn[a] = otherFloor.value;
                    }


                    Productspec.Services.MyProjectsService.AddToProjectExternal(productId, projectId, categoryId, floors, floorUn, spaces, spaceUn, note, addToMyProjectSuccess, falied, '');

                }
                else {
                    alert('Please select a project to add this project to.\r\nIf you do not have a project please go to MyProjects to set one up.');
                }

            }
            else {
                // the product id is not valid
                alert('Can not add this product to the selected project.  \r\nThe Product Id is invalid');
            }
        }
        
        // handles the add to MyProject callback success event
        function addToMyProjectSuccess(result, userContext)
        {
            if (result != null)
            {
                alert(result);

                $get("txtNote").value = '';
                $get('txtSpaceName').value = '';
                $get('txtFloorLevel').value = '';
                $get('divChkSpaceNameLt').innerHTML = '';
                $get('divChkSpaceNameRt').innerHTML = '';
                $get('divSpace').style.display = 'none';
                $get('divChkFloorLt').innerHTML = '';
                $get('divChkFloorRt').innerHTML = '';
                $get('divFloor').style.display = 'none';

                // Enable the Submit Button
                // Change back the button text
                var btn = $get('addToProject');
                btn.value = 'Add to MyProjects';
                btn.disabled = false;
                
                HideActiveToolTip();
            }
            else
            {
             // result is null
            }
        }
        
        
   
   // Hides the active tool tip
        function HideActiveToolTip() {
            var tooltip = GetActiveToolTip();
            tooltip.hide();
        }
        function GetActiveToolTip() {
            var controller = Telerik.Web.UI.RadToolTipController.getInstance();
            var tooltip = controller.get_activeToolTip();
            return tooltip;
        }