Sunday, May 7, 2017

Callouts popups example in SharePoint 2013 in Javascript



<script type="text/javascript" src="/_layouts/15/callout.js"></script>

<script type="text/javascript">

//This functions makes the request to the RESTful ListData service
function getListItems() {

var Url = "https://SPSite/_vti_bin/ListData.svc/Announcements";

//Create a WebRequest object
var request = new Sys.Net.WebRequest();

//Specify the verb
request.set_httpVerb("GET");


//Use the URL we already formulated
request.set_url(Url);


//Set the Accept header to ensure we get a JSON response
request.get_headers()["Accept"] = "application/json";


//Add a callback function that will execute when the request is completed
request.add_completed(onCompletedCallback);


//Run the web requests
request.invoke();

}

function onCompletedCallback(response, eventArgs) {

//Parse the JSON reponse into a set of objects by using the JavaScript eval() function

var announcements = eval("(" + response.get_responseData() + ")");

var newAnnouncement = document.createElement("div"); 

for (var i = 0; i < announcements.d.results.length; i++) {

//Display some properties
_announTitle = announcements.d.results[i].Title;
_announID = announcements.d.results[i].Id;
_announBody = announcements.d.results[i].Body;

announcementsList.appendChild(newAnnouncement); 

var calloutLink = document.createElement("div"); 
            calloutLink.id = _announID; 
            calloutLink.onmouseover = function () { 
                curListUrl = this.id; 
            } 

calloutLink.innerHTML = "<div class=\"ms-commandLink\" style=\"text-align: left;font-size: 14px;\"><b>" + _announTitle + "</b><br/><br/></div>"; 

announcementsList.appendChild(calloutLink); 

var listCallout = CalloutManager.createNew({ 
                launchPoint: calloutLink,
                beakOrientation: "leftRight", 
                ID: _announID, 
                title: _announTitle, 
                content: "<div class=\"ms-soften\" style=\"margin-top:13px;\">" 
                        + "<hr/></div>" 
                        + "<div class=\"callout-section\" style=\"margin-top:13px;\">" + _announBody + "</div>", 
            }); 

}

}


</script>

<div id="announcementsList"></div>
<a href="Javascript:getListItems()">Click Here to Display Announcements</a>

Friday, February 3, 2017

Rest Syntax for filtering Listitems from SharePoint 2013

Get all tasks assigned to me:
----------------------------------

/_api/web/lists/getbytitle('Development Tasks')/items?$expand=AssignedTo&amp;$select=Title,AssignedTo/Title&amp;$filter=AssignedTo/Title eq 'Anderson, Marc'


Get all tasks that have not been completed, showing the status and the % complete:
-----------------------------------------------------------------------------------------------------

/_api/web/lists/getbytitle('Development Tasks')/items?$expand=AssignedTo&amp;$select=Title,AssignedTo/Title,Status,PercentComplete&amp;$filter=Status ne 'Completed'


Source:
========
https://msdn.microsoft.com/en-us/library/gg309461.aspx

http://sympmarc.com/2016/09/07/retrieving-the-content-type-in-a-rest-call-in-sharepoint-2013-on-premises/


REST Call Syntax
----------------------------











Monday, January 23, 2017

Paging in JSOM in SharePoint

Sample one (Basic Paging)

This code sample request a list in chunks of 4 items, then the items are written on the page inside html table as the following image & code:


JavaScript
var context, 
    web, 
    spItems, 
    position, 
    nextPagingInfo, 
    previousPagingInfo, 
    listName = 'ContactsList', 
    pageIndex = 1// default page index value 
    pageSize = 4// default page size value 
    list, 
    camlQuery; 
 
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model  
$(document).ready(function () { 
    context = SP.ClientContext.get_current(); 
    list = context.get_web().get_lists().getByTitle(listName); 
    camlQuery = new SP.CamlQuery(); 
 
    $("#btnNext").click(function () { 
        pageIndex = pageIndex + 1; 
        if (nextPagingInfo) { 
            position = new SP.ListItemCollectionPosition(); 
            position.set_pagingInfo(nextPagingInfo); 
        } 
        else { 
            position = null; 
        } 
 
        GetListItems(); 
    }); 
 
    $("#btnBack").click(function () { 
        pageIndex = pageIndex - 1; 
        position = new SP.ListItemCollectionPosition(); 
        position.set_pagingInfo(previousPagingInfo); 
        GetListItems(); 
    }); 
 
    GetListItems(); 
}); 
 
function GetListItems() { 
    //Set the next or back list items collection position 
    //First time the position will be null 
    camlQuery.set_listItemCollectionPosition(position); 
 
    // Create a CAML view that retrieves all contacts items  with assigne RowLimit value to the query 
    camlQuery.set_viewXml("<View>" + 
                              "<ViewFields>" + 
                                     "<FieldRef Name='FirstName'/>" + 
                                     "<FieldRef Name='Title'/>" + 
                                     "<FieldRef Name='Company'/>" + 
                                "</ViewFields>" + 
                             "<RowLimit>" + pageSize + "</RowLimit></View>"); 
 
    spItems = list.getItems(camlQuery); 
 
    context.load(spItems); 
    context.executeQueryAsync( 
            Function.createDelegate(this, onSuccess), 
            Function.createDelegate(this, onFail) 
        ); 
} 
 
// This function is executed if the above OM call is successful 
// This function render the returns items to html table 
function onSuccess() { 
 
    var listEnumerator = spItems.getEnumerator(); 
    var items = []; 
    var item; 
 
    while (listEnumerator.moveNext()) { 
        item = listEnumerator.get_current(); 
        items.push("<td>" + item.get_item('FirstName') + "</td><td>" + item.get_item('Title') + "</td><td>" + item.get_item('Company') + "</td>"); 
    } 
 
    var content = "<table><tr><th>First Name</th><th>Last Name</th><th>Company</th></tr><tr>" 
                + items.join("</tr><tr>") + "</tr></table>"; 
    $('#content').html(content); 
 
    managePagerControl(); 
} 
 
function managePagerControl() { 
 
    if (spItems.get_listItemCollectionPosition()) { 
        nextPagingInfo = spItems.get_listItemCollectionPosition().get_pagingInfo(); 
    } else { 
        nextPagingInfo = null; 
    } 
 
    //The following code line shall add page information between the next and back buttons 
    $("#pageInfo").html((((pageIndex - 1) * pageSize) + 1) + " - " + ((pageIndex * pageSize) - (pageSize - spItems.get_count()))); 
 
    previousPagingInfo = "PagedPrev=TRUE&Paged=TRUE&p_ID=" + spItems.itemAt(0).get_item('ID'); 
 
    if (pageIndex <= 1{ 
        $("#btnBack").attr('disabled''disabled'); 
    } 
    else { 
        $("#btnBack").removeAttr('disabled'); 
    } 
 
    if (nextPagingInfo) { 
        $("#btnNext").removeAttr('disabled'); 
    } 
    else { 
        $("#btnNext").attr('disabled''disabled'); 
    } 
 
}

Sample two (Paging with CAML Sorting)



JavaScript
var context, 
    web, 
    spItems, 
    position, 
    nextPagingInfo, 
    previousPagingInfo, 
    listName = 'ContactsList', 
    pageIndex = 1// default page index value 
    pageSize = 4// default page size value 
    list, 
    camlQuery, 
    sortColumn = 'FirstName'// this is sort column, you can add more than one column, but you should add it also to CAML Query & managePagerControl function 
 
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model  
$(document).ready(function () { 
    context = SP.ClientContext.get_current(); 
    list = context.get_web().get_lists().getByTitle(listName); 
    camlQuery = new SP.CamlQuery(); 
 
    $("#btnNext").click(function () { 
        pageIndex = pageIndex + 1; 
        if (nextPagingInfo) { 
            position = new SP.ListItemCollectionPosition(); 
            position.set_pagingInfo(nextPagingInfo); 
        } 
        else { 
            position = null; 
        } 
 
        GetListItems(); 
    }); 
 
    $("#btnBack").click(function () { 
        pageIndex = pageIndex - 1; 
        position = new SP.ListItemCollectionPosition(); 
        position.set_pagingInfo(previousPagingInfo); 
        GetListItems(); 
    }); 
 
    GetListItems(); 
}); 
 
function GetListItems() { 
    //Set the next or back list items collection position 
    //First time the position will be null 
    camlQuery.set_listItemCollectionPosition(position); 
 
    // Create a CAML view that retrieves all contacts items  with assigne RowLimit value to the query 
    camlQuery.set_viewXml("<View>" + 
                                "<ViewFields>" + 
                                       "<FieldRef Name='FirstName'/>" + 
                                       "<FieldRef Name='Title'/>" + 
                                       "<FieldRef Name='Company'/>" + 
                                  "</ViewFields>" + 
                               "<Query>" + 
                                    "<OrderBy>" + 
                                      "<FieldRef Name='" + sortColumn + "' Ascending='true' />" + 
                                    "</OrderBy>" + 
                               "</Query>" + 
                               "<RowLimit>" + pageSize + "</RowLimit></View>"); 
 
    spItems = list.getItems(camlQuery); 
 
    context.load(spItems); 
    context.executeQueryAsync( 
            Function.createDelegate(this, onSuccess), 
            Function.createDelegate(this, onFail) 
        ); 
} 
 
// This function is executed if the above OM call is successful 
// This function render the returns items to html table 
function onSuccess() { 
 
    var listEnumerator = spItems.getEnumerator(); 
    var items = []; 
    var item; 
 
    while (listEnumerator.moveNext()) { 
        item = listEnumerator.get_current(); 
        items.push("<td>" + item.get_item('FirstName') + "</td><td>" + item.get_item('Title') + "</td><td>" + item.get_item('Company') + "</td>"); 
    } 
 
    var content = "<table><tr><th>First Name</th><th>Last Name</th><th>Company</th></tr><tr>" 
                + items.join("</tr><tr>") + "</tr></table>"; 
    $('#content').html(content); 
 
    managePagerControl(); 
} 
 
function managePagerControl() { 
 
    if (spItems.get_listItemCollectionPosition()) { 
        nextPagingInfo = spItems.get_listItemCollectionPosition().get_pagingInfo(); 
    } else { 
        nextPagingInfo = null; 
    } 
 
    $("#pageInfo").html((((pageIndex - 1) * pageSize) + 1) + " - " + ((pageIndex * pageSize) - (pageSize - spItems.get_count()))); 
 
    previousPagingInfo = "PagedPrev=TRUE&Paged=TRUE&p_ID=" + spItems.itemAt(0).get_item('ID') + "&p_" + sortColumn + "=" + encodeURIComponent(spItems.itemAt(0).get_item(sortColumn)); 
 
    if (pageIndex <= 1{ 
        $("#btnBack").attr('disabled''disabled'); 
    } 
    else { 
        $("#btnBack").removeAttr('disabled'); 
    } 
 
    if (nextPagingInfo) { 
        $("#btnNext").removeAttr('disabled'); 
    } 
    else { 
        $("#btnNext").attr('disabled''disabled'); 
    } 
 
}

Sunday, October 2, 2016

Wrintig the Custom CSS registration for multilingual Sites in SharePoint

Wrintig the Custom CSS registration for multilingual Sites in SharePoint 

From Layout forlder:
--------------------------
<SharePoint:CssRegistration ID="CssRegistration1" Name="Themable/CommonInitiative.css" runat="server" After="oslo.css"/>

From Style Library: if using the varistion in sharepoint
------------------------
<SharePointWebControls:CssRegistration ID="CssRegistration3" name="<% $SPUrl:~sitecollection/Style Library/~language/Themable/New_Css/CommonInitiative.css %>" runat="server"/>

Saturday, October 1, 2016

Binding DropDown with Ajax query from web service

Binding DropDown with Ajax query from web service 


$(document).ready(function () {

        var jobsVmDiv = new jobsVm();
        jobsVmDiv.init();
        ko.applyBindings(jobsVmDiv, $('#JobsDiv').get(0));

        $("#Job-selector option[value='-1']").attr("selected", true);
         $("#Job-selector").change(function () {
            var selector = document.getElementById("Job-selector");
            var ChangeText = $("#Job-selector option:selected").text();
            var completeUrl = selector.options[selector.selectedIndex].value;
            var indexOfComma = completeUrl.indexOf(',');
            window.location.href = window.location.origin + "/" + completeUrl;

        });

    })

    var jobsVm = function () {

        var self = this;

        self.JobsData = ko.observableArray(),

        self.language = function () {
            var lang = _spPageContextInfo.currentLanguage;
            if (lang == '1033') {
                return "English";
            }
            else {
                return "Arabic";
            }
        },
        self.init = function () {
            $.ajax({
                url: "/_vti_bin/JSONEServices/MoPWWebServices.svc/Vacancies/" + self.language(),
                type: "GET",
                async: false,
                headers: { "ACCEPT": "application/json;odata=verbose" },
                success: function (data) {
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            console.log(data);
                            $("#Job-selector").append($("<option></option>").val(data[i].Link).html(data[i].Title));
                        }
                    }
                },
                error:
                    function (data) {
                    },
            });
        }
    }
<html>
<select id="Job-selector" />
 <option value="-1"><asp:Literal ID="Literal1" runat="server" Text="<%$Resources:custom,PleaseSelect_Text%>"></asp:Literal></option>
</select>
</html>

Knockout Js Sample for Photo and Video

Knockout Js Sample for Photo and Video
------------------------------------------------------

<script type="text/javascript">

    var language;
    var languageText;
    var ajaxResult = new Array();
    var value = 1;
    var youtubeVideos = ko.observableArray();

    var myObj = function () {
        var content, id, link, status, openingDate
    }

    var viewModelPhotoGallery = function () {
        var self = this;

        self.video = ko.observable(),

self.photos = ko.observable(),

        self.language = ko.observable(language),

        self.init = function () {
            //GetFilteredTenders(self.tenders);
            //self.language(languageText);
            var uri = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=UUPO5AY4qU1s-HedJZ8T7xSw&key=AIzaSyB2uf8CU9re_74ybnPmnv4A--MpzfYWYME';
            $.ajax({
                url: uri,
                type: "GET",
                async: false,
                headers: { "ACCEPT": "application/json;odata=verbose" },
                success: function (data) {

                    self.video(data.items[0]);


                },
                error: function (request, textStatus, errorThrown) {

                }
            });


            var uri = '/_vti_bin/JSONEServices/MoPWWebServices.svc/GetTopTwoPhotos';
            $.ajax({
                url: uri,
                type: "GET",
                async: false,
                headers: { "ACCEPT": "application/json;odata=verbose" },
                success: function (data) {

                    self.photos(data);
               

                },
                error: function (request, textStatus, errorThrown) {

                }
            });
        }
    }


    $(document).ready(function () {
        var vmPG = new viewModelPhotoGallery();
        vmPG.init();
        ko.applyBindings(vmPG, $('#divPhotoVideos').get(0));


    })



    function CheckVideoLanguage(VideoTitle, Page) {

        if (Page.indexOf("en-us") > -1) {
            if (VideoTitle.match(/[a-z]/i)) {
                return true;
            } else {
                return false;
            }
        }
        else {
            if (!(VideoTitle.match(/[a-z]/i))) {
                return true;
            } else {
                return false;
            }
        }
    }
</script>

<div class="col-md-5 col-sm-12" id="divPhotoVideos">
    <header>
        <h2 class="full-caps text-left ">PHOTOS & VIDEOS <span class="pull-right view-all view-all-gallery">
            <a href="#">View Gallery
                <img src="/Style Library/en-us/Images/in-arrow.png" width="5" height="9" alt="" /></a>
        </span>
        </h2>
        <div class="border-3 Theme-border-color">
            <div class="border-left Theme-border-color-left"></div>
        </div>
    </header>
    <article>
        <!-- ko with: video() -->
        <div class="video-container col-md-12 col-sm-12 padding-right-none">
            <div>
                <iframe width="100%" height="234px" data-bind="attr: { 'src': 'http://www.youtube.com/embed/' + snippet.resourceId.videoId }" frameborder="0" allowfullscreen=""></iframe>

            </div>
            <div class="video-heading col-md-12 col-sm-12">
                <div class="videotittle" data-bind="text: snippet.title"> </div>
            </div>
        </div>
        <!-- /ko -->
<!-- ko foreach: photos -->

<div class="col-md-6 col-sm-6 col-xs-11 padding-right-none">
<img data-bind= "attr: { src: '/' + Url }" width="277px" height="182px">
</div>

<!-- /ko -->
    </article>
</div>

=======================================================================Another example=======================================================================




<script type="text/javascript" src="/SiteCollectionScripts/jquery.cssslider.js"></script>

<script type="text/javascript">

    var initiativeObj = function () {
        var Description,
ImageURL,
Title;
        var photos = [];
    }

    var photosClass = function () {
        var Title,
ImageURL,
CssString;
    }

    function AssignCssClassName(index) {

        switch (index) {
            case 0:
                return 'current_item';
                break;
            case 1:
                return 'previous_item';
                break;
            case 2:
                return 'next_item';
                break;
            case 3:
                return 'previous_item_2';
                break;
            case 4:
                return 'next_item_2';
                break;
        }
    }

    var vmInitiatativeDiv = function () {
        var self = this;

        self.initiatives = ko.observableArray([]),

        self.language = function () {
            var lang = _spPageContextInfo.currentLanguage;
            if (lang == '1033') {
                return "English";
            }
            else {
                return "Arabic";
            }
        },

        self.init = function () {

            $.ajax({
                url: 'http://vm.mopw.local/_vti_bin/JSONEServices/MoPWWebServices.svc/InitiativesWithNewsAndGallery/' + self.language() + '/',
                type: "GET",
                async: false,
                headers: { "ACCEPT": "application/json;odata=verbose" },
                success: function (data) {
                    console.log('length is : ' + data.length);
                    for (i = 0; i < data.length; i++) {
                        var obj = new initiativeObj();
                        obj.Description = data[i].Description;
                        obj.ImageURL = data[i].ImageURL;
                        obj.Title = data[i].Title;
                        obj.photos = new Array();

                        for (j = 0; j < data[i].PhotoGallery.length; j++) {
                            if (j == 5)
                                break;
                            var objPhoto = new photosClass();
                            objPhoto.Title = data[i].PhotoGallery[j].Title;
                            objPhoto.ImageURL = data[i].PhotoGallery[j].ImageURL;
                            objPhoto.CssString = AssignCssClassName(j);

                            obj.photos.push(objPhoto);
                        }
                        self.initiatives.push(obj);
                    }
                    console.log(self.initiatives());
                },
                error: function (request, textStatus, errorThrown) {

                }
            });
        }
    }

    $(document).ready(function () {

        var vmInitiatative = new vmInitiatativeDiv();

        vmInitiatative.init();
        ko.applyBindings(vmInitiatative, $('#InitiativeDiv').get(0));
    });

</script>
<div id="InitiativeDiv">

            <div class="col-md-7 col-sm-12 col-xs-12">
                <header>
                    <h2 class="full-caps text-left ">INITIATIVES<span class="pull-right view-all  view-all-initiatives">
                        <a href="#">View All Initiatives
                                    <img src="/Style Library/en-us/Images/in-arrow.png" width="5" height="9" alt="" />
                        </a>
                    </span>
                    </h2>
                    <div class="border-3 Theme-border-color">
                        <div class="border-left Theme-border-color-left"></div>
                    </div>
                </header>
                <article>

                    <article>

                        <!-- Initiative HTML -->

                        <div class="initiativeContainer">

                            <ul class="initiativeSlider">
                                <!-- ko foreach: initiatives -->
                                <li>
                                    <div class="choose_slider">
                                        <div class="choose_slider_items">
<ul id="mySlider1">
<!-- ko foreach: photos -->
                                           
                                                <li data-bind="attr: { class: CssString }">
                                                   <img data-bind="attr: { src: ImageURL }" width="226" height="152">
                                                </li>
                                           
<!-- /ko -->
</ul>
                                        </div>
                                    </div>
                                    <div class="col-md-12 initiative-content-container">
                                        <div class="col-md-3">
                                            <img data-bind="attr: { src: ImageURL }" alt="" />
                                        </div>
                                        <div class="col-md-9">
                                            <header class="">
                                                <div class="ReadingInitiative" data-bind="text: Title"></div>
                                            </header>
                                            <div class="border-btm-1 Theme-border-btm1-color" data-bind="html: Description"></div>
                                         
                                        </div>
                                    </div>

                                </li>
                                <!-- /ko-->
                           
                            </ul>

                            <!--header>
                                    <img alt="" class="initiatives-image" src="/Style Library/en-us/Images/initiatives-img.jpg">
                                </header-->

                            <script>

                                $(document).ready(function () {
                                    $('.initiativeSlider').bxSlider({
                                        auto: true,
                                        autoStart: true,
                                        pager: false,
                                        controls: true
                                    });
                                });


                                $(function () {
                                    $("#mySlider1").AnimatedSlider({
                                        //prevButton: "#btn_prev1",
                                        //nextButton: "#btn_next1",
                                        visibleItems: 5,
                                        infiniteScroll: true,
                                        willChangeCallback: function (obj, item) { $("#statusText").text("Will change to " + item); },
                                        changedCallback: function (obj, item) { $("#statusText").text("Changed to " + item); }
                                    });
                                    $("#mySlider2").AnimatedSlider({
                                        //prevButton: "#btn_prev1",
                                        //nextButton: "#btn_next1",
                                        visibleItems: 5,
                                        infiniteScroll: true,
                                        willChangeCallback: function (obj, item) { $("#statusText").text("Will change to " + item); },
                                        changedCallback: function (obj, item) { $("#statusText").text("Changed to " + item); }
                                    });


                                });

                            </script>


                        </div>
                    </article>



                </article>
            </div>
</div>




Knockout js binding Sample with ajax query

// Knockout  js binding Modal Sample with ajax query

-------------------------------------------------------------------

<link href="/Style Library/en-us/stylesheets/main.css" type="text/css" rel="stylesheet" />
<style>
.Theme-button-color {
    background-color: #a2821f !important;
    color: #fff !important;
}
</style>
<script type="text/javascript">

    var language;
    var languageText;
    var ajaxResult = new Array();
    var value = 1;
    var myObj = function() {
        var content, id, link, status, openingDate
    }

    var viewModel = function() {
        var self = this;

        self.tenders = ko.observableArray([]),

        self.language = ko.observable(language),

        self.init = function() {
            GetFilteredTenders(self.tenders);
            self.language(languageText);

        }
    }

    function daysInMonth(month, year) {
        return new Date(year, month, 0).getDate();
    }

    $(document).ready(function(){
        GetLanguage();
        //GetFilteredTenders();
        var vm = new viewModel();
        vm.init();
        ko.applyBindings(vm, $('#tendersDiv').get(0));
    });
    function GetLanguage() {

        var lang = _spPageContextInfo.currentLanguage;
        if (lang == '1033') {
            language = '/en-us/';
            languageText = "en";
        }
        else {
            language = '/ar-sa/';
            languageText = "ar";
        }
    }



    function GetFilteredTenders(tenders) {

        var currentYear = new Date().getFullYear();
        var month = "12";
        var status = "Open";
     
        var nbDays = new Date(currentYear, month, 0).getDate();
        var days = daysInMonth(12, currentYear);
        var d = new Date();
        var today = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
        var newsIndex = 0;
        var d = new Date();
        var formatedDate = d.format("yyyy-MM-ddTHH:mm:ssZ");
        // var  uri="https://services.moid.gov.ae/_api/lists/getbytitle('tenders')/items?$select=ID,TenderName_EN,TenderName_AR,TenderStatus,OpeningDate,SubmitDate&$filter=OpeningDate le datetime'" + formatedDate + "' and TenderStatus eq 'Approved' and SubmitDate le datetime'" + formatedDate + "'";
        var uri = "https://services.moid.gov.ae/_api/lists/getbytitle('tenders')/items?$select=ID,TenderName_EN,TenderName_AR,TenderStatus,OpeningDate,SubmitDate&$filter=OpeningDate ge datetime'" + formatedDate + "' and TenderStatus eq 'Approved' and SubmitDate le datetime'" + formatedDate + "'";
        $.ajax({
            url: uri,
            type: "GET",
            async: false,
            headers: { "ACCEPT": "application/json;odata=verbose" },
            success: function (data) {

                if(data.d.results.length>0)
                {
                    for(var i=0; i<data.d.results.length; i++)
                    {
                        if(i>3)
                        { break;}

                        if (language == '/en-us/') {
                            var cObj = new myObj();
                            cObj.content = data.d.results[i].TenderName_EN;
                        }
                        else{
                            cObj.content = data.d.results[i].TenderName_AR;
                        }
                        cObj.id = data.d.results[i].ID;
                        cObj.link = "https://services.moid.gov.ae" + language + "Competition/Pages/AvailableTenders.aspx?itemId=" + data.d.results[i].ID;
                        cObj.status = "open";
                        cObj.openingDate = moment(data.d.results[i].OpeningDate).format('MMMM DD, YYYY');
                        tenders.push(cObj);
                        //ajaxResult.push(cObj);


                    }
                }
                if(tenders().length < 4){
                    GetCloseTenders(tenders);
                }

            },
            error: function (request, textStatus, errorThrown) {

            }
     

        });

    }

    function GetCloseTenders(tenders)
    {
        var currentYear = new Date().getFullYear();
        var month = "12";
        var status = "Open";

        var value = 1;
        var nbDays = new Date(currentYear, month, 0).getDate();
        var days = daysInMonth(12, currentYear);
        var d = new Date();
        var today = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
        var newsIndex = 0;
   
        var d = new Date();
        var formatedDate = d.format("yyyy-MM-ddTHH:mm:ssZ");

        var  uri="https://services.moid.gov.ae/_api/lists/getbytitle('tenders')/items?$select=ID,TenderName_EN,TenderName_AR,TenderStatus,OpeningDate,SubmitDate&$filter=OpeningDate le datetime'" + formatedDate + "' and TenderStatus eq 'Approved' and SubmitDate le datetime'" + formatedDate + "'";

        $.ajax({
            url: uri,
            type: "GET",
            async: false,
            headers: { "ACCEPT": "application/json;odata=verbose" },
            success: function (data) {

                if(data.d.results.length>0)
                {
                    for(var i=0; i<data.d.results.length; i++)
                    {
                        if(tenders().length < 4){
                            if (language == '/en-us/') {
                                var cObj = new myObj();
                                cObj.content = data.d.results[i].TenderName_EN;
                            }
                            else{
                                cObj.content = data.d.results[i].TenderName_AR;
                            }
                            cObj.id = data.d.results[i].ID;
                            cObj.link = "https://services.moid.gov.ae" + language + "Competition/Pages/AvailableTenders.aspx?itemId=" + data.d.results[i].ID;

                            cObj.openingDate = moment(data.d.results[i].OpeningDate).format('MMMM DD, YYYY');
                            cObj.status="close";

                            tenders.push(cObj);
                            //ajaxResult.push(cObj);
                        }
                        else{
                            break;
                        }
 
                    }

                }
            },
            error: function (request, textStatus, errorThrown) {

            }

        });

    }

</script>

 <section id="tendersDiv" class="wrapper style1 special tender-bg">
        <div>
            <div class="inner">
                <header>
                    <h2 class="full-caps text-left tender-heding">Tenders <span class="pull-right view-all-tenders">
<!-- ko if: language() == "en" -->
<a href="/en-us/Competition/Pages/AvailableTenders.aspx">View All Tenders <i aria-hidden="true" class="fa fa-caret-right" style="font-size: 15px;"></i></a>
<!-- /ko -->
<!-- ko if: language() === 'ar' -->
<a href="/ar-sa/Competition/Pages/AvailableTenders.aspx">View All Tenders <i aria-hidden="true" class="fa fa-caret-right" style="font-size: 15px;"></i></a>
<!-- /ko -->
</span></h2>
                    <div class="border-3 Theme-border-color">
                        <div class="border-left Theme-border-color-left"></div>
                    </div>
                </header>
<!-- ko foreach: tenders -->
                <div class="col-md-3 col-sm-6 col-xs-12">

                    <div class="tender-box">
                        <div class="tender-text" >
                          <span data-bind="text: content"></span>
                            <div class="tender-datte" data-bind="text: openingDate"></div>
                            <div class="text-center margn-top-10">
<!-- ko if: status == 'open' -->
                                <a data-bind="attr : { href: link }" href="#" class="button special tendersbtn Theme-button-color">Participate </a>
<!-- /ko -->
<!-- ko if: status == 'close' -->
<span class="button special tendersbtn Theme-button-color" style="cursor: default;background-color: gray !important;">Closed </span>
<!-- /ko -->
                            </div>
                        </div>
                    </div>
                </div>
<!-- /ko -->
             
            </div>
        </div>
    </section>