/* Minification failed. Returning unminified contents.
(1645,33-40): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: selItem
 */
///var AoaCart = angular.module("AoaCart", []);

//for local
//var applicationUrl = "http://localhost:58422";

//for server
var applicationUrl = "https://store.the-aps.org";


var AoaShopping = angular.module('AoaShopping', ['ngCookies', '720kb.tooltips']);;
//loader

function hide() {
    document.getElementById("preloader").style.display = "none";
}

function show() {
    document.getElementById("preloader").style.display = "block";
}



var theDialog = $(".mydialog").dialog({
    autoOpen: false,
    resizable: false,
    modal: true,
    width: 'auto'
});

//Slider
function slideShow() {
    setTimeout(function () {
        $(".regular").slick({
            dots: false,
            infinite: true,
            slidesToShow: 3,
            slidesToScroll: 1,
            autoplay: true,
            autoplaySpeed: 3000,
        });
        $(".slider_main").show();
    }, 500);
};

var showHide = 0;
$(document).ready(function () {

    $("#show_banner").click(function () {
        if (showHide == 0) {
            $(this).text('Show Banner');
            $("#slides").hide();
            showHide = 1;
        } else if (showHide == 1) {
            $(this).text('Hide Banner');
            $("#slides").show();
            showHide = 0;
        }
    });
    $(".slider_main").hide();
    //PopUp Product close
    $('#popClose').click(function () {
        $(this).parents().find('div.product_quick_view').hide();
    });
});

//Change Grid/List Views
function viewChange(id) {
    if (id == "pd_listView") {
        $('#products_view').removeClass('pd_gridView').addClass('pd_listView');
    } else if (id == "pd_gridView") {
        $('#products_view').removeClass('pd_listView').addClass('pd_gridView');
    }
};

// Cart Popup
jQuery(document).ready(function ($) {
    //$('#CCNumber').attr('autocomplete', 'off');
    //$('#CCcvv').attr('autocomplete', 'off');

    $('#shipViaCodeDD').attr("disabled", true);
    var sesCustomerId = '';
    //close popup
    $('.cart-popup').on('click', function (event) {
        if ($(event.target).is('.cart-popup-close') || $(event.target).is('.cart-popup') || $(event.target).is('.continue-shopping')) {
            event.preventDefault();
            $(this).removeClass('is-visible');
            $('.cart-popup-container').removeAttr('style');

            $('.addressList').hide();
            sessionStorage.removeItem('fromCartPop');
            sessionStorage.removeItem('fromReviewPop');
        }
    });

    $('.wishlist-popup').on('click', function (event) {
        if ($(event.target).is('.cart-popup-close') || $(event.target).is('.cart-popup')) {
            event.preventDefault();
            $(this).removeClass('is-visible');
        }
    });

    //close popup when clicking the esc keyboard button
    $(document).keyup(function (e) {
        if (e.which == '27') {
            $('.cart-popup').removeClass('is-visible');
        }

    });

    $(document).keypress(function (e) {
        //validations
        var flag = true;
        if (e.target.className == "cartdetails" || e.target.className == "ProductQuantity" || e.target.className.indexOf("qty") != -1 || e.target.className.indexOf("ccNumInput") != -1) {

            var txtbox = e.target;

            if (txtbox.value != 0) {
                //Numeric validation           
                if (e.which != 13) {
                    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                        e.preventDefault();
                        return false;
                    }
                }
            }
        }

    });

    $('#continue_form').keypress(function (e) {

        if (e.which === 46) return false;
    }).on('input', function () {
        var self = this;
        setTimeout(function () {
            if (self.value.indexOf('.') != -1) self.value = parseInt(self.value, 10);
        }, 0);
    });

});

$(document).on('click', "#useOther, #ccType", function (event) {

    var evt = event || window.event;

    if (evt.target.id == "useOther") {
        $('#CreditCardForm').show();
        $('#CreditCardForm').removeClass("ng-hide");
    } else {
        $('#CreditCardForm').hide();
        clearCC();
    }
});
function clearCC() {
    $("#CCName").val('');
    $("#CCNumber").val('');
    $("#CCcvv").val('');
    $("#months").val("string:Month");
    $("#years").val('string:Year');
    $("#useOtherVal").text("false");
    $("#saveCCCard").prop("checked", false);
};
//$("#addAddressNew").click(function () {
//    $("#addAddressBilling").show();
//});
//$('#addNewAddress').click(function () {
//    $('#addAddress').show();
//    $(".actions").hide();
//});

$('#changeAddress').click(function () {
    $('.addressList').show();
    $(".actions").hide();
});

// Multi Step
$(document).ready(function () {

    $('.btnCancel').on("click", function () {
        $('#CreditCardForm').hide();
        $('.addressList').hide();
        $(".actions").show();
    });

    $('.step_trigger').on('click', function () {
        var updateCart = true;

        //$('#CreditCardForm').hide();
        $('.addressList').hide();
        $(".actions").show();
        var scope = angular.element(document.getElementById('step1_MyCart')).scope();
        var scope1 = angular.element(document.getElementById('step2_Shipping')).scope();
        var appElement = document.querySelector('[ng-app=AoaShopping]');
        var appScope = angular.element(appElement).scope();
        var controllerScope = appScope.$$childHead;

        if ($(this).attr('id') == 'myCart') {
            /* || typeof controllerScope.CartDetailsLength == "undefined"*/
            if (controllerScope.$parent.CartDetailsLength == 0) {
                $('#alrtMsg').empty();
                var txtLgn = "No products to continue!";
                $('#alrtMsg').show().html(txtLgn);
                return
            }

            //check the before continue is uer is login
            if (scope.sesCustomerId == null || scope.sesCustomerId == "") {
                $('#alrtMsg').empty();
                ////  var txtLgn = "Please <a href='" + applicationUrl + "/Login/index?url=" + window.location.href + "'>Login</a> to continue!";
                //var url = applicationUrl + '/Login/index';
                ////   var txtLgn = "Please <a href='javascript:;' onclick='window.open(" + url + ", 'Login', 'scrollbars=yes, resizable=yes, top=200, left=500, width=400, height=400');'>Login</a> to continue!";
                //var txtLgn = "Please  <a href='javascript:;' onclick='RDTOLogin();'>Login</a> to continue!";
                //$('#alrtMsg').show().html(txtLgn);
                RDTOLogin();
                sessionStorage.setItem('fromCartPop', 'fromCart');
                return false;
            }

            //UpdateToCart Method access when continue
            scope.$apply(function () {

                if (scope.UpdateToCart('cart')) {

                    updateCart = false;
                }
                try {
                    //Getting Shipping Charges based on the locations
                    scope.shipViaCodeClient();

                    //Getting Countries
                    scope.getCountries();

                    //Getting States
                    scope.getStates();
                    //scope.clearForm();
                } catch (e) {

                }

            });
        }

        if (updateCart) {

            if ($(this).attr('id') == 'addressTab') {
                $('.cart-popup-container').removeAttr('style');

                if ($('#shipViaCodeDD').val() == "") {
                    jAlert("Please select Shipping Preference");
                    return;
                }
                //if (!$('.addCheckBilling').is(':checked')) {
                //    jAlert("Please Check the Billing Address!");
                //    return;
                //}
                if (!$('.addCheckShiiping').is(':checked')) {
                    jAlert('Please Check the Shipping Address!');
                    return;
                }
                $('#popLoader').show();

                scope1.taxShippingPrice();
                //scope1.clearForm();
            }


            var divID = $(this).attr('data-box');
            $(this).addClass('trigger_active').siblings().removeClass('trigger_active');
            $('#' + divID).addClass('step_active').siblings().removeClass('step_active');
        }
    });
});

//Factorial Search function

function RDTOLogin() {
    setTimeout(function () {
        $('#LoginPopup').addClass('is-visible');
    }, 500);
}

//Sorting string Array 
function length_alpha_sort2(astr, bstr) {


    astr += '';
    bstr += '';
    if (astr.length != bstr.length) {
        return astr.length - bstr.length;
    }
    return (astr < bstr) ? -1 : (astr > bstr) ? 1 : 0;
};

//Sorting object based on length of property
function SortByLength(astr, bstr) {

    astr.SearchWordLength += '';
    bstr.SearchWordLength += '';
    if (astr.SearchWordLength != bstr.SearchWordLength) {
        return astr.SearchWordLength.length - bstr.SearchWordLength;
    }
    if (astr.SearchWordLength == bstr.SearchWordLength) {
        return astr.SearchItems.length - bstr.SearchItems.length;
    }

    return (astr.SearchWordLength < bstr.SearchWordLength) ? -1 : (astr.SearchWordLength > bstr.SearchWordLength) ? 1 : 0;
};


//Generating   Combinations of search word
function getCombinationWords(searchWord) {

    var string = searchWord;
    var sArray = string.split(' ');
    var n = sArray.length;

    sArray.sort(length_alpha_sort2);

    var combinations = "";
    for (var i = 0; i < n; i++) {
        for (var j = 0; j <= i; j++) {
            combinations = combinations + sArray.slice(j, n - i + j).join(' ') + ', ';

        }
    }
    //console.log(combinations)
    return combinations;
}

//remove duplicate object in array
var unique = function (origArr) {
    var newArr = [],
        origLen = origArr.length,
        found, x, y;
    for (x = 0; x < origLen; x++) {
        found = undefined;
        for (y = 0; y < newArr.length; y++) {
            if (origArr[x] === newArr[y]) {
                found = true;
                break;
            }
        }
        if (!found) {
            var products = $.grep(newArr, function (obj) {
                return obj.ProductId == origArr[x].ProductId;
            });
            if (products.length == 0) {
                newArr.push(origArr[x]);
            }
        }
    }
    return newArr;
}

//Factorial Search
var i = 0;
function factorialSearch(products, searchWord) {
    if (searchWord.length > 0) {
        var searchItems = [];
        angular.forEach(getCombinationWords(searchWord).split(','), function (predicate) {

            if (predicate.trim().length == 0)
                return;
            var items = {};
            var arr = predicate.trim().split(' ');
            var str = "";

            $.each(arr, function (index, value) {
                str += " (n.ProductName.toLowerCase().indexOf('" + value.toLowerCase() + "') > -1 || n.ProductCode.toLowerCase().indexOf('" + value.toLowerCase() + "') > -1)   &&";
                //console.log(str)
            });

            if (str.length > 0) {
                if (str.substring(str.length, str.length - 2) == "&&") {
                    str = str.substring(0, str.length - 2);
                }
            }

            items = $.grep(products, function (n, i) { // just use arr
                return eval(str);
            });
            //console.log(items);
            if (items.length > 0) {
                var srchItems = {}
                srchItems["SearchWordLength"] = predicate.trim().length;
                srchItems["SearchItems"] = items;
                srchItems["SearchWord"] = predicate.trim();
                searchItems.push(srchItems);
            }

        });

        searchItems = searchItems.sort(SortByLength);

        var actualItems = [];

        $.each(searchItems, function (index, obj) {
            if (obj.SearchItems.length > 0)
                Array.prototype.push.apply(actualItems, obj.SearchItems);
        });

        var arrUnique = unique(actualItems);


        return arrUnique;
    }

}

//end

// Mobile Menu	
$(document).ready(function () {
    $('.site_navigation').slicknav({
        //prependTo:'#mobile_nav',
        closeOnClick: true,
        allowParentLinks: true
    });

    $(".site_navigation ul li a").click(function (e) {
        $(".site_navigation ul li a").removeClass("current");
        $(this).addClass("current");

    });



});

$(window).scroll(function () {
    var sticky = $('#site_header'), scroll = $(window).scrollTop();
    if (scroll >= 10) {
        sticky.addClass('headerFixed');
    }
    else { sticky.removeClass('headerFixed'); }
});

function GetCardType(n) {

    //console.log("GetCardType", n);
    // visa
    var re = new RegExp("^4");
    if (n.match(re) != null)
        return "VI";

    // Mastercard
    re = new RegExp("^5[1-5]");
    if (n.match(re) != null)
        return "MC";

    // AMEX
    re = new RegExp("^3[47]");
    if (n.match(re) != null)
        return "AX";

    // Discover
    re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
    if (n.match(re) != null)
        return "DI";

    return "";
}
// Mobile Account Menu	
$(document).ready(function () {
    //$('.account_links').slicknav({
    //    prependTo: '#account_nav_mobile',
    //    label: 'My Account',
    //    closeOnClick: true,
    //    allowParentLinks: true
    //});

    $(document).on('click', '.add_credit_cart_btn', function (event) {
        $('#CreditCardForm').show();
        $("#useOtherVal").text("true");
    });

    $(document).on('keydown', '#CCNumber', function (event) {
        var ccNum = $('#CCNumber').val();

        if (ccNum.length > 2) {
            var cType = GetCardType(ccNum);

            switch (cType) {
                case "VI":
                    //console.log("VISA");
                    $("input[name=cardType][value='Visa']").attr('checked', 'checked');
                    $('#rdoVI').css("display", "block");
                    break;
                case "MC":
                    //console.log("MASTER");
                    $("input[name=cardType][value='MC']").attr('checked', 'checked');
                    $('#rdoMC').css("display", "block");
                    break;
                case "AX":
                    //console.log("AMERICAN EXPRESS");
                    $("input[name=cardType][value='AMEX']").attr('checked', 'checked');
                    $('#rdoAX').css("display", "block");
                    break;
                case "DI":
                    console.log("DIFFERENT");
                    $("input[name=cardType]").removeAttr('checked');
                    break;
                default:
                    console.log("NONE");
                    $("input[name=cardType]").removeAttr('checked');
                    break;
            }
        }
        else {
            //$('#rdoMC').css("display", "none");
            //$('#rdoVI').css("display", "none");
            //$('#rdoAX').css("display", "none");
        }
    });
    
});

function printOrder() {

    var divToPrint = $('.order_received_details').html();


    var contents = $('.order_received_details').html();
    var frame1 = document.createElement('iframe');
    frame1.name = "frame1";
    frame1.style.position = "absolute";
    frame1.style.top = "-1000000px";
    document.body.appendChild(frame1);
    var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
    frameDoc.document.open();
    frameDoc.document.write('<html><head><link href="../Content/style.css" rel="stylesheet" type="text/css"></head><title>Order Contents</title>');
    frameDoc.document.write('</head><body>');
    frameDoc.document.write(contents);
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
        window.frames["frame1"].focus();
        window.frames["frame1"].print();
        document.body.removeChild(frame1);
    }, 500);
    return false;
};

$(document).on('click', 'span.catTags a', function () {
    var scope = angular.element(document.getElementById('selctedCatsNames')).scope();

    var inputItem = $(this).attr("data-catType");
    var inputitemId = $(this).attr('data-catId');

    if (inputitemId != 'All') {
        $.each($('.' + inputItem), function () {
            if ($(this).attr('id') == inputitemId) {
                $(this).prop('checked', false);
            }
        });

        $(this).parent().remove();
    }
    else {
        var filter = ['category', 'format', 'topic', 'memberproducts', 'nonmemberproducts']
        var i = 0;
        for (i; i < filter.length; i++) {
            $.each($('.' + filter[i]), function () {
                $(this).prop('checked', false);
            });
            $(this).parent().remove();
        }
    }

    scope.$apply(function () {
        scope.BindProducts();
    });

});

//View Product
function viewProduct(href) {
    var viewProduct = '/Product/viewproduct/?ProductId=';

    if (!isNaN(parseInt(href))) {
        window.location.href = applicationUrl + viewProduct + href;
        return
    }
    if (href == "/Login/Index") {
        //var currentUrl = window.location + '';
        //console.log(currentUrl);
        //var xyz = applicationUrl + href + '?url=' + currentUrl;
        //var w = 500;
        //var h = 400;
        //var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
        //var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

        //var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        //var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

        //var left = ((width / 2) - (w / 2)) + dualScreenLeft;
        //var top = ((height / 2) - (h / 2)) + dualScreenTop;

        //var myWindow = window.open(xyz, 'Login', 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        RDTOLogin();

    } else {
        if (href.indexOf("http") >= 0)
            window.location.href = href;
        else
            window.location.href = applicationUrl + href;
    }
}

$(document).ready(function () {
    setTimeout(function () {
        console.log(sessionStorage.getItem('fromCartPop'))
        if (sessionStorage.getItem('fromCartPop') == "fromCart") {
            var scope = angular.element(document.getElementById('site_header')).scope();
            console.log(scope)
            scope.$apply(function () {
                scope.OpenCart();

                sessionStorage.removeItem('fromCartPop');
            });
        } else if (sessionStorage.getItem('fromReviewPop') == "fromReview") {
            var scope = angular.element(document.getElementById('site_header')).scope();
            scope.$apply(function () {
                scope.reviewPopup();
                sessionStorage.removeItem('fromReviewPop');
            });
        }
    }, 800);
});

function register() {
    $.ajax({
        method: "POST",
        url: applicationUrl + "/Home/GetRegisterURL",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {
        window.location.href = data + "?returnurl=" + encodeURIComponent(window.location);
    }).error(function (x) {
        //console.log(x)
    });
    //window.location.href = "http://172.17.50.20/personifyebusiness/RegisterCustomer/tabid/340/Default.aspx?returnurl=" + encodeURIComponent(window.location);
    //window.location.href = "http://ebus.the-aps.org/personifyebusiness/RegisterCustomer/tabid/340/Default.aspx?return=" + encodeURIComponent('/login?redir=' + window.location);
    //https://stage.aoa.org/SSO/Register?return=%2flogin%3fredir%3dhttp%3A%2F%2F182.18.172.127%2FAoaShoppingCart_v9.1%2F
}


// Mobile Filter Options
$(window).load(function () {
    $('#showFilter').click(function (e) {
        $('.left_sidebar').fadeIn('slow', function () {
            $('.left_sidebar').fadeIn('slow');
        });
    });
    $('#hideFilter').click(function (e) {
        $('.left_sidebar').fadeOut('slow', function () {
            $('.left_sidebar').fadeOut('slow');
        });
    });

    var currPage = $(".currentPage").text(),
        currPageSpl = currPage.split(">");

    $(".site_navigation ul li a").each(function () {
        if ($(this).text().toLowerCase() == currPageSpl[currPageSpl.length - 1].toLowerCase().trim()) {
            $(".site_navigation ul li a").removeClass("current");
            $(this).addClass("current");
        }
    });
});

$(window).resize(function () {
    if ($(window).width() >= 780) {
        $('.left_sidebar').removeAttr('style');
    }
});

var getQueryString = function (field, url) {
    var href = url ? url : window.location.href;
    var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
    var string = reg.exec(href);
    return string ? string[1] : null;
};

function ShareProduct(From) {
    var tittle = $(".productTitle").text().replace("&", "%26");
    var url = window.location.href;

    var indexUrl = getQueryString('productid', url)

    var fburl = applicationUrl + "/SocialShare/FaceBookProductshare/?productid=" + indexUrl;
    if (From == 'twitter') {
        window.open("https://twitter.com/share?url=" + url + "&text=" + tittle + "");
    } else if (From == 'facebook') {
        window.open("http://www.facebook.com/sharer/sharer.php?u=" + fburl + "&t=" + tittle + "");
    } else if (From == 'gplus') {
        window.open("https://plus.google.com/share?url=" + url + "&text=" + tittle + "");
    } else if (From == 'linkedin') {
        window.open("http://www.linkedin.com/shareArticle?url=" + url + "&text=" + tittle + "");
    } else if (From == 'pinterest') {
        window.open("https://www.pinterest.com/pin/create/button/?url=" + url + "&description=" + tittle + "");
    }
    else if (from = 'email') {
        var VSubject = tittle;
        var Vbody = 'Check out this product on the APS Store! ' + url;
        window.location.href = "mailto:?subject=" + VSubject + "&body=" + Vbody + "";
    }

    // <a class="fa fa-facebook share-base share-facebook" onclick="window.open('https://www.facebook.com/dialog/share?app_id=your_app_id&display=popup&href=the_authorized_link&redirect_uri=the_authorized_link')"></a>

}

//Time Stamp convert into Diasplay Time Zoze
function convertTimestamp(timestamp) {
    var d = new Date(timestamp * 1000),	// Convert the passed timestamp to milliseconds
          yyyy = d.getFullYear(),
          mm = ('0' + (d.getMonth() + 1)).slice(-2),	// Months are zero based. Add leading 0.
          dd = ('0' + d.getDate()).slice(-2),			// Add leading 0.
          hh = d.getHours(),
          h = hh,
          min = ('0' + d.getMinutes()).slice(-2),		// Add leading 0.
          ampm = 'AM',
          time;

    if (hh > 12) {
        h = hh - 12;
        ampm = 'PM';
    } else if (hh === 12) {
        h = 12;
        ampm = 'PM';
    } else if (hh == 0) {
        h = 12;
    }

    // ie: 2013-02-18, 8:35 AM	
    time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
    return time;
}

;
/*
 AngularJS v1.4.5
 (c) 2010-2015 Google, Inc. http://angularjs.org
 License: MIT
*/
(function (p, g, l) {
    'use strict'; function m(b, a, f) {
        var c = f.baseHref(), k = b[0]; return function (b, d, e) {
            var f, h; e = e || {}; h = e.expires; f = g.isDefined(e.path) ? e.path : c; d === l && (h = "Thu, 01 Jan 1970 00:00:00 GMT", d = ""); g.isString(h) && (h = new Date(h)); d = encodeURIComponent(b) + "=" + encodeURIComponent(d); d = d + (f ? ";path=" + f : "") + (e.domain ? ";domain=" + e.domain : ""); d += h ? ";expires=" + h.toUTCString() : ""; d += e.secure ? ";secure" : ""; e = d.length + 1; 4096 < e && a.warn("Cookie '" + b + "' possibly not set or overflowed because it was too large (" +
            e + " > 4096 bytes)!"); k.cookie = d
        }
    } g.module("ngCookies", ["ng"]).provider("$cookies", [function () {
        var b = this.defaults = {};
        this.$get = ["$$cookieReader", "$$cookieWriter", function (a, f) {
            return {
                get: function (c) { return a()[c] }, getObject: function (c) { return (c = this.get(c)) ? g.fromJson(c) : c }, getAll: function () { return a() },
                put: function (c, a, n) { f(c, a, n ? g.extend({}, b, n) : b) },
                putObject: function (c, b, a) { this.put(c, g.toJson(b), a) },
                remove: function (a, k) { f(a, l, k ? g.extend({}, b, k) : b) }
            }
        }]
    }]);
    g.module("ngCookies").factory("$cookieStore", ["$cookies", function (b) {
        return {
            get: function (a) { return b.getObject(a) },
            put: function (a, f) { b.putObject(a, f) },
            remove: function (a) { b.remove(a) }
        }
    }]); m.$inject = ["$document", "$log", "$browser"]; g.module("ngCookies").provider("$$cookieWriter", function () { this.$get = m })
})(window, window.angular);
//# sourceMappingURL=angular-cookies.min.js.map
;
AoaShopping.controller('AoaShoppingController',
    ['$scope'
        , '$filter'
        , '$http'
        , 'urlService'
        , '$timeout'
        , '$rootScope'
        , '$window'
        , 'productCart'


    , function ($scope
        , $filter
        , $http
        , urlService
        , $timeout
        , $rootScope
        , $window
        , productCart
        , $routeParam) {
        "use strict"
        //Global Variables
        $scope.currentPage = 0;
        $scope.productsPerPage = 12;
        $scope.getData = [];
        $scope.search = '';
        $scope.Products = '';
        $scope.ServerProducts = '';
        $scope.pageSize = "12";
        $scope.pageStartIndex = '';
        $scope.pageDynamicCount = $scope.productsPerPage;
        $scope.totalProducts = '';
        $scope.sesCustomerId = '';
        $scope.sesToken = '';
        $scope.sesCustomerName = '';
        $scope.sesUserIsMember = '';
        $scope.FeatureProductImages = '';
        $scope.catList = '';
        $scope.userAddress = '';
        $scope.ShippingAddresses = [];
        $scope.BillingAddresses = [];
        $scope.catList = [];
        $scope.showDetails = false;
        $scope.CartDetailsLength = 0;

        //Sorting
        // set the default sort type
        $scope.sortReverse = false;  // set the default sort order

        $scope.BindSettings = function () {
            if (sessionStorage.getItem("pagesize") != null) {
                if (sessionStorage.getItem("pagesize") == 0) {
                    $scope.pageSize = "all";
                    $scope.productsPerPage = 0;
                    $scope.pageDynamicCount = 12;
                }
                else {
                    $scope.pageSize = sessionStorage.getItem("pagesize");
                    $scope.productsPerPage = sessionStorage.getItem("pagesize");
                    $scope.pageDynamicCount = sessionStorage.getItem("pageDynCount");
                }
            }

            if ($scope.pageSize == "all") {
                $scope.pageDynamicCount = sessionStorage.getItem("tp");
            }

            if (sessionStorage.getItem("sortBy") != null) {
                $scope.sortBy = sessionStorage.getItem("sortBy");
            }
            else {
                $scope.sortBy = "Sort by";
            }
            if (sessionStorage.getItem("sortType") != null) {
                $scope.sortType = sessionStorage.getItem("sortType");

            }
            if (sessionStorage.getItem("sortReverse") != null) {


                if (sessionStorage.getItem("sortReverse") == "true") {
                    $scope.sortReverse = true;
                }
                else {
                    $scope.sortReverse = false;
                }
            }

            if (sessionStorage.getItem("sortReverse") != null) {
                if (sessionStorage.getItem("sortReverse") == "true") {
                    $scope.sortReverse = true;
                }
                else {
                    $scope.sortReverse = false;
                }

            }
        }
        $scope.BindSettings();

        $scope.sort = function () {

            if ($scope.sortBy == "A-Z") {
                $scope.sortType = 'ProductName'
                $scope.sortReverse = false;
            }
            else if ($scope.sortBy == "Z-A") {
                $scope.sortType = 'ProductName'
                $scope.sortReverse = true;
            }
            else if ($scope.sortBy == "PriceLH") {
                if ($scope.sesUserIsMember == '1')
                    $scope.sortType = 'MemberPrice'
                else
                    $scope.sortType = 'Price'
                $scope.sortReverse = false;
            }
            else if ($scope.sortBy == "PriceHL") {
                if ($scope.sesUserIsMember == '1')
                    $scope.sortType = 'MemberPrice'
                else
                    $scope.sortType = 'Price'
                $scope.sortReverse = true;
            }
            else if ($scope.sortBy == "highRating") {
                $scope.sortType = 'Rating'
                $scope.sortReverse = true;
            }
            else if ($scope.sortBy == "lowRating") {
                $scope.sortType = 'Rating'
                $scope.sortReverse = false;
            } else {
                //$scope.sortType = 'ProductName'
                //$scope.sortReverse = false;
                $scope.sortType = ''
                $scope.sortReverse = false;
            }


            //Maintaining sorting state
            sessionStorage.setItem("sortBy", $scope.sortBy);
            sessionStorage.setItem("sortType", $scope.sortType);
            sessionStorage.setItem("sortReverse", $scope.sortReverse);

        };

        // Left Menu Categories
        function SelectCategory(propertyname, selectedCategories, categories) {
            $.each(selectedCategories, function (index, value) {

                if (value.length > 0) {

                    $.grep(categories, function (e) {

                        var str = "if (e." + propertyname + "== value) {e[\"selected\"] = true;";
                        str += "}";
                        eval(str);
                    })
                }

            });
        }

        urlService.dataProvider(categoryMethod, "GET", '').success(function (data) {
            $scope.catList = data;

            if (sessionStorage.getItem("Format") != null) {
                var Selectedformats = sessionStorage.getItem("Format").split(',');
                SelectCategory("FormatId", Selectedformats, $scope.catList.Formats);
            }

            $scope.Formats = $scope.catList.Formats;

            if (sessionStorage.getItem("Category") != null) {
                var SelectedCategories = sessionStorage.getItem("Category").split(',');

                SelectCategory("CategoryId", SelectedCategories, $scope.catList.Categories);
            }

            $scope.Categories = $scope.catList.Categories;



            if (sessionStorage.getItem("Topic") != null) {
                var SelectedTopics = sessionStorage.getItem("Topic").split(',');


                //alert(SelectedTopics);
                SelectCategory("TopicCode", SelectedTopics, $scope.catList.Topics);
            }

            $scope.Topics = $scope.catList.Topics;

            //Member for block
            if (sessionStorage.getItem("member") != null) {
                if (sessionStorage.getItem("member")) {
                    $(".memberproducts").attr("checked", true);
                }
            }
            if (sessionStorage.getItem("nonmember") != null) {
                if (sessionStorage.getItem("nonmember")) {
                    $(".nonmemberproducts").attr("checked", true);
                }
            }
            //end

            //dropdown filling
            var categeriesDdl = [];

            var def = {};
            def["Description"] = "All";
            def["type"] = "All";
            categeriesDdl.push(def);
            if ($scope.Formats !== undefined) {
                $.each($scope.Formats, function (index, value) {

                    var formats = {};
                    formats["Description"] = value.Description;
                    formats["type"] = "format:" + value.FormatId;
                    categeriesDdl.push(formats);
                });
            }
            if ($scope.Categories !== undefined) {
                $.each($scope.Categories, function (index, value) {

                    var categories = {};
                    categories["Description"] = value.CategoryName;
                    categories["type"] = "category:" + value.CategoryId;
                    categeriesDdl.push(categories);
                });
            }
            if ($scope.Topics !== undefined) {
                $.each($scope.Topics, function (index, value) {

                    var topics = {};
                    topics["Description"] = value.TopicDescription;

                    topics["type"] = "topic:" + value.TopicCode;
                    topics["TopicCode"] = value.TopicCode;
                    categeriesDdl.push(topics);

                });
            }
            $scope.ddlCategories = categeriesDdl;

            //end


        });

        // Products data from factory Service
        var featuredProductsBanner = [];
        $scope.listProducts = function () {
            urlService.dataProvider(allProductsMethod, "POST", '').success(function (data) {
                $scope.TempProducts = data;
                $scope.Products = unique($scope.TempProducts);
                $scope.ServerProducts = data;
                $scope.totalProducts = $scope.Products.length;
                $scope.BindProducts(); //To maintain state of filter products      
                $scope.searchLoad();
                hide();
                $scope.sort();
                if ($scope.FeatureProductImages.length == 0) {
                    $.grep($scope.Products, function (i) {
                        if (i.IsFeatureProduct == true) {
                            featuredProductsBanner.push({ "ProductImage": i.ProductImage, "ProductId": i.ProductId, "ShortDescription": i.ShortDescription, "ProductName": i.ProductName });
                        }
                    });
                }

                //get customer information
                //$scope.sessionInfo();
            });
        };
        $scope.listProducts();

        //Get sessioninfo
        $scope.sessionInfo = function () {
            urlService.dataProvider(sessionMethod, "POST", '').success(function (data) {
                $scope.sesCustomerId = data[0].CustomerId;
                $scope.sesToken = data[0].Token;
                $scope.sesCustomerName = data[0].CustomerName;
                $scope.sesUserIsMember = data[0].IsMember;
                if ($scope.sesCustomerId != '') {
                    //Getting User Favourite Items with customer Id
                    $scope.GetFavouriteItems($scope.sesCustomerId);

                    ////Getting Shipping Charges based on the locations
                    //$scope.shipViaCodeClient();

                    ////Getting Countries
                    //$scope.getCountries();

                    ////Getting States
                    //$scope.getStates();
                }
            });
        }
        $scope.sessionInfo();

        $scope.FeatureProductImages = featuredProductsBanner;

        //Product filter Method
        $scope.filterProducts = function (SearchCondition) {
            var catUrl = applicationUrl + '/home/GetProducts';
            return $http({
                method: "GET",
                url: catUrl,
                params: { SelectedItems: SearchCondition },
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            }).success(function (data) {
                $scope.Products = data;
                $scope.totalProducts = $scope.Products.length;
                hide();
            }).error(function (x) {

            });

        }

        // Products Navigation START
        $scope.prevPage = function () {
            if ($scope.currentPage > 0) {
                $scope.currentPage--;
                sessionStorage.setItem("currentPage", $scope.currentPage);

                if ($scope.currentPage == parseInt($scope.totalProducts / parseInt($scope.pageSize))) {
                    $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                    $scope.pageDynamicCount = $scope.totalProducts;
                } else {
                    $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                    $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                    sessionStorage.setItem("pageDynCount", $scope.pageDynamicCount);
                }

            }
        };

        $scope.prevPageDisabled = function () {
            return $scope.currentPage === 0 ? "disabled" : "";
        };

        $scope.pageCount = function () {

            if ($scope.productsPerPage == 0) {
                return 0;
            }

            return Math.ceil($scope.totalProducts / $scope.productsPerPage) - 1;

        };

        $scope.nextPage = function () {

            if ($scope.currentPage < $scope.pageCount()) {
                $scope.currentPage++;
                sessionStorage.setItem("currentPage", $scope.currentPage);

                if ($scope.currentPage == parseInt($scope.totalProducts / parseInt($scope.pageSize))) {
                    $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                    $scope.pageDynamicCount = $scope.totalProducts;
                } else {
                    $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                    $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                    sessionStorage.setItem("pageDynCount", $scope.pageDynamicCount);
                }

            }
            //paging();
        };

        $scope.nextPageDisabled = function () {
            return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
        };

        $scope.range = function () {

            var rangeSize = 12;
            var ret = [];
            var start;
            start = $scope.currentPage;

            if (start > $scope.pageCount() - rangeSize) {
                start = $scope.pageCount() - rangeSize + 1;
            }
            for (var i = start; i < start + rangeSize; i++) {
                if (i >= 0) {
                    ret.push(i);
                }
            }

            if (ret.length > 1) //Hiding  pagination when page count is one 
                return ret;
        };

        $scope.setPage = function (n) {
            $scope.currentPage = n;

            if (n == parseInt($scope.totalProducts / parseInt($scope.pageSize))) {
                $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                $scope.pageDynamicCount = $scope.totalProducts;
            } else {
                $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                sessionStorage.setItem("pageDynCount", $scope.pageDynamicCount);
            }
            sessionStorage.setItem("currentPage", $scope.currentPage);
        };

        //get filtered data length
        $scope.getData = function () {
            return $filter('filter')($scope.Products, $scope.search);
        }

        $scope.numberOfPages = function () {
            return Math.ceil($scope.getData().length / $scope.pageSize);
        }

        // LeftMenu Categories filters
        function SearchItemsCategory(products, categoryType, CategoryIds) {

            var categories = "";
            $(".categories").find("input:checked").filter('.category').each(function (index) {
                categories = categories + $(this).prop('id') + ',';
            });

            var str = "";

            $.each(CategoryIds.split(','), function (index, value) {

                if (value.length > 0) {
                    if (categoryType == "format")
                        str += " (obj.Formats==" + value + ") ||";
                    else if (categoryType == "category") {
                        str += " (obj.Categories==" + value + ") ||";
                    }
                    else if (categoryType == "topic") {
                        var expr = "";
                        if (categories.split(',').length > 0) {

                            $.each(categories.split(','), function (index, topicCategoryId) {
                                if (topicCategoryId.length > 0) {
                                    expr += " (obj.TopicCode=='" + value + "') && (obj.TopicCategoryIds=='" + topicCategoryId + "') ||";
                                }
                            });
                        }
                        if (expr.length == 0) {
                            str += " (obj.TopicCode=='" + value + "') ||";
                        }
                        else {
                            str = str + expr;
                        }
                    }
                }
            });


            if (str.length > 0) {
                if (str.substring(str.length, str.length - 2) == "||") {
                    str = str.substring(0, str.length - 2);
                }
            }

            var items = $.grep(products, function (obj) {
                return eval(str);
            });

            return items;

        }

        //This fuction for filterig prdoducts formats after selecting Category or Topic an both.
        function FilterFormats(products, formatIds) {

            var str = "";

            $.each(formatIds.split(','), function (index, value) {

                if (value.length > 0) {
                    str += " (obj.Formats==" + value + ") ||";
                }
            });

            if (str.length > 0) {
                if (str.substring(str.length, str.length - 2) == "||") {
                    str = str.substring(0, str.length - 2);
                }
            }

            var items = $.grep(products, function (obj) {
                return eval(str);
            });
            return items;

        }

        $scope.BindProducts = function () {

            //getting selected categories
            $scope.Products = $scope.TempProducts;

            //format
            var filterItems = [];
            var formatIds = "";



            var selectedCategories = $(".categories").find("input:checked");
            var uniqueList = '';

            $('#selctedCatsNames').text('');
            if (selectedCategories.length > 0) {

                $(".categories").find("input:checked").filter('.format').each(function (index) {
                    formatIds = formatIds + $(this).prop('id') + ',';
                    uniqueList = uniqueList + "<span class='catTags'>" + $(this).next().text() + " <a href='javascript:;' data-catType='" + $(this).attr('class') + "' data-catId='" + $(this).prop('id') + "'>X</a></span>";
                });

                sessionStorage.setItem("Format", formatIds); //To maintain state on refresh 

                //end

                //Category
                var catProducts = [];
                var categoryIds = "";

                $(".categories").find("input:checked").filter('.category').each(function (index) {
                    categoryIds = categoryIds + $(this).prop('id') + ',';
                    uniqueList = uniqueList + "<span class='catTags'>" + $(this).next().text() + " <a href='javascript:;' data-catType='" + $(this).attr('class') + "' data-catId='" + $(this).prop('id') + "'>X</a></span>";
                });

                if (categoryIds.length > 0) {
                    sessionStorage.setItem("Category", categoryIds); //To maintain state on refresh 
                    var categoryItems = SearchItemsCategory($scope.Products, "category", categoryIds);
                    catProducts = categoryItems;

                }

                //Topic
                var topicIds = "";
                $(".categories").find("input:checked").filter('.topic').each(function (index) {
                    topicIds = topicIds + $(this).parent().find('#topicCode').val() + ',';
                    uniqueList = uniqueList + "<span class='catTags'>" + $(this).next().text() + " <a href='javascript:;' data-catType='" + $(this).attr('class') + "' data-catId='" + $(this).prop('id') + "'>X</a></span>";
                });

                //Member for

                if ($(".memberproducts").is(":checked"))
                    uniqueList = uniqueList + "<span class='catTags'>" + $(".memberproducts").next().text() + " <a href='javascript:;' data-catType='" + $(".memberproducts").attr('class') + "' data-catId='" + $(".memberproducts").prop('id') + "'>X</a></span>";

                if ($(".nonmemberproducts").is(":checked"))
                    uniqueList = uniqueList + "<span class='catTags'>" + $(".nonmemberproducts").next().text() + " <a href='javascript:;' data-catType='" + $(".nonmemberproducts").attr('class') + "' data-catId='" + $(".nonmemberproducts").prop('id') + "'>X</a></span>";



                var filtTex = "&nbsp;&nbsp;&nbsp;<b style='color:#000;'>Filtered by: </b>"
                $('#selctedCatsNames').html(filtTex).append(uniqueList);


                var CAll = "<span class='catTags'><a href='javascript:;'  data-catType='" + $(this).attr('class') + "' data-catId='All'>Clear All</a></span>";


                $('#selctedCatsNames').html(filtTex).append(uniqueList).append(CAll);

                if (topicIds.length > 0) {
                    var topicItems = SearchItemsCategory($scope.Products, "topic", topicIds);
                    sessionStorage.setItem("Topic", topicIds);
                    //To maintain state on refresh 
                    catProducts = topicItems;
                }

                //IF either of Topics and Categories not selected then we will filter  products based on selected format 
                if (categoryIds.length == 0 && topicIds.length == 0) {
                    filterItems = FilterFormats($scope.Products, formatIds);
                }
                else {
                    //IF either of Topics and Categories selected then we will filter  products after filtering category and topic selected format 
                    Array.prototype.push.apply(filterItems, catProducts);
                }
                if (!(typeof filterItems === "undefined")) {
                    //getting products on selected formats only 
                    if (formatIds.length > 0)
                        filterItems = FilterFormats(filterItems, formatIds);
                    //end

                    //console.log($(".categories").find("input:checked").find(".memberproducts,.nonmemberproducts"));
                    //var memberprod = $(".categories").find("input:checked").find(".memberproducts").length;

                    var count = 0;
                    if ($(".memberproducts").is(":checked")) {
                        count++;
                    }
                    if ($(".nonmemberproducts").is(":checked")) {
                        count++;
                    }
                    if (filterItems.length == 0 && categoryIds.length == 0 && topicIds.length == 0 && formatIds.length == 0) {
                        filterItems = $scope.Products;
                    }

                    if (count != 2) {

                        //Member Products filter
                        if ($(".memberproducts").is(":checked")) {
                            var memberProducts = $.grep(filterItems, function (n) {
                                return n.IsMemberOnly == true
                            });
                            sessionStorage.setItem("member", true);
                            $scope.Products = unique(memberProducts);
                        } //Non Member Products filter
                        else if ($(".nonmemberproducts").is(":checked")) {

                            var NonMemberProducts = $.grep(filterItems, function (n) {
                                return n.IsMemberOnly == false
                            });
                            sessionStorage.setItem("nonmember", true);
                            $scope.Products = unique(NonMemberProducts);

                        }
                        else {
                            $scope.Products = unique(filterItems);
                        }
                    }
                    else {
                        $scope.Products = unique(filterItems);
                    }

                    if ($scope.Products.length == 0) {
                        $('#loadMsg').show();
                        $('#loadMsg').text('No results found!');
                        $scope.pageStartIndex = 0;
                        $scope.pageDynamicCount = 0;
                        sessionStorage.getItem("pageDynCount", 0);
                    } else {
                        $('#loadMsg').hide();
                        $('#loadMsg').text('Loading Results...');
                        $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                    }
                }
            }
            else {
                //clearing
                sessionStorage.removeItem("Format");
                sessionStorage.removeItem("Category");
                sessionStorage.removeItem("Topic");
                sessionStorage.removeItem("member");
                sessionStorage.removeItem("nonmember");

            }
            try {
                $scope.totalProducts = $scope.Products.length;
            } catch (e) {

            }

            $scope.currentPage = 0;

            if (sessionStorage.getItem("currentPage") != null) {
                if (sessionStorage.getItem("currentPage")) {
                    $scope.currentPage = parseInt(sessionStorage.getItem("currentPage"));

                    if ($scope.pageSize == "all") {
                        if (sessionStorage.getItem("tp") >= $scope.totalProducts) {
                            $scope.pageDynamicCount = $scope.totalProducts;
                        } else if (sessionStorage.getItem("tp") == unique($scope.Products).length) {
                            $scope.pageDynamicCount = sessionStorage.getItem("tp");
                        } else {
                            $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                        }
                    }
                    else {
                        $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                    }
                }
            }

            $scope.Products = unique($scope.Products);

            if ($scope.Products.length == 0) {
                $('#loadMsg').show();
                $('#loadMsg').text('No results found!');
                $scope.pageStartIndex = 0;
                $scope.pageDynamicCount = 0;
                sessionStorage.getItem("pageDynCount", 0);
            } else {
                $('#loadMsg').hide();
                $('#loadMsg').text('Loading Results...');
                $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
            }

            if ($scope.pageSize > $scope.totalProducts) {
                $scope.pageDynamicCount = $scope.totalProducts;
            }

            $scope.totalProducts = $scope.Products.length;


            hide();
        }//BindProducts Method End

        $scope.getItemByCategory = function ($event) {

            try {
                var thisElem = $($event.target).parent();
            } catch (e) {

            }

            if ($(thisElem).find('input').prop('checked') != true) {
                $(thisElem).find('input').prop('checked', true);
            } else {
                $(thisElem).find('input').prop('checked', false);
            }

            ////hiding Banner
            //$("#show_banner").text('Show Banner');
            //$("#slides").hide();
            //showHide = 1;

            //To reset page
            if ($(thisElem).text().trim() != "Journal") {
                if(window.location.href==applicationUrl + "/Home/Publications")
                    window.location.href = applicationUrl;
                sessionStorage.setItem("currentPage", 0);
                sessionStorage.setItem("pageDynCount", $scope.productsPerPage);

                show();
                $scope.BindProducts();
            } else {
                //jAlert("Hey Ding Ding Fellow I am Conference! Not Product... What do you want from me!!!!");
                window.location.href = applicationUrl + "/Home/Publications";
                sessionStorage.removeItem("Format");
                sessionStorage.removeItem("Category");
                sessionStorage.removeItem("Topic");
                sessionStorage.removeItem("member");
                sessionStorage.removeItem("nonmember");
            }

        }

        function getDataInArray(array) {
            var names = [];
            $.each(array, function (i, d) {
                names.push(d.ProductName + " (" + d.ProductCode + ")");
            });

            return names;
        }

        //clear filters

        $scope.clsFil = function ($event) {
            var thisElm = $event.target;
            var clsFilterName = $(thisElm).attr('id');
            sessionStorage.removeItem(clsFilterName);
            $(thisElm).parent().parent().find('input[type="checkbox"]').prop('checked', false);
            $scope.listProducts();
        }

        // Search Filter by keyword & by select category
        $scope.SearchProducts = function (from) {

            if (from == 'topSearch')
                $("#search").val('');
            else
                $("#topSearch").val('');
            ////hide Banner
            //var selItem = '';
            //$("#show_banner").text('Show Banner');
            //$("#slides").hide();
            //showHide = 1;

            try {
                var productSearch = $("#search").val().trim();
            } catch (e) {

            }

            //topHeader Search start's from here
            var topSearch = $("#topSearch").val().trim();
            if (topSearch.length > 0) {
                var searchedProducts = factorialSearch($scope.TempProducts, topSearch);

                if (!(typeof searchedProducts === "undefined")) {

                    var Names = [];
                    Names = getDataInArray(searchedProducts);

                    $("#topSearch").autocomplete({
                        source: function (request, response) {
                            response(Names);
                            //console.log(Names)
                        },
                        select: function (event, ui) {

                            var items = $.grep($scope.TempProducts, function (obj) {

                                if (obj.ProductName + " (" + obj.ProductCode + ")" == ui.item.value)
                                    return obj.ProductName;
                            });

                            window.location = applicationUrl + '/Product/viewproduct/?ProductId=' + items[0].ProductId;
                        }
                    });
                }

            }//topHeader Search End from here
            else if (productSearch.length > 0) { //Products search control start 

                $scope.Products = $scope.TempProducts;
                $('#loadMsg').hide();
                var searchWord = $("#search").val().trim();
                var category = $("#CategorySearch").val();

                //if "All" 
                if (category == "All") {

                    //Searching with All option
                    var searchedProducts = factorialSearch($scope.Products, searchWord);

                    if (!(typeof searchedProducts === "undefined")) {
                        $scope.Products = searchedProducts;
                        var Names = [];
                        Names = getDataInArray(searchedProducts);

                        $("#search").autocomplete({
                            source: function (request, response) {
                                response(Names);
                            },
                            select: function (event, ui) {
                                var items = $.grep($scope.TempProducts, function (obj) {

                                    if (obj.ProductName + " (" + obj.ProductCode + ")" == ui.item.value)
                                        return obj.ProductName;
                                });

                                window.location = applicationUrl + '/Product/viewproduct/?ProductId=' + items[0].ProductId;

                            }

                        });
                    }

                }//"All" End
                else { //Other than "All" Option Start
                    var catArr = category.split(':');
                    var products = $.grep($scope.Products, function (obj, index) {

                        if (catArr[0] == "format") {
                            return obj.Formats.toLowerCase() == catArr[1]
                        }
                        else if (catArr[0] == "category") {
                            return obj.Categories.toLowerCase() == catArr[1]
                        }
                        else {
                            return obj.TopicCode.toLowerCase() == catArr[1].toLowerCase()
                        }
                    });
                    $scope.Products = unique(products);

                    //Searching with Category 
                    var searchedProducts = factorialSearch(products, searchWord);

                    //Search Dropdown other than all option
                    if (!(typeof searchedProducts === "undefined")) {
                        var Names = [];
                        Names = getDataInArray(searchedProducts);
                        $("#search").autocomplete({
                            source: function (request, response) {
                                response(Names);
                            },
                            select: function (event, ui) {
                                selItem = $.grep($scope.TempProducts, function (obj) {

                                    if (obj.ProductName + " (" + obj.ProductCode + ")" == ui.item.value)
                                        return obj;
                                });
                                $scope.$apply(function () {
                                    $scope.Products = selItem;
                                    $scope.Products = unique($scope.Products);
                                    $scope.totalProducts = $scope.Products.length;
                                    $scope.currentPage = 0;
                                });
                                //Product filter and search actions
                                if ($scope.Products.length == 0) {
                                    $('#loadMsg').show();
                                    $('#loadMsg').text('No results found!');
                                    $scope.pageStartIndex = 0;
                                    $scope.pageDynamicCount = 0;
                                    sessionStorage.getItem("pageDynCount", 0);
                                } else {
                                    $('#loadMsg').hide();
                                    $('#loadMsg').text('Loading Results...');
                                    if ($scope.totalProducts < $scope.pageSize) {
                                        $scope.pageDynamicCount = $scope.totalProducts;
                                    } else {
                                        $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                                    }
                                    $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                                }
                            }
                        });
                    }

                }//Other than "All" Option End
                $scope.Products = unique($scope.Products);
                $scope.totalProducts = $scope.Products.length;
                $scope.currentPage = 0;

                if ($scope.Products != null) {
                    //Product filter and search actions
                    if ($scope.Products.length == 0) {
                        $('#loadMsg').show();
                        $('#loadMsg').text('No results found!');
                        $scope.pageStartIndex = 0;
                        $scope.pageDynamicCount = 0;
                        sessionStorage.getItem("pageDynCount", 0);
                    } else {
                        $('#loadMsg').hide();
                        $('#loadMsg').text('Loading Results...');
                        if ($scope.totalProducts < $scope.pageSize || $scope.pageSize == 'all') {
                            $scope.pageDynamicCount = $scope.totalProducts;
                        } else {
                            $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                        }
                        $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                    }
                }
            }
            else {
                if ($scope.pageSize == 'all') {
                    $scope.Products = unique($scope.TempProducts);
                    $scope.totalProducts = $scope.Products.length;
                    $scope.currentPage = 0;
                    $scope.pageDynamicCount = $scope.totalProducts;
                }
            }
        }

        //per page value update when Per page drop down change
        $scope.ProductsPerPage = function () {

            if ($scope.pageSize == "all") {
                $scope.productsPerPage = 0;
                $scope.currentPage = 0;
                //Saving pagesize
                $scope.pageStartIndex = 1;
                $scope.pageDynamicCount = $scope.Products.length;
                sessionStorage.setItem("tp", $scope.Products.length);
                sessionStorage.setItem("pagesize", $scope.productsPerPage);
            }
            else {
                if ($scope.pageSize > $scope.Products.length) {
                    $scope.pageDynamicCount = $scope.Products.length;
                } else {
                    $scope.productsPerPage = $scope.pageSize;
                    $scope.pageStartIndex = 1;
                    $scope.pageDynamicCount = $scope.productsPerPage;
                    $scope.currentPage = 0;

                    //Saving pagesize 
                    sessionStorage.setItem("pagesize", $scope.productsPerPage);
                }
            }
        }

        //Selected Product
        $scope.getSelProduct = function (event) {
            $scope.pdId = event.target.id;
            $($scope.Products).filter(function (index, value) {
                if (value.ProductId == $scope.pdId) {
                    $scope.selectedProduct = value;
                };
            });

            setTimeout(function () {
                $('.product_quick_view').show();
            }, 100);
        }

        //Getting Cart details   
        $scope.TotalPrice = 0;

        //Adding Product To Cart
        $scope.getCartData = function () {
            urlService.dataProvider(cartDetailsMethod, "POST", '').success(function (data) {

                if (data == "ADDED_FAIL") {
                    $scope.CartDetails = [];
                    $scope.TotalPrice = 0;
                    $scope.TotalItems = 0;
                    $scope.CartDetailsLength = $scope.CartDetails.length;
                    jAlert('Unable to get cart details,Please try later.');
                }
                else if (data != "NO_DETAILS_FOUND") {

                    var totalCartPrice = 0, totalItems = 0;

                    $.each(data, function (index, obj) {
                        if ($scope.sesUserIsMember == '1') {
                            totalCartPrice = totalCartPrice + (obj.Quantity * obj.product.MemberPrice);
                        } else {
                            totalCartPrice = totalCartPrice + (obj.Quantity * obj.product.Price);
                        }
                        totalItems = totalItems + (obj.Quantity);
                    });

                    $scope.CartDetails = data;
                    $scope.CartDetailsLength = $scope.CartDetails.length;
                    $scope.TotalPrice = totalCartPrice;
                    $scope.TotalItems = totalItems;


                } else {

                    $scope.CartDetails = [];
                    $scope.TotalItems = 0;
                    $scope.TotalPrice = 0;
                    $scope.CartDetailsLength = $scope.CartDetails.length;
                }

            });
        };

        $scope.getCartData();
        //AddToCart
        $scope.AddToCart = function ($event, from) {
            productCart.ProductAddToCart($event.target.id, $scope, from, $event);
        };

        //Open Cart
        $scope.OpenCart = function () {
            /* selecting first tab always*/
            $(".stepContent").removeClass("step_active");
            $("#step1_MyCart").addClass("step_active");
            //Gettings Cart Information if available
            $scope.getCartData();

            //Gettings user address
            $scope.getAddressData();

            //Gettings user CreditCatds
            $scope.getCreditCardDetails();

            //Gettings ship Via Code
            $scope.shipViaCodeClient();

            setTimeout(function () {
                $('#CartPopUp').addClass('is-visible');
            }, 500);

        }

        //Update Cart
        $scope.UpdateToCart = function () {
            if ($('#shipViaCodeDD').val() == "") {
                $('#shipViaCodeDD').css('box-shadow', '0px 0px 2px #FF0000');
            } else {
                $('#shipViaCodeDD').removeAttr('style');
                $scope.billingAddIdDiv = false;
                $scope.shippingAddIdDiv = false;
            }

            if ($(".cartdetails").length > 0) {
                $('#popLoader').show();
            } else {
                $('#alrtMsg').empty();
                var txtLgn = "No products to update!";
                $('#alrtMsg').show().html(txtLgn);
                return;
            }

            var errorFlag = false;
            $(".cartdetails").each(function () {
                var i = 0;
                var avlQty = $(this).next().text();
                var quantity = $(this).val();
                var productid = $(this).prop('id');
                var from = "update";
                var customOrStandard = $scope.viewUmbrellProductDD;
                var shippreference = '';
                if ($scope.shipViaCodeDD != undefined)
                    shippreference = $scope.shipViaCodeDD.Code;

                var cartArgu = { ProductId: productid, Quantity: quantity, From: from, StrCustomOrStandard: customOrStandard, shipviacode: shippreference };
                //var cartArgu = { ProductId: productid, Quantity: quantity, From: from, StrCustomOrStandard: customOrStandard };
                if ($(this).attr("data-Inventoried") == "true") {
                    if (quantity != 0) {
                        if (parseFloat(avlQty) >= parseFloat(quantity)) {

                            urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                                $scope.getCartData();
                                $('#popLoader').hide();
                            });
                        } else {
                            //if ($scope.product.BackorderAvailable == true) {
                            if ($scope.CartDetails[i].product.BackorderAvailable == true) {
                                urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                                    $scope.getCartData();
                                    $('#popLoader').hide();
                                });
                            } else {
                                $('#popLoader').hide();
                                jAlert(' This Product Stock Availability upto ' + avlQty + '!');
                                errorFlag = true;
                                return false;
                            }
                        }
                    } else {
                        //if ($scope.product.BackorderAvailable == true) {
                        if ($scope.CartDetails[i].product.BackorderAvailable == true) {
                            urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                                $scope.getCartData();
                                $('#popLoader').hide();
                            });
                        } else {
                            $('#popLoader').hide();
                            jAlert(' Product Available in minimum quantities of 1 !');
                            errorFlag = true;
                            return false;
                        }

                    }
                    i++;
                } else {
                    urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {
                        $scope.getCartData();
                        $('#popLoader').hide();
                    });
                }
            });
            return errorFlag;
        }

        //Delete Cart
        $scope.DeleteCart = function (productid) {
            productCart.ProductAddToCart(productid, $scope, 'delete', '');
        };

        //Add WishList Products
        var xId = [];
        $scope.AddToWishList = function (wId, CustomerID, x) {
            var wishlistId = '';
            //select & unselect wishlist icon
            $.grep($scope.Products, function (i) {
                if (i.ProductId == wId) {
                    if (i.IsInWishList != true) {
                        i.IsInWishList = true;
                    }
                    else {
                        i.IsInWishList = false;
                    }
                }
            });

            var addWishArgu = { ProductId: wId, CustomerID: CustomerID, From: 1 };
            urlService.dataProvider(saveWishlistMethod, "POST", addWishArgu).success(function (status) {

                if (status == 3) {//Already Added
                }

            });
        };

        //get WishList Products
        $scope.GetWishListItems = function (customerId) {
            var getWishListArgu = { CustomerID: customerId };
            urlService.dataProvider(getWishlistMethod, "POST", getWishListArgu).success(function (data) {
                $scope.WishListItems = unique(data);
                $.grep($scope.WishListItems, function (i) {
                    xId.push(i.ProductId);
                });

                //after reload Wishlist icon active state
                $.grep(xId, function (item) {
                    $.grep($scope.Products, function (y) {
                        if (y.ProductId == item) {
                            if (y.IsInWishList != true)
                                y.IsInWishList = true;
                            else
                                y.IsInWishList = false;
                        }
                    });
                });

            });//for
        }

        //Get Shipping & Billing Address
        var shipCustId = '';
        $scope.getAddressData = function () {
            urlService.dataProvider(GetAddressesMethod, "POST", '').success(function (data) {
                if (data != "ADDED_FAIL") {
                    $scope.userAddress = data;
                    //console.log($scope.userAddress);

                    var addListCount = $scope.userAddress.AddressList.length;
                    //console.log($scope.userAddress)
                    //console.log($scope.userAddress.AddressList[0].FormattedAddress)
                    // Adding ShipToFlag default to scope ShippingAddresses
                    $scope.ShippingAddresses = [];
                    if (sessionStorage.getItem('ShippingIndex') != null) {
                        if (sessionStorage.getItem('ShippingIndex').length != 0) {
                            var sessionShippingIndexVal = $scope.userAddress.AddressList[sessionStorage.getItem('ShippingIndex')];
                            $scope.ShippingAddresses.push(sessionShippingIndexVal);
                        } else {
                            $.grep($scope.userAddress.AddressList, function (item) {
                                if (item.ShipToFlag == true) {
                                    $scope.ShippingAddresses.push(item);
                                    shipCustId = item.CustomerAddressId;
                                    sessionStorage.setItem('ShippingCustId', item.CustomerAddressId);
                                }
                            });
                        }
                    }
                    else {
                        $.grep($scope.userAddress.AddressList, function (item) {
                            if (item.ShipToFlag == true) {
                                $scope.ShippingAddresses.push(item);
                                shipCustId = item.CustomerAddressId;
                                sessionStorage.setItem('ShippingCustId', item.CustomerAddressId);
                            }
                        });
                    }

                    // Adding BillToFlag default to scope BillingAddresses
                    $scope.BillingAddresses = [];
                    if (sessionStorage.getItem('BillingIndex') != null) {
                        if (sessionStorage.getItem('BillingIndex').length != 0) {
                            var sessionBillingIndexVal = $scope.userAddress.AddressList[sessionStorage.getItem('BillingIndex')];
                            $scope.BillingAddresses.push(sessionBillingIndexVal);
                        } else {
                            $.grep($scope.userAddress.AddressList, function (item) {
                                if (item.BillToFlag == true) {
                                    $scope.BillingAddresses.push(item);
                                    sessionStorage.setItem('billingAdd', $scope.BillingAddresses[0].FormattedAddress);
                                    sessionStorage.setItem('BillingCustId', item.CustomerAddressId);
                                }
                            });
                        }
                    } else {
                        $.grep($scope.userAddress.AddressList, function (item) {
                            if (item.BillToFlag == true) {
                                $scope.BillingAddresses.push(item);
                                sessionStorage.setItem('BillingCustId', item.CustomerAddressId);
                                sessionStorage.setItem('billingAdd', $scope.BillingAddresses[0].FormattedAddress);
                            }
                        });
                    }

                    if ($scope.ShippingAddresses.length == 0)
                        $scope.ShippingAddresses = "Shipping Address is not available!";

                    if ($scope.BillingAddresses.length == 0)
                        $scope.BillingAddresses = "Billing Address is not available";

                    //Set Default address for Shipping and Billing
                    $scope.setDefaultAddress = function ($event, $index, container) {
                        $('#popLoader').show();
                        var addCurrType = $($event.target).attr('data-type');
                        var addCurrId = $($event.target).attr('data-addid');
                        urlService.dataProvider(setAddress, "POST", { addId: addCurrId, addtype: addCurrType }).success(function () {
                            if (data != "fail") {
                                //jAlert("Address Changed Successfully!");
                                $scope.getCartData();
                                $('#popLoader').hide();
                            }
                            //else{
                            //    jAlert("Please try again!");
                            //}

                        }).error(function (ex) {
                            $('#popLoader').hide();
                        });
                        //console.log($($event.target).parent())
                        if (addCurrType == "Billing") {
                            $scope.BillingAddresses = [];
                            $.grep($scope.userAddress.BillingAddresses, function (item) {
                                item.BillToFlag = false
                            });
                            $scope.userAddress.BillingAddresses[$index].BillToFlag = "true";
                            var addressIndex = $scope.userAddress.BillingAddresses[$index];
                            $scope.BillingAddresses.push(addressIndex);
                            sessionStorage.setItem('BillingIndex', $index);
                            sessionStorage.setItem('BillingCustId', $scope.userAddress.BillingAddresses[$index].CustomerAddressId);
                            sessionStorage.setItem('billingAdd', $scope.BillingAddresses[$scope.BillingAddresses.length - 1].FormattedAddress);
                            $("#billingAddressList").find(".shwAddress").find(".default").hide();
                            $("#billingAddressList").find(".useAdd").removeClass("btn_active");
                            $($event.target).parent().find(".default").removeClass('ng-hide').show();
                            $("#billingAddressList").find($event.target).addClass("btn_active");
                        }

                        if (addCurrType == "Shipping") {
                            $scope.ShippingAddresses = [];
                            $.grep($scope.userAddress.ShippingAddresses, function (item) {
                                item.ShipToFlag = false
                            });
                            $scope.userAddress.ShippingAddresses[$index].ShipToFlag = "true";
                            var addressIndex = $scope.userAddress.ShippingAddresses[$index];
                            shipCustId = $scope.userAddress.ShippingAddresses[$index].CustomerAddressId;
                            sessionStorage.setItem('ShippingIndex', $index);
                            sessionStorage.setItem('ShippingCustId', $scope.userAddress.ShippingAddresses[$index].CustomerAddressId);
                            $scope.ShippingAddresses.push(addressIndex);
                            $("#shippingAddressList").find(".shwAddress").find(".default").hide();
                            $("#shippingAddressList").find(".useAdd").removeClass("btn_active");
                            $($event.target).parent().find(".default").removeClass('ng-hide').show();
                            $("#shippingAddressList").find($event.target).addClass("btn_active");
                        }
                    }
                }

                //$(".shwAddress").width(addListCount * 270);
                $scope.taxShippingPrice = function (shippreference) {
                    var shippreference = '';
                    if ($scope.shipViaCodeDD != undefined)
                        shippreference = $scope.shipViaCodeDD.Code;

                    shipCustId = sessionStorage.getItem('ShippingCustId');
                    return $http({
                        method: "POST",
                        url: applicationUrl + '/Order/GetTax',
                        params: { ShippingId: shippreference },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    }).success(function (data) {
                        if (data != "ADDED_FAIL") {
                            $scope.getTaxData = data;
                            $scope.shippingHandling = data.TotalShipping;
                            $scope.Tax = data.TotalTax;
                            $scope.CouponSaving = data.Coupons.length == 0 ? null : data.Coupons[0].Amount;
                            $scope.CouponSavingDesc = data.Coupons.length == 0 ? null : data.Coupons[0].Description;
                        } else {
                            jAlert('Internal Technical Error. Please try again!');
                            return
                        }
                        $('#popLoader').hide();
                    }).error(function (x) {
                        jAlert(x);
                    });
                }

            });
        };
        // End

        //Get Credit Card Details
        $scope.getCreditCardDetails = function () {
            urlService.dataProvider(GetCreditCardMethod, "POST", "").success(function (data) {
                $scope.cCard = data;
                //console.log($scope.cCard.length);

                if ($scope.cCard.length == 0)
                    $("#useOtherVal").text("true");
            });
        };

        //End

        //Create Order
        $scope.placeOrder = function () {
            if (($scope.TotalPrice + $scope.Tax + $scope.shippingHandling) == 0) {
                createOrderItem();
            }
            else if ($('input[id="useOther"]').is(':checked') || $("#useOtherVal").text() == "true") {
                $scope.cValidation();
                if (valid == true) {
                    if ($("#saveCCCard").is(":checked") == true) { //Save CreditCard Details
                        saveCreditCardDetails();
                    }
                    else {
                        createOrderItem();
                    }
                }
            } else {
                createOrderItem();
            }

            function saveCreditCardDetails() {
                $('#popLoader').show();
                $('.errorMsg').empty();
                var selectedRadioValue = $('input[name=cardType]:checked').val();

                var CardType = selectedRadioValue,
                    CardHolderName = CCName.value,
                    CreditCardNumber = CCNumber.value,
                    CreditCardCVVNumber = CCcvv.value,
                    ExpireMonth = $scope.months,
                    ExpireYear = $scope.years;

                var saveCCArgu = {
                    CardType: CardType,
                    CardNumber: CreditCardNumber,
                    Cvv: CreditCardCVVNumber,
                    ExpDate: ExpireMonth,
                    ExpYear: ExpireYear,
                    NameOnCard: CardHolderName
                };
                urlService.dataProvider(addCCardMethod, "POST", saveCCArgu).success(function (data) {
                    if (data != true) {
                        jAlert('Please enter valid details!');
                        $('#popLoader').hide();
                        clearCC();
                    }
                    else {
                        createOrderItem();
                    }
                }).error(function (errorx) {
                    clearCC();
                    $('#popLoader').hide();
                    jAlert(errorx);
                });
            }

            function createOrderItem() {
                $('#popLoader').show();
                $('.errorMsg').empty();
                var selectedRadioValue = $('input[name=cardType]:checked').val();
                var CardType = selectedRadioValue,
                    CardHolderName = CCName.value,
                    CreditCardNumber = CCNumber.value,
                    CreditCardCVVNumber = CCcvv.value,
                    ExpireMonth = $scope.months,
                    ExpireYear = $scope.years,
                    userOption = $("#saveCCCard").is(":checked") == true ? true : false;

                var saveCCArgu = {
                    CreditCardType: CardType,
                    CreditCardNumber: CreditCardNumber,
                    Cvv2: CreditCardCVVNumber,
                    ExpirationMonth: ExpireMonth,
                    ExpirationYear: ExpireYear,
                    NameOnCard: CardHolderName,
                    WantToSave: userOption
                };

                if ($scope.getTaxData.ValidationIssues != null) {
                    var validationRes = [];
                    var valiIssuItems = $(".taxValidationsIssues");
                    $(valiIssuItems).each(function (index) {
                        var thisKey = $(this).find("p.msg").attr("data-key");
                        var tempObj = {
                            Key: thisKey,
                            SeelctedValue: $(this).find("input[name='" + thisKey + "']:checked").val()
                        };
                        validationRes.push(tempObj);
                    });
                }

                var billingAddId = sessionStorage.getItem("BillingCustId");   //$('input[name="billingAddId"]:checked').attr('id');
                var shippingAddId = sessionStorage.getItem("ShippingCustId"); //$('input[name="shippingAddId"]:checked').attr('id');
                var ccId = $('input[id="ccType"]').is(':checked') == true ? $('input[id="ccType"]').attr('data-PartialCardNumber') : '';
                var tax = $("#tax").text().replace('$', '');
                var shippingPrice = $("#shippingHandling").text().replace('$', '');
                var shippreference = $scope.shipViaCodeDD.Code;   //Added By Rakesh

                //$('.cart-popup').removeClass('is-visible');
                show();
                var placeOrderArgu = {
                    billingAddId: billingAddId,
                    shippingAddId: shippingAddId,
                    ccId: ccId,
                    TotalTax: tax,
                    TotalShipping: shippingPrice,
                    shipViaCode: shippreference,
                    CreditCardInfo: $('input[id="useOther"]').is(':checked') == true || $("#useOtherVal").text() == "true" ? JSON.stringify(saveCCArgu) : null,
                    ValidationResponses: $scope.getTaxData.ValidationIssues != null ? JSON.stringify(validationRes) : ''
                };
                urlService.dataProvider(createOrderMethod, "POST", placeOrderArgu).success(function (d) {
                    $('#popLoader').hide();
                    //if (d != "ADDED_FAIL") {
                    if (d.Success == true) {
                        $scope.finalOrderNumber = d.Items.OrderNumber;
                        sessionStorage.setItem('orderNumber', $scope.finalOrderNumber);
                        $('.cart-popup').removeClass('is-visible');
                        window.location = applicationUrl + '/Product/orderConfirmation';
                        clearCC();
                    } else {
                        hide();
                        //clearCC();
                        //jAlert('Unable to place order Please try again!');
                        jAlert(d.ErrorMessage);
                        if (d.Message == 'No Product in Cart !')
                        {
                            $scope.getCartData();
                            $(".stepContent").removeClass("step_active");
                            $("#step1_MyCart").addClass("step_active");
                        }
                    }
                }).error(function (x) {
                    $('#popLoader').hide();
                    hide();
                    clearCC();
                    jAlert(x.ErrorMessage);
                });
            }
        };
        //add Credit Card
        //Months array
        $scope.monthList = ["Month", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        $scope.months = $scope.monthList[0];

        //get Next 100 years and store into array var
        var years = [];
        var i;
        var getYear = new Date().getFullYear();
        for (i = 0; i <= 100; i++) {
            years.push(getYear);
            getYear = getYear + 1;
        }
        years.unshift('Year');
        $scope.yearList = years;
        $scope.years = $scope.yearList[0];

        var valid = true;
        $scope.cValidation = function () {
            debugger;
            valid = '';
            

            if (CCName.value == '') {
                $('#CCName').next().text('Please enter the Card Holder name!');
                valid = false;
            } else {
                $('#CCName').next().empty();
            }
            if (CCNumber.value == '') {
                $('#CCNumber').next().text('Please enter the Credit Card Number!');
                valid = false;
            } else {
                $('#CCNumber').next().empty();
            }
            if (CCcvv.value == '') {
                $('#CCcvv').next().text('Please enter the CVV Number!');
                valid = false;
            } else {
                $('#CCcvv').next().empty();
            }
            if (!$('input[name=cardType]').is(':checked')) {
                $('input[name=cardType]').parent().find('.errorMsg').text('Please select card type!');
                $('#CCNumber').next().text('Please enter valid Credit Card Number!');
                valid = false;

            } else {
                $('input[name=cardType]').parent().find('.errorMsg').empty();
            }
            if ($scope.months == 'Month') {
                $('#months').next().text('Please select the month!');
                valid = false;
            } else {
                $('#months').next().empty();
            }
            if ($scope.years == 'Year') {
                $('#years').next().text('Please select the Year!');
            } else {
                $('#years').next().empty();
            }

            var today, someday;
            var exMonth = $scope.months;
            var exYear = $scope.years;
            today = new Date();
            someday = new Date();
            someday.setFullYear(exYear, exMonth, 1);

            if (someday < today) {
                $('#years').next().text("The expiry date is before today's date. Please select a valid expiry date!");
                valid = false;
            } else {
                $('#years').next().empty();
            }

            if (valid.length == 0) {
                valid = true
            } else {
                valid = false
            }

            return valid;
        };

        //End

        //Getting Countries
        $scope.getCountries = function () {
            urlService.dataProvider(getCountryMethod, 'POST', '').success(function (data) {
                var CountryList = $.grep(data, function (i) {
                    return i.CountryCode != "[ALL]";
                });

                $scope.CountryList = CountryList.sort()
                //  $scope.Countrys = $scope.Countrys["USA"];

            });
        };

        //Getting States
        $scope.getStates = function () {
            urlService.dataProvider(getStateMethod, 'POST', '').success(function (data) {
                $scope.StateList = data;
                $scope.TmpStateList = data;
                //$scope.States = $scope.StateList[0];
            });
        };

        $scope.billingAddIdDiv = false;
        $scope.shippingAddIdDiv = false;

        $scope.addBtnClick = function (from) {
            if (from == "Shipping") {
                $scope.billingAddIdDiv = false;
                $scope.shippingAddIdDiv = true;
                $scope.addressType = "Shipping Address";
                setTimeout(function () {
                    $("#Countrys").val("USA");
                    $("#Countrys").trigger("change");
                }, 500)
            } else {
                $scope.billingAddIdDiv = true;
                $scope.shippingAddIdDiv = false;
                $scope.addressType = "Billing Address";
                setTimeout(function () {
                    $("#Countrys").val("USA");
                    $("#Countrys").trigger("change");
                }, 500)
            }
            $(".actions").hide();
        };

        $scope.cancelBtnClick = function () {
            $scope.billingAddIdDiv = false;
            $scope.shippingAddIdDiv = false;
            $scope.clearForm();
        };

        $scope.clearForm = function () {
            $scope.addressType = $scope.shippingAddIdDiv == true ? 'Shipping Address' : 'Billing Address';
            $scope.Countrys.CountryDescription = '';
            $scope.Countrys.CountryCode = '';
            $scope.address1 = '';
            $scope.address2 = '';
            $scope.city = '';
            $scope.States = '';
            $scope.postCode = '';
        };


        //Selecty Country code to filter states list
        $scope.onCountryChange = function (a) {
            $scope.inputEnbl = false;
            var AllCountry = $('#Countrys').val();

            if (AllCountry == "") {
                urlService.dataProvider(getStateMethod, 'POST', '').success(function (data) {
                    $scope.StateList = data;
                    $scope.States = $scope.StateList;
                });
                return
            }
            //filterting states based on Country selection
            var result = $.grep($scope.TmpStateList, function (e) { return e.CountryCodeString == a.CountryCode });

            if (result.length != 0) {
                $scope.StateList = result;
                $scope.States = $scope.StateList;
                //console.log($scope.States)
            } else {
                //if states not available
                //$scope.StateList = [{ StateDescription: 'No States Available' }];
                $scope.inputEnbl = true;
                //console.log(typeof $("input#States").val())
                setTimeout(function () {
                    $("input#States").val("");
                    $("input#States").attr('placeholder','State');
                }, 50)
            }

        };
        var stateCode = $('#States').val();

        var valid = true;

        //Address Form Validations
        $scope.validations = function () {
            valid = '';
            if ($('#addressType').val() == "") {
                $('#addressType').next().text('Please select the Address Type!');
                valid = false;
            } else {
                $('#addressType').next().empty();
            }

            if ($('#Countrys').val() == '') {
                $("#Countrys").next().text('Please select Country!');
                valid = false;
            } else {
                $('#Countrys').next().empty();
            }

            if ($('#States').val() == "") {
                if ($scope.inputEnbl != true)
                    $("#States").next().text('Please select State!');
                else
                    $("#States").next().text('Please Enter State!');
                valid = false;
            } else {
                $('#States').next().empty();
            }
            if ($('#States').val() == "undefined") {
                stateCode = '';
                valid = false;
            } else {
                stateCode = $('#States').val();
            }

            if (address1.value == '') {
                $("#address1").next().text('Please enter the Address!');
                valid = false;
            } else {
                $('#address1').next().empty();
            }

            if (city.value == '') {
                $("#city").next().text('Please enter the City!');
                valid = false;
            } else {
                $('#city').next().empty();
            }

            if (postCode.value == '') {
                $("#postCode").next().text('Please enter the Postal Code!');
                valid = false;
            } else {
                $('#postCode').next().empty();
            }

            if (valid.length == 0) {
                valid = true
            } else {
                valid = false
            }

            return valid;
        };

        //Inserting Address
        $scope.addAddress = function () {
            $('#popLoader').show();
            $scope.validations();
            if (valid == true) {
                $('.errorMsg').empty();

                var newAddress = [{
                    addressType: $scope.addressType,
                    Country: $scope.Countrys.CountryDescription,
                    CountryCode: $scope.Countrys.CountryCode,
                    Address1: $scope.address1,
                    Address2: $scope.address2 || "",
                    City: $scope.city,
                    State: $("#States").val(),//,$scope.States.StateCode,
                    PostalCode: $scope.postCode
                    //Address1: address1.value,
                    //Address2: address2.value,
                    //City: city.value,
                    //State: stateCode,
                    //PostalCode: postCode.value
                }];

                var saveAddArgu = { AddressObj: newAddress }
                urlService.dataProvider(addAddressMethod, "POST", saveAddArgu).success(function (data) {

                    if (data != "ADDED_FAIL") {
                        $('#popLoader').hide();
                        jAlert('Address Added Successfully!');
                        $('#addAddress').hide();
                        $('.actions').show();
                        $scope.addressType = '';
                        $scope.Countrys.CountryDescription = '';
                        $scope.Countrys.CountryCode = '';
                        $scope.address1 = '';
                        $scope.address2 = '';
                        $scope.city = '';
                        $scope.States = $scope.StateList[0];
                        $scope.postCode = '';
                        //Update the existing address after new address added - Start
                        urlService.dataProvider(GetAddressesMethod, "POST", '').success(function (d) {
                            $scope.userAddress = d;
                            $.grep($scope.userAddress.AddressList, function (item) {
                                item.BillToFlag = false;
                                item.ShipToFlag = false;
                            });

                            $.grep(d.AddressList, function (i) {
                                if (i.CustomerAddressId == data.CusAddressId) {
                                    if ($(addressType).val() == "Billing Address") {
                                        i.BillToFlag = true;
                                        $scope.BillingAddresses = [];
                                        $scope.BillingAddresses.push(i);
                                        //console.log($scope.BillingAddresses);
                                        sessionStorage.setItem('billingAdd', $scope.BillingAddresses[0].FormattedAddress);
                                        sessionStorage.setItem('BillingCustId', data.CusAddressId);
                                    } else {
                                        //if ($(addressType).val() == "Shipping Address") {
                                        i.ShipToFlag = true;
                                        $scope.ShippingAddresses = [];
                                        $scope.ShippingAddresses.push(i);
                                        sessionStorage.setItem('ShippingAdd', $scope.ShippingAddresses[0].FormattedAddress);
                                        sessionStorage.setItem('ShippingCustId', data.CusAddressId);
                                    }
                                    return
                                }
                                //    }
                            });
                            $scope.billingAddIdDiv = false;
                            $scope.shippingAddIdDiv = false;
                        });//End

                    } else {
                        $('#popLoader').hide();
                        //jAlert('Please enter valid details!');
                        jAlert('Address not found');
                    }
                }).error(function (x) {
                    $('#popLoader').hide();
                    jAlert(x);
                });
            } else {
                $('#popLoader').hide();
                return
            }
        };

        //Get Param by regular Expression
        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        };

        $scope.searchLoad = function () {
            var wL = window.location + '';
            var wLArray = wL.split('/');
            var indexUrl = wLArray.indexOf("search");
            if (wLArray[indexUrl] == "search") {
                var topSearch = $("#topSearch").val(getParameterByName("SearchValue"));
                $scope.SearchProducts();
            }
        };

        function ClearFillter() {
            sessionStorage.removeItem("Format");
            sessionStorage.removeItem("Category");
            sessionStorage.removeItem("Topic");
            sessionStorage.removeItem("nonmember");
            sessionStorage.removeItem("member");
        };

        //ng-repeat callback function
        $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
            slideShow();
            if ($scope.sesCustomerId != '') {
                $scope.GetWishListItems($scope.sesCustomerId);
            }
            //$scope.querySearch();
        });

        $('#search').on('input', function (e) {
            if ('' == this.value) {
                $scope.listProducts();
                $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
            }
        });
        show();
        //delay in function, to get the DOM elements

        if (window.location.search != '') {
            $timeout(function () {
                $scope.querySearch = function () {
                    var count = 0;
                    var winSearchStr = window.location.search;
                    var searchValue = winSearchStr.replace('?', '').split('=');
                    if (window.location.search != '') {
                        if (searchValue[1] == "all") {
                            $('.' + searchValue[0]).attr("checked", true);
                        } else {
                            var catItemsList = searchValue[1];
                            var filterItems = catItemsList.split(',');
                            //start filtering the query string
                            $.grep(filterItems, function (item, index) {
                                //Category section
                                if (searchValue[0].toLowerCase() == "format") {
                                    $.grep($scope.catList.Formats, function (j) {
                                        if (j.Description.toLowerCase() == decodeURIComponent(item).toLowerCase()) {
                                            $('.' + searchValue[0]).each(function () {
                                                if ($(this).attr('id') == j.FormatId)
                                                    $(this).attr("checked", true);
                                            });
                                            //console.log(j.FormatId);
                                        }
                                    });
                                    return
                                }
                                //Category section
                                if (searchValue[0].toLowerCase() == "category") {
                                    $.grep($scope.catList.Categories, function (e) {
                                        if (e.CategoryName.toLowerCase() == decodeURIComponent(item).toLowerCase()) {
                                            $('.' + searchValue[0]).each(function () {
                                                if ($(this).attr('id') == e.CategoryId)
                                                    $(this).attr("checked", true);
                                            });
                                            //console.log(e.CategoryId);
                                        }
                                    });
                                    return
                                }
                                //Topic section
                                if (searchValue[0].toLowerCase() == "topic") {
                                    $.grep($scope.catList.Topics, function (t) {
                                        if (t.TopicDescription.toLowerCase() == decodeURIComponent(item).toLowerCase()) {
                                            $('.' + searchValue[0]).each(function () {
                                                if ($(this).attr('id') == t.TopicID)
                                                    $(this).attr("checked", true);
                                            });
                                            //console.log(t.TopicID);
                                        }
                                    });
                                    return
                                }
                                //Member For section
                                if (searchValue[0].toLowerCase() == "membertype") {
                                    //$.grep($scope.catList.Topics, function (j) {
                                    if (decodeURIComponent(item).toLowerCase() == "memberproducts")
                                        $('input[id="memberUser"]').attr("checked", true);
                                    else
                                        $('input[id="nonMemberUser"]').attr("checked", true);
                                }
                                return
                            })
                            hide();
                        }//else End
                    }//if End

                    //updating data scope as per the query string
                    $scope.BindProducts();
                }
                $scope.querySearch();
            }, 2000);
        };

        //ShipViaCodes
        $scope.shipViaCodeClient = function () {
            urlService.dataProvider(shipViaCodeMethod, 'POST', '').success(function (data) {
                $scope.shipViaCode = data;
                var defaultCountry = '';
                if ($scope.ShippingAddresses != undefined)
                    defaultCountry = $scope.ShippingAddresses[0].CountryCode;
                if (defaultCountry == "USA") {
                    $scope.shipViaCodeDD = $scope.shipViaCode[1];
                }
                else {
                    $scope.shipViaCodeDD = $scope.shipViaCode[0];
                }
            }).error(function (x) {
            });
        };

        //get Favourites Products
        $scope.GetFavouriteItems = function (Masterid) {
            var getFavouritesArgu = { masterid: Masterid };
            urlService.dataProvider(getFavouriteItems, "POST", getFavouritesArgu).success(function (data) {
                $scope.FavouriteItems = unique(data);
            });//for
        };

        if ($scope.sesCustomerId != '') {

            //Getting User Favourite Items with customer Id
            $scope.GetFavouriteItems($scope.sesCustomerId);

            //Getting Shipping Charges based on the locations
            $scope.shipViaCodeClient();

            //Getting Countries
            $scope.getCountries();

            //Getting States
            $scope.getStates();

        }

        //Open Login Popup
        $scope.LoginPopup = function () {
            setTimeout(function () {
                if ($scope.sesCustomerId == '') {

                    $('#LoginPopup').addClass('is-visible');
                } else {
                    var currentUrl = window.location + '';
                    //window.location.href = applicationUrl + "/Login/Index" + '?url=' + currentUrl;
                    $('#LoginPopup').addClass('is-visible');
                }
            },
                500);
        }

        $scope.Login = function () {

            if (typeof $scope.UserName === "undefined" || $scope.UserName == "") {
                jAlert("Please Enter Username.");
            } else if (typeof $scope.Password == "undefined" || $scope.Password == '') {
                jAlert("Please Enter Password.");
            } else {
                $("#LoginPopup").find('#LoginpopLoader').show();
                var ChkRememberMe = $("#ChkRM").is(":checked");
                var currentUrl = window.location.href;
                var commeArgu = { Email: $scope.UserName, Password: $scope.Password, CurrentUrl: currentUrl, RememberMe: ChkRememberMe };
                urlService.dataProvider(LoginInfo, "POST", commeArgu).success(function (response) {
                    if (response.Success) {
                        //window.location.href = response.SSOURL;
                        window.location.href = currentUrl;
                        $scope.UserName = '';
                        $scope.Password = '';
                    }
                    else {
                        $('#LoginPopup').addClass('is-visible');
                        jAlert("Please Enter valid Username and Password.");
                        $("#LoginPopup").find('#LoginpopLoader').hide();
                        return;
                    }

                });

            }

        };
    }]);;
AoaShopping.controller('viewProductController',
        ['$http'
        , '$scope'
        , 'urlService'
        , 'productCart'
        , '$cookies'
        , '$cookieStore'
        , '$rootScope'
        , '$window'
        , function ($http
            , $scope
            , urlService
            , productCart
            , $location
            , $cookies
            , $cookieStore
            , $rootScope
            , $window) {

            "user strict";

            //Session variable data
            var pageLoad = false;
            $scope.sesCustomerId = '';
            $scope.sesToken = '';
            $scope.sesCustomerName = '';
            $scope.sesUserIsMember = '';
            $scope.viewUmbrellProducts = [];
            $scope.recentView = [];
            $scope.viewUmbrellSelectProduct = '';
            $scope.Products = '';
            $scope.viewProduct = '';
            $scope.rating = 0;
            $scope.showDetails = false;
            $scope.CartDetailsLength = 0;
            // <!--
            $scope.lastSelectObj = '';
            // -->
            var wL = window.location + '';
            var wLArray = wL.split('/');

            //getCategories
            urlService.dataProvider(categoryMethod, "GET", '').success(function (data) {
                $scope.catList = data;
            });

            //Cart Implementation
            var lSRcentItem = [];
            $scope.listProducts = function () {
                urlService.dataProvider(allProductsMethod, "POST", '').success(function (data) {
                    $scope.TempProducts = data;
                    $scope.Products = unique($scope.TempProducts);
                    $scope.ServerProducts = data;
                    $scope.totalProducts = $scope.Products.length;
                    $scope.searchLoad();

                    //LocalStorage RecentItems
                    if (localStorage.getItem("RecentItems") != null) {
                        var lSRecentItems = localStorage.getItem("RecentItems").split(",");
                        $.grep($scope.Products, function (key, index) {
                            $.grep(lSRecentItems, function (j, i) {
                                if (j != $scope.id) {
                                    if (key.ProductId == j) {
                                        lSRcentItem.push(key);
                                    }
                                }
                            });
                        });
                    }
                    $scope.recentView = lSRcentItem;
                    hide();
                });
            };
            $scope.listProducts();

            //Get sessioninfo
            $scope.sessionDetails = function () {
                urlService.dataProvider(sessionMethod, "POST", '').success(function (data) {
                    $scope.sesCustomerId = data[0].CustomerId;
                    $scope.sesToken = data[0].Token;
                    $scope.sesCustomerName = data[0].CustomerName;
                    $scope.sesUserIsMember = data[0].IsMember;
                    $scope.userEmail = data[0].Email;
                    if ($scope.userEmail == null)
                        $scope.userEmail = '';
                    //console.log($scope.userEmail);

                    var indexFavUrl = wLArray.indexOf("Favourites");
                    if (wLArray[indexFavUrl] == "Favourites") {
                        if ($scope.sesCustomerId != '') {
                            //Getting User Favourite Items with customer Id
                            $scope.GetFavouriteItems($scope.sesCustomerId);
                        }
                    }
                    /* To Open Popup after login */
                    if (sessionStorage.getItem("CustomPro") == "fromCompse") {
                        if (!sessionStorage.getItem("UMBID"))
                            var cprt = window.location.search.split("=")[1];
                        else
                            var cprt = sessionStorage.getItem("UMBID");
                        show();
                        if ($scope.sesUserIsMember != "1") {
                            jAlert('This Product is only for members.');
                            sessionStorage.removeItem("CustomPro");
                            return false
                        } else {
                            $scope.ProductCompose(cprt, '', cprt);
                        }
                    }
                });

            }
            $scope.sessionDetails();

            //Get Param by regular Expression
            function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                    results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            }

            //Assigning param valur to scope.id
            $scope.id = getParameterByName("ProductId");

            //Getting data by scope.id

            var indexUrl = wLArray.indexOf("viewproduct");
            if (wLArray[indexUrl] == "viewproduct") {
                show();
                (function () {
                    return $http({
                        method: "GET",
                        url: applicationUrl + '/Product/GetProductDetails',
                        params: { ProductId: $scope.id },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    }).success(function (data) {

                        if (data != "ERROR_FAIL") {
                            $scope.viewProduct = data;
                            //console.log($scope.viewProduct);
                            $scope.productRatingCount = $scope.viewProduct.RatingCount;
                            updateRatings($scope.viewProduct.Rating);

                            //if Umbrella Product true Method
                            if ($scope.viewProduct.IsUmbrellaProduct == true) {
                                $http({
                                    method: "GET",
                                    url: applicationUrl + '/Product/GetSubProductDetails',
                                    params: { ProductId: $scope.id },
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json"
                                }).success(function (data) {
                                    $scope.viewUmbrellProducts = data;
                                }).error(function (x) {
                                });
                            }

                            //Get Related & Recent & favourite Products
                            $scope.GetrelatedItems();
                            $scope.GetrecentlyItems();

                            //Load Reviews
                            $scope.loadReviews($scope.id, 9);
                            hide();
                        }
                        else {
                            jAlert('Unable to get product details,Please try later.');
                        }
                    }).error(function (x) {
                    });
                })();
            };

            $scope.IsUmbrellaProductTrue = true;
            $scope.IsUmbrellaProductElements = false;
            $scope.IsUmbrellaProductAddToCart = false;
            // <!-- 
            var lastActivityOpt1, lastActivityOpt2;
            // -->
            $scope.onProductChange = function ($event) {

                $(".preImageLoader").show();
                /* To Open Popup after login */
                setTimeout(function () {
                    if ($scope.sesCustomerId == '')
                        sessionStorage.setItem("UMBID", $(".ProductCompose").attr("data-prdId"));
                }, 2000);

                $("#CreateProof").attr("data-umb", "true").attr("data-parenetId", $("#parentId").text());
                $(document.body).off();

                if ($('#prdQuantity').val() == "") {
                    $('#prdQuantity').css('box-shadow', '0px 0px 2px #FF0000');
                } else {
                    $('#prdQuantity').removeAttr('style');
                }

                if ($('#viewUmbrellProductDD').val() == "") {
                    $('#viewUmbrellProductDD').css('box-shadow', '0px 0px 2px #FF0000');
                } else {
                    if ($('#prdQuantity').val() == "") {
                        // <!-- 
                        $scope.viewUmbrellProductDD = "";
                        setTimeout(function () {
                            isUmbrellaProdTrue();
                        }, 500);
                        $(".preImageLoader").hide();
                        return false;
                        // -->
                    } else {
                        $('#viewUmbrellProductDD').removeAttr('style');
                    }
                };
                // <!-- 
                var imgGallery = [];
                // -->
                function isUmbrellaProdTrue() {
                    // <!-- 
                    // in this last && condition added
                    if ($("#viewUmbrellProductDD").val() == "" && $("#viewUmbrellProductDD").is(":visible") == true && $("#prdQuantity").val() == "") {
                    // -->
                        $scope.IsUmbrellaProductTrue = true;
                        $scope.IsUmbrellaProductElements = false;
                        $scope.IsUmbrellaProductAddToCart = false;
                        $scope.viewUmbrellSelectProduct = $scope.viewUmbrellProducts;
                        updateRatings($scope.viewProduct.Rating);
                        $scope.productRatingCount = $scope.viewProduct.RatingCount;
                        $scope.loadReviews($scope.id, 9);
                        // <!-- 
                        $(".sp-large").remove();
                        $(".sp-thumbs").remove();
                        setTimeout(function () {
                            $('.sp-wrap').smoothproducts();
                            if ($(".product_img").index("a") == -1 && $(".product_img").index("div") == -1) {
                                $(".product_img").append("<img src='http://avenir-it.com/HRMS/Images/Image-not-available.png' alt='' />");
                            }
                            $(".preImageLoader").hide();
                        }, 2000);
                        return false;
                        // -->
                    }
                    if ($("#prdQuantity").val() == "") {
                        $scope.IsUmbrellaProductTrue = true;
                        $scope.IsUmbrellaProductElements = false;
                        $scope.IsUmbrellaProductAddToCart = false;
                        $scope.viewUmbrellSelectProduct = $scope.viewUmbrellProducts;
                        $(".sp-large").remove();
                        $(".sp-thumbs").remove();
                        setTimeout(function () {
                            $('.sp-wrap').smoothproducts();
                            if ($(".product_img").index("a") == -1 && $(".product_img").index("div") == -1) {
                                $(".product_img").append("<img src='http://avenir-it.com/HRMS/Images/Image-not-available.png' alt='' />");
                            }
                            $(".preImageLoader").hide();
                        }, 1000);
                        updateRatings($scope.viewProduct.Rating);
                        $scope.productRatingCount = $scope.viewProduct.RatingCount;
                        $scope.loadReviews($scope.id, 9);
                    }
                }

                if (($scope.viewUmbrellProducts.SubProductOption02).length == 0) {
                    if ($("#prdQuantity").val() == "") {
                        isUmbrellaProdTrue();
                    } else {
                        $.grep($scope.viewUmbrellProducts.UmbrellaSubProducts, function (obj) {
                            if (obj.Option1Subcode == $('#prdQuantity').val()) {
                                $scope.viewUmbrellSelectProduct = obj;
                                if ($scope.viewUmbrellSelectProduct.LongDescription == null || $scope.viewUmbrellSelectProduct.LongDescription.length <= 0)
                                    $(".moreDetails").hide();
                                else
                                    $(".moreDetails").show();
                                $scope.productRatingCount = $scope.viewUmbrellSelectProduct.RatingCount;
                                updateRatings($scope.viewUmbrellSelectProduct.Rating);
                                $scope.loadReviews($scope.viewUmbrellSelectProduct.ProductId, 9);
                            }
                        });

                        //updating product gallery if data source is null
                        if ($scope.viewUmbrellSelectProduct.ProductGalleryImgs == null) {
                            imgGallery.push($scope.viewUmbrellSelectProduct.ProductImage);
                            $scope.viewUmbrellSelectProduct.ProductGalleryImgs = imgGallery;
                            $(".sp-large").remove();
                            $(".sp-thumbs").remove();
                            setTimeout(function () {
                                $('.sp-wrap').smoothproducts();
                                if ($(".product_img").index("a") == -1 && $(".product_img").index("div") == -1) {
                                    $(".product_img").append("<img src='http://avenir-it.com/HRMS/Images/Image-not-available.png' alt='' />");
                                }
                                $(".preImageLoader").hide();
                            }, 2000);
                        } else {
                            $scope.viewUmbrellSelectProduct.ProductGalleryImgs = $scope.viewUmbrellSelectProduct.ProductGalleryImgs;
                            $(".sp-large").remove();
                            $(".sp-thumbs").remove();
                            setTimeout(function () {
                                $('.sp-wrap').smoothproducts();
                                if ($(".product_img").index("a") == -1 && $(".product_img").index("div") == -1) {
                                    $(".product_img").append("<img src='http://avenir-it.com/HRMS/Images/Image-not-available.png' alt='' />");
                                }
                                $(".preImageLoader").hide();
                            }, 2000);
                        }

                        //Enable data divs for umbrella products
                        $scope.IsUmbrellaProductTrue = false;
                        $scope.IsUmbrellaProductElements = true;
                        $scope.IsUmbrellaProductAddToCart = true;
                    }
                } else {

                    if ($("#viewUmbrellProductDD").val() != "" && $('#prdQuantity').val() != "") {
                        // <!-- 
                        $scope.viewUmbrellSelectProduct = '';
                        // -->
                        $.grep($scope.viewUmbrellProducts.UmbrellaSubProducts, function (obj) {
                            if (obj.Option1Subcode == $scope.prdQuantity.OptionMasterListCode && obj.Option2Subcode == $scope.viewUmbrellProductDD.OptionMasterListCode) {
                                $scope.viewUmbrellSelectProduct = obj;
                                $scope.productRatingCount = $scope.viewUmbrellSelectProduct.RatingCount;
                                updateRatings($scope.viewUmbrellSelectProduct.Rating);
                                $scope.loadReviews($scope.viewUmbrellSelectProduct.ProductId, 9);
                            }
                        });

                        // <!-- 
                        if ($scope.viewUmbrellSelectProduct != "") { 
                            $scope.lastSelectObj = $scope.viewUmbrellSelectProduct;
                            lastActivityOpt1 = $('#prdQuantity')[0].selectedIndex;
                            lastActivityOpt2 = $('#viewUmbrellProductDD')[0].selectedIndex;

                        } else {
                            if ($('#viewUmbrellProductDD').val() != "") {
                                jAlert("No Products Available");
                                $scope.viewUmbrellSelectProduct = $scope.lastSelectObj;
                                $scope.prdQuantity = $scope.viewUmbrellProducts.SubProductOption01[parseInt(lastActivityOpt1) - 1];
                                $scope.viewUmbrellProductDD = $scope.viewUmbrellProducts.SubProductOption02[parseInt(lastActivityOpt2) - 1];
                                $(".preImageLoader").hide();
                                return false;
                            } else {
                                isUmbrellaProdTrue();
                                $(".preImageLoader").hide();
                            }
                        };
                        // -->

                        var imgGallery = [];
                        if ($scope.viewUmbrellSelectProduct.ProductGalleryImgs == null) {
                            imgGallery.push($scope.viewUmbrellSelectProduct.ProductImage);
                            $scope.viewUmbrellSelectProduct.ProductGalleryImgs = imgGallery;
                            $(".sp-large").remove();
                            $(".sp-thumbs").remove();
                            setTimeout(function () {
                                $('.sp-wrap').smoothproducts();
                                if ($(".product_img").index("a") == -1 && $(".product_img").index("div") == -1) {
                                    $(".product_img").append("<img src='http://avenir-it.com/HRMS/Images/Image-not-available.png' alt='' />");
                                }
                                $(".preImageLoader").hide();
                            }, 2000);
                        } else {
                            $scope.viewUmbrellSelectProduct.ProductGalleryImgs = $scope.lastSelectObj.ProductGalleryImgs;
                            $(".sp-large").remove();
                            $(".sp-thumbs").remove();
                            setTimeout(function () {
                                $('.sp-wrap').smoothproducts();
                                if ($(".product_img").index("a") == -1 && $(".product_img").index("div") == -1) {
                                    $(".product_img").append("<img src='http://avenir-it.com/HRMS/Images/Image-not-available.png' alt='' />");
                                }
                                $(".preImageLoader").hide();
                            }, 1000);
                        }

                        //Enable data divs for umbrella products
                        $scope.IsUmbrellaProductTrue = false;
                        $scope.IsUmbrellaProductElements = true;
                        $scope.IsUmbrellaProductAddToCart = true;

                    } else {
                        isUmbrellaProdTrue();
                        $(".preImageLoader").hide();
                    }
                }

            };

            //viewUmbrellProductsShortDescription
            urlService.dataProvider(cartDetailsMethod, "POST", '').success(function (data) {
                $scope.viewCartData = data;
            });

            //Getting Cart details  
            $scope.TotalPrice = 0;
            $scope.GetCartProducts = function (from) {
                from = from || '';
                var catUrl = applicationUrl + '/Product/GetCartDetails';
                return $http({
                    method: "POST",
                    url: catUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                }).success(function (data) {
                    if (data == "ADDED_FAIL") {
                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalItems = 0;
                        $scope.CartDetailsLength = $scope.CartDetails.length;
                        jAlert('Unable to get cart details,Please try later.');
                    }
                    else if (data != "NO_DETAILS_FOUND") {
                        if (from == "delete" || from == "update") {
                            $scope.viewCartData = data;
                        }

                        //Caliculating Total Price
                        var totalPrice = 0, totalItems = 0;

                        $.each(data, function (index, obj) {
                            if ($scope.sesUserIsMember == "1") {
                                totalPrice = totalPrice + (obj.Quantity * obj.product.MemberPrice);
                            } else {
                                totalPrice = totalPrice + (obj.Quantity * obj.product.Price);
                            }
                            totalItems = totalItems + (obj.Quantity);

                        });
                        $scope.CartDetails = data;
                        $scope.CartDetailsLength = $scope.CartDetails.length;
                        $scope.TotalPrice = totalPrice;
                        $scope.TotalItems = totalItems;

                    }
                    else {
                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalItems = 0;
                        $scope.CartDetailsLength = $scope.CartDetails.length;

                    }

                }).error(function (x) {
                });
            }
            $scope.GetCartProducts();
            $scope.cartSuccess = '';

            //Adding Product To Cart
            $scope.AddToCart = function (productid, $event, from) {
                debugger;
                productCart.ProductAddToCart(productid, $scope, from, $event);
            };

            //Open Cart
            $scope.OpenCart = function () {

                $scope.GetCartProducts();

                //Gettings user CreditCatds
                $scope.getCreditCardDetails();

                //Gettings ship Via Code
                $scope.shipViaCodeClient();

                setTimeout(function () {
                    $('#CartPopUp').addClass('is-visible');
                }, 500);
            }

            //Update Cart
            $scope.UpdateToCart = function (from) {

                if ($('#shipViaCodeDD').val() == "") {
                    $('#shipViaCodeDD').css('box-shadow', '0px 0px 2px #FF0000');
                } else {
                    $('#shipViaCodeDD').removeAttr('style');
                    $scope.billingAddIdDiv = false;
                    $scope.shippingAddIdDiv = false;
                }
                if ($(".cartdetails").length > 0) {
                    $('#popLoader').show();
                } else {
                    $('#alrtMsg').empty();
                    var txtLgn = "No products to update!";
                    $('#alrtMsg').show().html(txtLgn);
                    return;
                }

                var errorFlag = false;

                var selector = "";
                var viewcartflag = false;

                if (from == "viewcart") {
                    viewcartflag = true;
                    selector = ".qty";
                }
                else if (from == "cart") {
                    selector = ".cartdetails";
                }

                $(selector).each(function () {

                    var avlQty = $(this).next().text();
                    var quantity = $(this).val();
                    var productid = $(this).prop('id');

                    var bo = $(this).attr("data-bo");
                    var from = "update";
                    var customOrStandard = $scope.viewUmbrellProductDD;
                    var shippreference = '';
                    if ($scope.shipViaCodeDD != undefined)
                        shippreference = $scope.shipViaCodeDD.Code;

                    var cartArgu = { ProductId: productid, Quantity: quantity, From: from, StrCustomOrStandard: customOrStandard, shipviacode: shippreference };
                    // var cartArgu = { ProductId: productid, Quantity: quantity, From: from, StrCustomOrStandard: customOrStandard };
                    if ($(this).attr("data-Inventoried") == "true") {
                        if (quantity >= 0) {
                            if (parseFloat(avlQty) >= parseFloat(quantity)) {
                                urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                                    if (viewcartflag) {
                                        from = "viewcart";
                                    }

                                    $scope.GetCartProducts(from);

                                });

                            } else {
                                if (bo == "true") {
                                    urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                                        if (viewcartflag) {
                                            from = "viewcart";
                                        }

                                        $scope.GetCartProducts(from);

                                    });
                                } else {
                                    $('#popLoader').hide();
                                    jAlert(' This Product Stock Availability upto ' + avlQty + '!');
                                    errorFlag = true;
                                    return false;
                                }
                            }
                        } else {
                            if (bo == "true") {
                                urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                                    if (viewcartflag) {
                                        from = "viewcart";
                                    }

                                    $scope.GetCartProducts(from);

                                });
                            } else {
                                $('#popLoader').hide();
                                jAlert(' Product Available in minimum quantities of 1 !');
                                errorFlag = true;
                                return false;
                            }
                        }
                    } else {
                        urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {
                            if (viewcartflag) {
                                from = "viewcart";
                            }
                            $scope.GetCartProducts(from);

                        });
                    }

                });
                $('#popLoader').hide();
                return errorFlag;

            }

            //Delete Cart
            $scope.DeleteCart = function (productid) {
                productCart.ProductAddToCart(productid, $scope, 'delete', '');
            };

            //Get Credit Card Details
            $scope.getCreditCardDetails = function () {
                urlService.dataProvider(GetCreditCardMethod, "POST", "").success(function (data) {
                    $scope.cCard = data;
                    if ($scope.cCard.length == 0)
                        $("#useOtherVal").text("true");
                });
            }
            $scope.getCreditCardDetails();

            //add Credit Card
            //Months array
            $scope.monthList = ["Month", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
            $scope.months = $scope.monthList[0];

            //get Next 100 years and store into array var
            var years = [];
            var i;
            var getYear = new Date().getFullYear();
            for (i = 0; i <= 100; i++) {
                years.push(getYear);
                getYear = getYear + 1;
            }
            years.unshift('Year');
            $scope.yearList = years;
            $scope.years = $scope.yearList[0];

            var valid = true;
            $scope.cValidation = function () {
                valid = '';
                if (!$('input[name=cardType]').is(':checked')) {
                    $('input[name=cardType]').parent().find('.errorMsg').text('Please select card type!');
                    valid = false;
                } else {
                    $('input[name=cardType]').parent().find('.errorMsg').empty();
                }

                if (CCName.value == '') {
                    $('#CCName').next().text('Please enter the Card Holder name!');
                    valid = false;
                } else {
                    $('#CCName').next().empty();
                }
                if (CCNumber.value == '') {
                    $('#CCNumber').next().text('Please enter the Credit Card Number!');
                    valid = false;
                } else {
                    $('#CCNumber').next().empty();
                }
                if (CCcvv.value == '') {
                    $('#CCcvv').next().text('Please enter the CVV Number!');
                    valid = false;
                } else {
                    $('#CCcvv').next().empty();
                }

                if ($scope.months == 'Month') {
                    $('#months').next().text('Please select the month!');
                    valid = false;
                } else {
                    $('#months').next().empty();
                }
                if ($scope.years == 'Year') {
                    $('#years').next().text('Please select the Year!');
                    valid = false;
                } else {
                    $('#years').next().empty();
                }

                var today, someday;
                var exMonth = $scope.months;
                var exYear = $scope.years;
                today = new Date();
                someday = new Date();
                someday.setFullYear(exYear, exMonth, 1);

                if (someday < today) {
                    $('#years').next().text("The expiry date is before today's date. Please select a valid expiry date!");
                    valid = false;
                } else {
                    $('#years').next().empty();
                }

                if (valid.length == 0) {
                    valid = true
                } else {
                    valid = false
                }

                return valid;
            };

            //End

            //Add WishList Products
            $scope.AddToWishList = function (wId, CustomerID) {
                // '1' for add, '2' for remove
                var addWishArgu = { ProductId: wId, CustomerID: CustomerID, From: 2 };
                urlService.dataProvider(saveWishlistMethod, "POST", addWishArgu).success(function (status) {

                    //if (status == 2) {
                    //    jAlert('removed successfully');
                    //}

                    //Scope Refreshed
                    $scope.listProducts();

                    //for Adding to Wish List
                    $scope.GetWishListItems(CustomerID);
                });
            };

            //Only at WishList Page checking by Url
            var indexWishUrl = wLArray.indexOf("WishList");
            if (wLArray[indexWishUrl] == "WishList") {
                $scope.GetWishListItems = function (customerId) {
                    var getWishListArgu = { CustomerID: customerId };
                    urlService.dataProvider(getWishlistMethod, "POST", getWishListArgu).success(function (data) {
                        if (data.length == 0) {
                            sessionStorage.removeItem("wData");
                        }
                        $scope.WishListItems = unique(data);
                    });
                };
                $scope.GetWishListItems($scope.sesCustomerId);
            };


            var shipCustId = '';
            //Get Shipping & Billing Address
            urlService.dataProvider(GetAddressesMethod, "POST", '').success(function (data) {
                $scope.userAddress = data;
                //console.log($scope.userAddress);
                var addListCount = $scope.userAddress.AddressList.length;
                // Adding ShipToFlag default to scope ShippingAddresses
                $scope.ShippingAddresses = [];
                if (sessionStorage.getItem('ShippingIndex') != null) {
                    if (sessionStorage.getItem('ShippingIndex').length != 0) {
                        var sessionShippingIndexVal = $scope.userAddress.AddressList[sessionStorage.getItem('ShippingIndex')];
                        $scope.ShippingAddresses.push(sessionShippingIndexVal);
                    } else {
                        $.grep($scope.userAddress.AddressList, function (item) {
                            if (item.ShipToFlag == true) {
                                $scope.ShippingAddresses.push(item);
                                shipCustId = item.CustomerAddressId;
                                sessionStorage.setItem('ShippingCustId', item.CustomerAddressId);
                            }
                        });
                    }
                }
                else {
                    $.grep($scope.userAddress.AddressList, function (item) {
                        if (item.ShipToFlag == true) {
                            $scope.ShippingAddresses.push(item);
                            shipCustId = item.CustomerAddressId;
                            sessionStorage.setItem('ShippingCustId', item.CustomerAddressId);
                        }
                    });
                }

                // Adding BillToFlag default to scope BillingAddresses
                $scope.BillingAddresses = [];
                if (sessionStorage.getItem('BillingIndex') != null) {
                    if (sessionStorage.getItem('BillingIndex').length != 0) {
                        var sessionBillingIndexVal = $scope.userAddress.AddressList[sessionStorage.getItem('BillingIndex')];
                        $scope.BillingAddresses.push(sessionBillingIndexVal);
                    } else {
                        $.grep($scope.userAddress.AddressList, function (item) {
                            if (item.BillToFlag == true) {
                                $scope.BillingAddresses.push(item);
                                sessionStorage.setItem('BillingCustId', item.CustomerAddressId);
                                sessionStorage.setItem('billingAdd', $scope.BillingAddresses[0].FormattedAddress);
                            }
                        });
                    }
                } else {
                    $.grep($scope.userAddress.AddressList, function (item) {
                        if (item.BillToFlag == true) {
                            $scope.BillingAddresses.push(item);
                            sessionStorage.setItem('BillingCustId', item.CustomerAddressId);
                            sessionStorage.setItem('billingAdd', $scope.BillingAddresses[0].FormattedAddress);
                        }
                    });
                }

                if ($scope.ShippingAddresses.length == 0)
                    $scope.ShippingAddresses = "Shipping Address is not available!";

                if ($scope.BillingAddresses.length == 0)
                    $scope.BillingAddresses = "Billing Address is not available";

                //Set Default address for Shipping and Billing
                $scope.setDefaultAddress = function ($event, $index, container) {
                    $('#popLoader').show();
                    var addCurrType = $($event.target).attr('data-type');
                    var addCurrId = $($event.target).attr('data-addid');
                    urlService.dataProvider(setAddress, "POST", { addId: addCurrId, addtype: addCurrType }).success(function () {
                        if (data != "fail") {
                            $scope.getCartData();
                            $('#popLoader').hide();
                        }
                    }).error(function (ex) {
                        $('#popLoader').hide();
                    });
                    if (addCurrType == "Billing") {
                        $scope.BillingAddresses = [];
                        $.grep($scope.userAddress.BillingAddresses, function (item) {
                            item.BillToFlag = false
                        });
                        $scope.userAddress.BillingAddresses[$index].BillToFlag = "true";
                        var addressIndex = $scope.userAddress.BillingAddresses[$index];
                        $scope.BillingAddresses.push(addressIndex);
                        sessionStorage.setItem('BillingIndex', $index);
                        sessionStorage.setItem('BillingCustId', $scope.userAddress.BillingAddresses[$index].CustomerAddressId);
                        sessionStorage.setItem('billingAdd', $scope.BillingAddresses[$scope.BillingAddresses.length - 1].FormattedAddress);
                        $("#billingAddressList").find(".shwAddress").find(".default").hide();
                        $("#billingAddressList").find(".useAdd").removeClass("btn_active");
                        $($event.target).parent().find(".default").removeClass('ng-hide').show();
                        $("#billingAddressList").find($event.target).addClass("btn_active");
                    }

                    if (addCurrType == "Shipping") {
                        $scope.ShippingAddresses = [];
                        $.grep($scope.userAddress.ShippingAddresses, function (item) {
                            item.ShipToFlag = false
                        });
                        $scope.userAddress.ShippingAddresses[$index].ShipToFlag = "true";
                        var addressIndex = $scope.userAddress.ShippingAddresses[$index];
                        shipCustId = $scope.userAddress.ShippingAddresses[$index].CustomerAddressId;
                        sessionStorage.setItem('ShippingIndex', $index);
                        sessionStorage.setItem('ShippingCustId', $scope.userAddress.ShippingAddresses[$index].CustomerAddressId);
                        $scope.ShippingAddresses.push(addressIndex);
                        $("#shippingAddressList").find(".shwAddress").find(".default").hide();
                        $("#shippingAddressList").find(".useAdd").removeClass("btn_active");
                        $($event.target).parent().find(".default").removeClass('ng-hide').show();
                        $("#shippingAddressList").find($event.target).addClass("btn_active");
                    }
                }

                //$(".shwAddress").width(addListCount * 270);

                $scope.taxShippingPrice = function (shippreference) {
                    var shippreference = '';
                    if ($scope.shipViaCodeDD != undefined)
                        shippreference = $scope.shipViaCodeDD.Code;

                    var taxErrorFlag = true;
                    shipCustId = sessionStorage.getItem('ShippingCustId');
                    return $http({
                        method: "POST",
                        url: applicationUrl + '/Order/GetTax',
                        params: { ShippingId: shippreference },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    }).success(function (data) {
                        if (data != "ADDED_FAIL") {
                            $scope.getTaxData = data;
                            $scope.shippingHandling = data.TotalShipping;
                            $scope.Tax = data.TotalTax;
                            $scope.CouponSaving = data.Coupons.length == 0 ? null : data.Coupons[0].Amount;
                        } else {
                            jAlert('Internal Technical Error. Please try again!');
                            taxErrorFlag = false
                            return false;
                        }
                        $('#popLoader').hide();
                    }).error(function (x) {
                        jAlert(x);
                    });
                    return taxErrorFlag;
                }

            });

            //Create Order
            $scope.placeOrder = function () {
                if (($scope.TotalPrice + $scope.Tax + $scope.shippingHandling) == 0) {
                    createOrderItem();
                }
                else if ($('input[id="useOther"]').is(':checked') || $("#useOtherVal").text() == "true") {
                    $scope.cValidation();
                    if (valid == true) {
                        if ($("#saveCCCard").is(":checked") == true) { //Save CreditCard Details
                            saveCreditCardDetails();
                        }
                        else {
                            createOrderItem();
                        }
                    }
                } else {
                    createOrderItem();
                }

                function saveCreditCardDetails() {
                    $('#popLoader').show();
                    $('.errorMsg').empty();
                    var selectedRadioValue = $('input[name=cardType]:checked').val();

                    var CardType = selectedRadioValue,
                        CardHolderName = CCName.value,
                        CreditCardNumber = CCNumber.value,
                        CreditCardCVVNumber = CCcvv.value,
                        ExpireMonth = $scope.months,
                        ExpireYear = $scope.years;

                    var saveCCArgu = {
                        CardType: CardType,
                        CardNumber: CreditCardNumber,
                        Cvv: CreditCardCVVNumber,
                        ExpDate: ExpireMonth,
                        ExpYear: ExpireYear,
                        NameOnCard: CardHolderName
                    };
                    urlService.dataProvider(addCCardMethod, "POST", saveCCArgu).success(function (data) {
                        if (data != true) {
                            jAlert('Please enter valid details!');
                            $('#popLoader').hide();
                            clearCC();
                        }
                        else {
                            createOrderItem();
                        }
                    }).error(function (errorx) {
                        clearCC();
                        $('#popLoader').hide();
                        jAlert(errorx);
                    });
                }

                function createOrderItem() {
                    $('#popLoader').show();
                    $('.errorMsg').empty();
                    var selectedRadioValue = $('input[name=cardType]:checked').val();
                    var CardType = selectedRadioValue,
                        CardHolderName = CCName.value,
                        CreditCardNumber = CCNumber.value,
                        CreditCardCVVNumber = CCcvv.value,
                        ExpireMonth = $scope.months,
                        ExpireYear = $scope.years,
                        userOption = $("#saveCCCard").is(":checked") == true ? true : false;

                    var saveCCArgu = {
                        CreditCardType: CardType,
                        CreditCardNumber: CreditCardNumber,
                        Cvv2: CreditCardCVVNumber,
                        ExpirationMonth: ExpireMonth,
                        ExpirationYear: ExpireYear,
                        NameOnCard: CardHolderName,
                        WantToSave: userOption
                    };

                    if ($scope.getTaxData.ValidationIssues != null) {
                        var validationRes = [];
                        var valiIssuItems = $(".taxValidationsIssues");
                        $(valiIssuItems).each(function (index) {
                            var thisKey = $(this).find("p.msg").attr("data-key");
                            var tempObj = {
                                Key: thisKey,
                                SeelctedValue: $(this).find("input[name='" + thisKey + "']:checked").val()
                            };
                            validationRes.push(tempObj);
                        });
                    }

                    var billingAddId = sessionStorage.getItem("BillingCustId");   //$('input[name="billingAddId"]:checked').attr('id');
                    var shippingAddId = sessionStorage.getItem("ShippingCustId"); //$('input[name="shippingAddId"]:checked').attr('id');
                    var ccId = $('input[id="ccType"]').is(':checked') == true ? $('input[id="ccType"]').attr('data-PartialCardNumber') : '';
                    var tax = $("#tax").text().replace('$', '');
                    var shippingPrice = $("#shippingHandling").text().replace('$', '');
                    var shippreference = $scope.shipViaCodeDD.Code;   //Added By Rakesh

                    //$('.cart-popup').removeClass('is-visible');
                    show();
                    var placeOrderArgu = {
                        billingAddId: billingAddId,
                        shippingAddId: shippingAddId,
                        ccId: ccId,
                        TotalTax: tax,
                        TotalShipping: shippingPrice,
                        shipViaCode: shippreference,
                        CreditCardInfo: $('input[id="useOther"]').is(':checked') == true || $("#useOtherVal").text() == "true" ? JSON.stringify(saveCCArgu) : null,
                        ValidationResponses: $scope.getTaxData.ValidationIssues != null ? JSON.stringify(validationRes) : ''
                    };
                    urlService.dataProvider(createOrderMethod, "POST", placeOrderArgu).success(function (d) {
                        $('#popLoader').hide();
                        if (d.Success == true) {
                            $scope.finalOrderNumber = d.Items.OrderNumber;
                            sessionStorage.setItem('orderNumber', $scope.finalOrderNumber);
                            $('.cart-popup').removeClass('is-visible');
                            window.location = applicationUrl + '/Product/orderConfirmation';
                            clearCC();
                        } else {
                            hide();
                            //clearCC();
                            //jAlert('Unable to place order Please try again!');
                            jAlert(d.ErrorMessage);
                            if (d.Message == 'No Product in Cart !') {
                                /*Remove Items from Cart*/
                                $scope.getCartData();
                                $(".stepContent").removeClass("step_active");
                                $("#step1_MyCart").addClass("step_active");
                            }
                        }
                    }).error(function (x) {
                        $('#popLoader').hide();
                        hide();
                        clearCC();
                        jAlert(x.ErrorMessage);
                    });
                }
            };


            $scope.orderResponse = function () {

                urlService.dataProvider(getOrderdeatilsMethod, "POST", "").success(function (data) {
                    $scope.repOrderData = data;
                    $scope.repCouponSaving = data.Coupons.length == 0 ? null : data.Coupons[0].Amount;
                    $scope.repCouponSavingDesc = data.Coupons.length == 0 ? null : data.Coupons[0].Description;
                });

                var placeOrderAddress = sessionStorage.getItem('billingAdd');
                placeOrderAddressFormat = placeOrderAddress.replace(',', ', <br />');
                $scope.bilAddress = placeOrderAddressFormat;
                $scope.orderNumber = sessionStorage.getItem('orderNumber');
            }

            // Search Filter by keyword & by select category
            $scope.SearchProducts = function (from) {
                if (from == 'topSearch')
                    $("#search").val('');
                else
                    $("#topSearch").val('');

                var topSearch = $("#topSearch").val().trim();

                if (topSearch.length > 0) {

                    var searchedProducts = factorialSearch($scope.TempProducts, topSearch);

                    if (!(typeof searchedProducts === "undefined")) {
                        $scope.Products = searchedProducts;

                        var Names = [];
                        Names = getDataInArray(searchedProducts);

                        $("#topSearch").autocomplete({
                            source: function (request, response) {
                                response(Names);
                            },
                            select: function (event, ui) {
                                var items = $.grep($scope.Products, function (obj) {

                                    if (obj.ProductName + " (" + obj.ProductCode + ")" == ui.item.value)
                                        return obj.ProductName;
                                });

                                window.location = applicationUrl + '/Product/viewproduct/?ProductId=' + items[0].ProductId;
                            }
                        });
                    }

                }
                else {

                    $scope.Products = $scope.TempProducts;
                    var searchWord = $("#search").val().trim();

                    var category = $("#CategorySearch").val();
                    if (category == "All") {

                        //Searching with All option
                        var searchedProducts = factorialSearch($scope.Products, searchWord);

                        if (!(typeof searchedProducts === "undefined")) {
                            $scope.Products = searchedProducts;

                            var Names = [];
                            Names = getDataInArray(searchedProducts);

                            $("#search").autocomplete({
                                source: function (request, response) {
                                    response(Names);
                                }
                            });
                        }
                    }
                    else {
                        var catArr = category.split(':');

                        var products = $.grep($scope.Products, function (obj, index) {

                            if (catArr[0] == "format") {
                                return obj.Formats.toLowerCase() == catArr[1]
                            }
                            else if (catArr[0] == "category") {
                                return obj.Categories.toLowerCase() == catArr[1]
                            }
                            else {
                                return obj.TopicCode.toLowerCase() == catArr[1].toLowerCase()
                            }
                        });

                        $scope.Products = unique(products);

                        //Searching with Category 
                        var searchedProducts = factorialSearch(products, searchWord);

                        if (!(typeof searchedProducts === "undefined")) {
                            $scope.Products = searchedProducts;

                            var Names = [];
                            Names = getDataInArray(searchedProducts);
                            $("#search").autocomplete({
                                source: function (request, response) {
                                    response(Names);
                                }
                            });
                        }
                    }
                    $scope.Products = unique($scope.Products);
                    $scope.totalProducts = $scope.Products.length;
                    $scope.currentPage = 0;
                }
            }

            function getDataInArray(array) {
                var names = [];
                $.each(array, function (i, d) {
                    names.push(d.ProductName + " (" + d.ProductCode + ")");
                    // names.push(d.ProductCode);
                });
                return names;
            }

            //Adding new address
            urlService.dataProvider(getCountryMethod, 'POST', '').success(function (data) {
                $scope.CountryList = data;
                //$scope.Countrys = $scope.CountryList[0];
                $scope.Countrys = $scope.CountryList[2];

            });

            urlService.dataProvider(getStateMethod, 'POST', '').success(function (data) {
                $scope.StateList = data;
                $scope.TmpStateList = data;
                $scope.States = $scope.StateList[0];
            });

            $scope.billingAddIdDiv = false;
            $scope.shippingAddIdDiv = false;
            $scope.addBtnClick = function (from) {
                if (from == "Shipping") {
                    $scope.billingAddIdDiv = false;
                    $scope.shippingAddIdDiv = true;
                    $scope.addressType = "Shipping Address";
                } else {
                    $scope.billingAddIdDiv = true;
                    $scope.shippingAddIdDiv = false;
                    $scope.addressType = "Billing Address";
                }
                $(".actions").hide();
            };

            $scope.cancelBtnClick = function () {
                $scope.billingAddIdDiv = false;
                $scope.shippingAddIdDiv = false;
                $scope.clearForm();
            };

            $scope.clearForm = function () {
                $scope.addressType = $scope.shippingAddIdDiv == true ? 'Shipping Address' : 'Billing Address';
                $scope.Countrys.CountryDescription = '';
                $scope.Countrys.CountryCode = '';
                $scope.address1 = '';
                $scope.address2 = '';
                $scope.city = '';
                $scope.States = '';
                $scope.postCode = '';
            };

            //Selecty Country code to filter states list
            $scope.onCountryChange = function (a) {
                $scope.inputEnbl = false;
                if (a.CountryDescription == "All Countries") {
                    urlService.dataProvider(getStateMethod, 'POST', '').success(function (data) {
                        $scope.StateList = data;
                        //$scope.States = $scope.StateList[0];
                    });
                }
                //filterting states based on Country selection
                var result = $.grep($scope.TmpStateList, function (e) { return e.CountryCodeString == a.CountryCode });
                if (result.length != 0) {
                    $scope.StateList = result;
                    //$scope.States = $scope.StateList[0];
                } else {
                    //if states not available
                    //$scope.StateList = [{ StateDescription: 'No States Available' }];
                    $scope.inputEnbl = true;
                    $("input#States").val('');
                }

            }

            var stateCode = $('#States').val();
            var valid = true;
            $scope.validations = function () {
                valid = '';
                if ($('#addressType').val() == "") {
                    $('#addressType').next().text('Please select the Address Type!');
                    valid = false;
                } else {
                    $('#addressType').next().empty();
                }

                if ($('#Countrys').val() == '') {
                    $("#Countrys").next().text('Please select Country!');
                    valid = false;
                } else {
                    $('#Countrys').next().empty();
                }

                if ($('#States').val() == "") {
                    if ($scope.inputEnbl != true)
                        $("#States").next().text('Please select State!');
                    else
                        $("#States").next().text('Please Enter State!');
                    valid = false;
                } else {
                    $('#States').next().empty();
                }
                if ($('#States').val() == "undefined") {
                    stateCode = '';
                    valid = false;
                } else {
                    stateCode = $('#States').val();
                }

                if (address1.value == '') {
                    $("#address1").next().text('Please enter the Address!');
                    valid = false;
                } else {
                    $('#address1').next().empty();
                }

                if (city.value == '') {
                    $("#city").next().text('Please enter the City!');
                    valid = false;
                } else {
                    $('#city').next().empty();
                }

                if (postCode.value == '') {
                    $("#postCode").next().text('Please enter the Postal Code!');
                    valid = false;
                } else {
                    $('#postCode').next().empty();
                }

                if (valid.length == 0) {
                    valid = true
                } else {
                    valid = false
                }

                return valid;
            };

            //Add New address Method
            $scope.addAddress = function () {
                $('#popLoader').show();
                $scope.validations();

                if (valid == true) {
                    $('.errorMsg').empty();

                    var newAddress = [{
                        addressType: $scope.addressType,
                        Country: $scope.Countrys.CountryDescription,
                        CountryCode: $scope.Countrys.CountryCode,
                        Address1: $scope.address1,
                        Address2: $scope.address2 || "",
                        City: $scope.city,
                        State: $("#States").val(),
                        PostalCode: $scope.postCode
                    }];

                    var saveAddArgu = { AddressObj: newAddress }
                    urlService.dataProvider(addAddressMethod, "POST", saveAddArgu).success(function (data) {
                        if (data != "ADDED_FAIL") {
                            $('#popLoader').hide();
                            jAlert('Address Added Successfully!');
                            $('#addAddress').hide();
                            $('.actions').hide();
                            $scope.addressType = '';
                            $scope.Countrys.CountryDescription = '';
                            $scope.Countrys.CountryCode = '';
                            $scope.address1 = '';
                            $scope.address2 = '';
                            $scope.city = '';
                            //$scope.States = $scope.StateList[0];
                            $scope.postCode = '';
                            //Update the existing address after new address added - Start
                            urlService.dataProvider(GetAddressesMethod, "POST", '').success(function (d) {
                                $scope.userAddress = d;
                                $.grep($scope.userAddress.AddressList, function (item) {
                                    item.BillToFlag = false;
                                    item.ShipToFlag = false;
                                });

                                $.grep(d.AddressList, function (i) {
                                    if (i.CustomerAddressId == data.CusAddressId) {
                                        if ($(addressType).val() == "Billing Address") {
                                            i.BillToFlag = true;
                                            $scope.BillingAddresses = [];
                                            $scope.BillingAddresses.push(i);
                                            //console.log($scope.BillingAddresses);
                                            sessionStorage.setItem('billingAdd', $scope.BillingAddresses[0].FormattedAddress);
                                            sessionStorage.setItem('BillingCustId', data.CusAddressId);
                                        } else {
                                            //if ($(addressType).val() == "Shipping Address") {
                                            i.ShipToFlag = true;
                                            $scope.ShippingAddresses = [];
                                            $scope.ShippingAddresses.push(i);
                                            sessionStorage.setItem('ShippingAdd', $scope.ShippingAddresses[0].FormattedAddress);
                                            sessionStorage.setItem('ShippingCustId', data.CusAddressId);
                                        }
                                        return
                                    }
                                    //    }
                                });
                                $scope.billingAddIdDiv = false;
                                $scope.shippingAddIdDiv = false;
                            });//End
                        }
                        else {
                            $('#popLoader').hide();
                            //jAlert('Please enter valid details!');
                            jAlert('Address not found');
                        }
                    }).error(function (x) {
                        $('#popLoader').hide();
                        jAlert(x);
                    });
                } else {
                    $('#popLoader').hide();
                    return
                }
            }
            //End

            //For Top search
            var wL = window.location + '';
            var wLArray = wL.split('/');
            var indexUrl = wLArray.indexOf("search");
            $scope.searchLoad = function () {

                if (wLArray[indexUrl] == "search") {
                    var topSearch = $("#topSearch").val(getParameterByName("SearchValue"));
                    window.location = applicationUrl + '/Product/search?SearchValue=' + ui.item.value;
                    $scope.SearchProducts();
                }
            };

            //ng-repeat callback function
            $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
                //zoomImage("Scope load Complete");
            });

            //ShipViaCodes
            $scope.shipViaCodeClient = function () {
                urlService.dataProvider(shipViaCodeMethod, 'POST', '').success(function (data) {
                    $scope.shipViaCode = data;
                    var defaultCountry = '';
                    if ($scope.ShippingAddresses != undefined)
                        defaultCountry = $scope.ShippingAddresses[0].CountryCode;

                    if (defaultCountry == "USA") {
                        $scope.shipViaCodeDD = $scope.shipViaCode[1];
                    }
                    else {
                        $scope.shipViaCodeDD = $scope.shipViaCode[0];
                    }
                }).error(function (x) {
                });
            }
            $scope.shipViaCodeClient();

            //get Favourites Products
            $scope.GetFavouriteItems = function (Masterid) {
                var getFavouritesArgu = { masterid: Masterid };
                urlService.dataProvider(getFavouriteItems, "POST", getFavouritesArgu).success(function (data) {
                    $scope.FavouriteItems = unique(data);
                });
            }

            //Delete Favourite Item
            $scope.DeleteFavouriteItem = function (productid) {
                $('#popLoader').show();
                var removeFavouriteArgu = { productid: productid };
                urlService.dataProvider(removeFavouriteItems, "POST", removeFavouriteArgu).success(function (data) {
                    $('#popLoader').hide();
                }).error(function () {
                    $('#popLoader').hide();
                });
                $scope.GetFavouriteItems($scope.sesCustomerId);
            }

            //Get Recently Viewed Items From LocalStorage
            var recentViewItemID = [];
            var existItem = [];

            if ($scope.sesCustomerId == null) {
                if (localStorage.getItem('RecentItems') != null) {
                    var xItems = localStorage.getItem('RecentItems').split(',');
                    if (xItems.length >= 6) {
                        var exItems = xItems.splice(6, xItems.length - 1);
                    };
                    existItem = $.grep(xItems, function (i) {
                        return $scope.id == i;
                    });
                };

                if (existItem.length == 0) {
                    recentViewItemID.push($scope.id);
                    recentViewItemID.push(xItems);
                } else {
                    recentViewItemID.push(xItems);
                };

                localStorage.setItem('RecentItems', recentViewItemID);
            };

            //Get Recently Viewed Items From Service
            $scope.GetrecentlyItems = function () {
                localStorage.removeItem('RecentItems');
                var custIdArgu = { productid: $scope.id };
                urlService.dataProvider(getRecentlyViewedItems, "POST", custIdArgu).success(function (data) {
                    $scope.recentView = data;
                    $.grep($scope.recentView, function (obj, i) {
                        recentViewItemID.push(obj.ProductId);
                    });
                    $("#recentlyViewdProducts").show();
                    if ($scope.recentView.length == 0) {
                        $("#recentlyViewdProducts span.noData").text("No Products Found.");
                    }
                    localStorage.setItem('RecentItems', recentViewItemID);
                });

            }

            //Get Recently Viewed Items
            $scope.GetrelatedItems = function () {
                var pdId = { productid: $scope.id };
                urlService.dataProvider(relatedProductsMethod, "POST", pdId).success(function (data) {
                    $scope.relatedView = data;
                    $("#relatedProducts").show();
                    if ($scope.relatedView.length == 0) {
                        $("#relatedProducts span.noData").text("No Products Found.");
                    }
                });
            }

            //Check Comments input length
            $scope.currentInputLength = "0 of 256";
            $scope.checklenth = function ($event) {
                if ($event.currentTarget.value.length <= 256) {
                    $scope.currentInputLength = $event.currentTarget.value.length + " of 256";
                } else {
                    $event.currentTarget.value = $event.currentTarget.value.substr(0, 255);
                }
            }

            //AddComments
            $scope.commentsDataView = [];
            var currentTimeStamp = '';

            //onLoadReviews
            $scope.loadReviews = function (selPrdId, count) {
                var getCommeArgu = { comments: "", productId: selPrdId, starRating: 0, ratingTitle: "" };
                urlService.dataProvider(getOrInsertProductRevuew, "POST", getCommeArgu).success(function (response) {
                    $scope.reviewLength = response.length;

                    $scope.commentsDataView = $.grep(response, function (obj, i) {
                        if (i <= count) {
                            return obj
                        };
                    });

                    $("#userReview").show();
                    $.grep($scope.commentsDataView, function (iObj, i) {
                        var resTime = $scope.commentsDataView[i].ReviewDate;
                        var conVTime = resTime.replace(/[()\D\a\t\e]/g, "");
                        iObj.ReviewDate = convertTimestamp(Math.round(conVTime / 1000.0));

                    });
                    if ($scope.commentsDataView.length == 0) {
                        $("#userReview span.noData").text("No Reviews Found.");
                    };

                    //calc Review load count out of total count
                    if ($scope.reviewLength > count) {
                        $scope.reviewInfo = (count + 1) + " out of " + $scope.reviewLength + " Reviews";
                    } else {
                        $scope.reviewInfo = $scope.reviewLength + " out of " + $scope.reviewLength + " Reviews";
                    };

                });
            };

            //Load More Reviews
            $scope.loadMore = function ($event) {
                var nextCount = parseFloat($($event.currentTarget).attr('data-reviewlength')) + 9;
                $scope.loadReviews($scope.id, nextCount);
            };

            //Insert Reviews
            $scope.addReviews = function () {

                if (typeof $scope.commentsInput === "undefined" || $scope.commentsInput == "") {
                    jAlert("Please Enter Comment.");
                } else if (currentUserRating == "undefined" || currentUserRating == '') {
                    jAlert("Please let us know your Rating.");
                    return
                } else {
                    $("#reviewPopup").find('#popLoader').show();
                    //Data Insert
                    var commeArgu = { comments: $scope.commentsInput, productId: $scope.id, starRating: currentUserRating, ratingTitle: "" };
                    urlService.dataProvider(getOrInsertProductRevuew, "POST", commeArgu).success(function (response) {
                        if (response != "SESSION_NULL" && response != "ERROR_FAIL") {
                            $scope.commentsDataView = response;
                            $.grep($scope.commentsDataView, function (iObj, i) {
                                var resTime = $scope.commentsDataView[i].ReviewDate;
                                var conVTime = resTime.replace(/[()\D\a\t\e]/g, "");
                                iObj.ReviewDate = convertTimestamp(Math.round(conVTime / 1000.0));
                            });

                            $("#reviewPopup").find('#popLoader').hide();
                            jAlert("Thanks for your Feedback.");
                        } else if (response == "SESSION_NULL") {
                            var currentUrl = window.location + '';
                            //window.location.href = applicationUrl + "/Login/Index" + '?url=' + currentUrl;
                            $('#LoginPopup').addClass('is-visible');
                        } else if (response == "ERROR_FAIL") {
                            jAlert("Please try again.");
                            $("#reviewPopup").find('#popLoader').hide();
                        }

                    });

                    $('#reviewPopup').removeClass('is-visible');
                    //Reset the values
                    $scope.commentsInput = '';
                    $scope.currentInputLength = "0 of 256";
                    //$().rating('select', 0)
                    $('div.star-rating').removeClass('star-rating-on');
                }

            };

            //Open Review Popup
            $scope.reviewPopup = function () {
                setTimeout(function () {
                    if ($scope.sesCustomerId == '') {
                        var currentUrl = window.location + '';
                        sessionStorage.setItem('fromReviewPop', 'fromReview');
                        //  window.location.href = applicationUrl + "/Login/Index" + '?url=' + currentUrl;
                        $('#LoginPopup').addClass('is-visible');
                    }
                    else
                        $('#reviewPopup').addClass('is-visible');
                }, 500);
            }

            //Open Login Popup
            $scope.LoginPopup = function () {
                setTimeout(function () {
                    if ($scope.sesCustomerId == '') {
                        $('#LoginPopup').addClass('is-visible');
                    } else {
                        var currentUrl = window.location + '';
                        //window.location.href = applicationUrl + "/Login/Index" + '?url=' + currentUrl;
                        $('#LoginPopup').addClass('is-visible');
                    }
                },
                    500);
            }

            $scope.Login = function () {
                if (typeof $scope.UserName === "undefined" || $scope.UserName == "") {
                    jAlert("Please Enter Username.");
                } else if (typeof $scope.Password == "undefined" || $scope.Password == '') {
                    jAlert("Please Enter Password.");
                } else {
                    // var ChkRememberMe = $('input[name="ChkRM"]:checked')
                    var ChkRememberMe = $("#ChkRM").is(":checked");
                    $("#LoginPopup").find('#LoginpopLoader').show();
                    //Data Insert
                    var currentUrl = window.location.href;
                    var commeArgu = { Email: $scope.UserName, Password: $scope.Password, CurrentUrl: currentUrl, RememberMe: ChkRememberMe };
                    urlService.dataProvider(LoginInfo, "POST", commeArgu).success(function (response) {
                        if (response.Success) {
                            //window.location.href = response.SSOURL;

                            window.location.href = currentUrl;
                            $scope.UserName = '';
                            $scope.Password = '';
                            if (sessionStorage.setItem("CustomPro") != null && sessionStorage.setItem("CustomPro") == "fromCompse") {
                                localStorage.setItem("CustomPro", "true");
                            }
                        }
                        else {
                            $('#LoginPopup').addClass('is-visible');
                            jAlert("Please Enter valid Username and Password.");
                            $("#LoginPopup").find('#LoginpopLoader').hide();
                            return;
                        }

                    });

                }

            };

            //AddToCart
            $scope.AddToCartR = function ($event) {
                show();
                $('#alrtMsg').empty();
                var avQal = $($event.target).parent().find('#aQval').text();
                var productid = $($event.target).attr('id');
                var bo = $('#bo').attr('data-bo');
                var quantity = 1;
                var from = "add";
                var customOrStandard = $scope.viewUmbrellProductDD;
                var shippreference = '';
                if ($scope.shipViaCodeDD != undefined)
                    shippreference = $scope.shipViaCodeDD.Code;

                var cartArgu = { ProductId: productid, Quantity: quantity, From: from, StrCustomOrStandard: customOrStandard, shipviacode: shippreference };
                if (parseInt(avQal) != 0) {
                    urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                        if (data == "PRODUCTMEMBER_ONLY") {
                            if ($scope.sesCustomerId != '') {
                                jAlert('This Product is only for members.');
                            } else {
                                jConfirm("This product is for Members Only please login to add to you cart or cancel to return to the previous screen?", function (status) {
                                    if (status == true) {
                                        var currentUrl = window.location + '';
                                        //window.location.href = applicationUrl + "/Login/Index" + '?url=' + currentUrl;
                                        $('#LoginPopup').addClass('is-visible');
                                    }
                                });
                            }
                        }
                        if (data.indexOf("REMAINING_") != -1) {
                            jAlert('You remain to add upto ' + parseFloat(data.replace('REMAINING_', '')) + ' out of ' + parseFloat(avQal) + '!');
                        }
                        else if (data == "ADDED_FAIL") {
                            jAlert('Unable to add product to cart,Please try later.');
                        }
                        $scope.getCartData();
                        hide();

                        if (data == "ADDED_SUCCESSFULLY") {
                            $("#cartMsg").show(function () {
                                setTimeout(function () { $("#cartMsg").hide(); }, 2000);
                            });
                        }


                    });
                } else {
                    if (bo == "true") {
                        //jConfirm("Are you sure you want to place a backorder for this item?", function (status) {
                        //    if (status == true) {
                        urlService.dataProvider(addToCartMethod, "POST", cartArgu).success(function (data) {

                            if (data == "PRODUCTMEMBER_ONLY") {
                                jAlert('This Product is only for members.');
                            }
                            if (data.indexOf("REMAINING_") != -1) {
                                jAlert('You remain to add upto ' + parseFloat(data.replace('REMAINING_', '')) + ' out of ' + parseFloat(avQal) + '!');
                            }
                            else if (data == "ADDED_FAIL") {
                                jAlert('Unable to add product to cart,Please try later.');
                            }
                            $scope.getCartData();
                            hide();

                            if (data == "ADDED_SUCCESSFULLY") {
                                $("#cartMsg").show(function () {
                                    setTimeout(function () { $("#cartMsg").hide(); }, 2000);
                                });
                            }

                        });
                        //    } else {
                        //        hide();
                        //    }
                        //});
                    } else {
                        hide();
                        jAlert('Out Of Stock!');
                    }
                }
            };

            $scope.getCartData = function () {
                urlService.dataProvider(cartDetailsMethod, "POST", '').success(function (data) {

                    if (data == "ADDED_FAIL") {
                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalItems = 0;
                        $scope.CartDetailsLength = $scope.CartDetails.length;
                        //
                        //console.log("1 - " + $scope.CartDetails.length);
                        jAlert('Unable to get cart details,Please try later.');
                    }
                    else if (data != "NO_DETAILS_FOUND") {

                        var totalCartPrice = 0, totalItems = 0;

                        $.each(data, function (index, obj) {
                            if ($scope.sesUserIsMember == '1') {
                                totalCartPrice = totalCartPrice + (obj.Quantity * obj.product.MemberPrice);
                            } else {
                                totalCartPrice = totalCartPrice + (obj.Quantity * obj.product.Price);
                            }
                            totalItems = totalItems + (obj.Quantity);
                        });

                        $scope.CartDetails = data;
                        //console.log("2 - " + $scope.CartDetails.length);
                        $scope.CartDetailsLength = $scope.CartDetails.length;
                        $scope.TotalPrice = totalCartPrice;
                        $scope.TotalItems = totalItems;


                    } else {

                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalItems = 0;
                        //console.log("3 - " + $scope.CartDetails.length);
                        $scope.CartDetailsLength = $scope.CartDetails.length;
                    }

                });
            };

            $scope.ProductCompose = function (Productname, GroupName, Templatename) {
                show();
                /* To Open Popup after login */
                if ($scope.sesCustomerId == '') {
                    sessionStorage.setItem("CustomPro", "fromCompse");
                    var currentUrl = window.location + '';
                    $('#LoginPopup').addClass('is-visible');
                    hide();
                    return false;
                }
                if ($scope.sesUserIsMember != "1") {
                    jAlert('This Product is only for members.');
                    sessionStorage.removeItem("CustomPro");
                    hide();
                    return false;
                }

                //$scope.AddToCart(Productname);
                //if ($scope.cartSuccess == true) {
                var getCommeArgu = { ProductName: Productname, Group: GroupName, TemplateName: Templatename };
                urlService.dataProvider(ProductComposeFileds, "POST", getCommeArgu).success(function (response) {
                    if (response != "No Codes Received") {
                        //Create a HTML Table element.
                        var table = document.createElement("TABLE");
                        table.width = "100%";
                        table.border = "1";

                        //Add the data rows.
                        for (var i = 0; i < response.Fields.length; i++) {
                            row = table.insertRow(-1);
                            var cell = row.insertCell(-1);
                            cell.width = '30%';
                            cell.innerHTML = response.Fields[i]['FiledName'];
                            var cell = row.insertCell(-1);
                            var RequriedFiled = '';
                            var RequriedFiledMark = '';
                            if (response.Fields[i]['RequriedFiled']) {
                                RequriedFiled = 'required';
                                RequriedFiledMark = '<span>*</span>';
                            }

                            cell.innerHTML = '<input class="ng-pristine ng-valid ng-touched" id="' + response.Fields[i]['FiledName'] + '" type="text"  value="' + response.Fields[i]['FiledValue'] + '" ' + RequriedFiled + ' /> ' + RequriedFiledMark + '';
                        }

                        var dvTable = document.getElementById("tblPreview");
                        dvTable.innerHTML = "";
                        dvTable.appendChild(table);

                        var VPageCount = response.NoOfPages;
                        //Show Paging
                        $('#lblComposeId').val(response.ComposeID);
                        $("#DivPaging button").remove();
                        //console.log($('#lblComposeId').val());
                        for (var i = 1; i <= VPageCount; i++) {
                            var btnhtml = "<button class='' style='background-image: none;'>" + i + "</button>";
                            var newButt = angular.element(btnhtml);
                            newButt.bind('click', $scope.ComposePagePreview);
                            angular.element($("#DivPaging").append(newButt));
                        }
                        //Show Paging End

                        $('#lblGroup').val(GroupName);
                        $('#lblTemplatename').val(Templatename);
                        $('#lblProductId').val(Productname);
                        $("#Imgpreview").attr("src", response.ImgUrl);
                        //$('#CreateProof').prop('disabled', true);
                        $('#ProductPreview').addClass('is-visible');
                        sessionStorage.removeItem("CustomPro");
                        sessionStorage.removeItem("UMBID");
                        hide();
                    }
                    else {
                        jAlert('No template found.');
                        sessionStorage.removeItem("CustomPro");
                        sessionStorage.removeItem("UMBID");
                        hide();
                    }

                });
                //else {
                //            hide();
                //        }
            }

            $scope.ComposePreview = function () {
                var div = document.getElementById('tblPreview');
                var Flag = true;
                var ComposeFiledsWithValues = '';
                $("#ProductPreview").find('#PreviewpopLoader').show();
                $(div).find('input:text').each(function () {
                    var IsReq = $(this).attr('required');
                    if (IsReq != undefined && $(this).val().trim() == '') {
                        jAlert("Please Enter " + this.id);
                        Flag = false;
                        return false;
                    }
                    if (ComposeFiledsWithValues == '')
                        ComposeFiledsWithValues = this.id + ';' + $(this).val();
                    else
                        ComposeFiledsWithValues = ComposeFiledsWithValues + '#' + this.id + ';' + $(this).val();

                });

                var Group = $('#lblGroup').val();
                var Templatename = $('#lblTemplatename').val();

                if (Flag) {
                    var getCommeArgu = { GroupName: Group, TemplateName: Templatename, ComposeData: ComposeFiledsWithValues, PageNumber: '0' };
                    urlService.dataProvider(ComposePreview, "POST", getCommeArgu).success(function (response) {
                        if (response['ErrorMsg'] == "") {
                            $("#Imgpreview").attr("src", response['FiledPath']);
                            $("#lblComposeId").val(response['CompositionID']);
                            //  $('#CreateProof').prop('disabled', false);
                            $("#ProductPreview").find('#PreviewpopLoader').hide();
                            $("#hlkDownload").attr("href", response['DownloadLink']);

                            //Show Paging
                            //clear old buttons
                            $("#DivPaging button").remove();
                            var count = $("#lblCount").val();
                            for (var i = 1; i <= count; i++) {
                                var btnhtml = "<button class='' style='background-image: none;'>" + i + "</button>";
                                var newButt = angular.element(btnhtml);
                                newButt.bind('click', $scope.ComposePagePreview);
                                angular.element($("#DivPaging").append(newButt));
                            }
                            //Show Paging End

                            $("#spanDDL").show();
                        }
                        else {
                            jAlert(response['ErrorMsg']);
                            $("#ProductPreview").find('#PreviewpopLoader').hide();
                        }
                    });
                }
            };

            $scope.ComposePagePreview = function () {
                var pgnum = $(this).text();
                var getCommeArgu = { CompositionID: $("#lblComposeId").val(), PageOrChunkNumber: pgnum };
                urlService.dataProvider(GetPageURLPreview, "POST", getCommeArgu).success(function (response) {
                    if (response != 'File Not Found') {
                        $("#Imgpreview").attr("src", response);
                    }
                });
            };

            $scope.ComposePreviewClose = function () {
                $('#ProductPreview').removeClass('is-visible');
            };

            $scope.ComposeAddCart = function ($event, from) {

                if ($("#lblComposeId").val().trim() != '') {
                    $scope.AddToCart($("#lblProductId").val(), $event, from);
                    $('#ProductPreview').removeClass('is-visible');
                } else {
                    jAlert("Please preview the document before submitting it to shopping cart.");
                }

            }
        }]);


;
AoaShopping.filter('startFrom', function () {
    return function (input, start) {

        if (!input || !input.length) { return; }
        start = +start; //parse to int
        return input.slice(start);
    };
});

//Html string filter service
AoaShopping.filter("sanitize", ['$sce', function ($sce) {
    return function (htmlCode) {
        return $sce.trustAsHtml(htmlCode);
    }
}]);

//Image not available or image link borken 
AoaShopping.directive('noImage', function (defaultImg) {
    var setDefaultImage = function (el) {
        el.attr('src', defaultImg.noImageUrl);
    };

    return {
        restrict: 'A',
        link: function (scope, el, attr) {
            //Set loading is true at the time when load the page.
            scope.loading = true;

            scope.$watch(function () {
                scope.loading = false;
                return attr.ngSrc;
            }, function () {
                var src = attr.ngSrc;
                if (!src) {
                    setDefaultImage(el);
                    scope.loading = false;
                }
            });

            el.bind('error', function () { setDefaultImage(el); });

        }

    }
});

//restric Input Limit 
AoaShopping.directive("limitTo", ['$compile', function ($compile) {
    return {
        restrict: "A",
        link: function (scope, elem, attrs) {
            angular.element(elem).on("keypress", function (evt) {

                evt = (evt) ? evt : window.event;
                var charCode = (evt.which) ? evt.which : evt.keyCode;
                if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                    return false;
                }
                var limit = parseInt(attrs.limitTo);

                if (this.value.length == limit) {
                    this.value = this.value.substr(0, this.value.length - 1);
                    return
                }
            });
        }
    }
}]);

//Allow only Alpha Numeric
//AoaShopping.directive("alphaNumberic", [function () {
//    return {
//        restrict: "A",
//        link: function (scope, elem, attrs) {
//            angular.element(elem).on("keypress", function (e) {
//                var evt = window.event || e;
//                var regex = new RegExp("^[a-zA-Z0-9 ]+$");
//                var str = String.fromCharCode(!evt.charCode ? evt.which : evt.charCode);
//                console.log(regex.test(str))
//                if (regex.test(str)) {
//                    return true;
//                }
//                e.preventDefault();
//                return false;
//            });
//        }
//    }
//}]);
AoaShopping.directive('alphaNumberic', function ($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, iElement, iAttrs, controller) {
            scope.$watch(iAttrs.ngModel, function (value) {
                if (!value) {
                    return;
                }
                $parse(iAttrs.ngModel).assign(scope, value.replace(new RegExp(iAttrs.alphaNumberic, 'g'), '').replace(/\s+/g, ' '));
            });
        }
    }
});
//string length cut
AoaShopping.directive("limitDesc", [function () {
    return {
        restrict: "A",
        link: function (scope, elem, limit) {
            limit = angular.element(elem).attr('data-limit');
            scope.$watch(function () {
                var x = angular.element(elem);
                var elemText = x.text().substr(0, limit);
                if (x.text().length > limit) {
                    x.text(elemText + '...');
                }

            });
        }
    }
}]);

//Event calls after loop completion
AoaShopping.directive('ngRepeatLoadFinish', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elm, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    };
}]);

//View Ratings with Comments
AoaShopping.directive("ratingStars", ['$compile', function ($compile) {


    var myCount = 0;
    return {
        restrict: 'AE',

        controller: function ($scope, $attrs, $element) {
            $attrs.$observe('item', function (newVal, oldVal) {
                if (newVal) {
                    var el = $compile('<p id="rating' + myCount++ + '"><span class="stars" id="stars' + myCount++ + '"><span style="width:' + (Math.max(0, (Math.min(5, parseFloat(newVal)))) * 16) + 'px;"></span></span></p>')($scope);
                    $element.append(el);
                }
            })
        }
    };
}]);
;
//Get data from Methods
var sessionMethod = '/Product/GetSessionInfo',
    categoryMethod = '/home/getItems',
    allProductsMethod = '/home/GetProducts',
    addToCartMethod = '/Product/AddProductToCart',
    cartDetailsMethod = '/Product/GetCartDetails',
    saveWishlistMethod = '/Product/SaveWishList',
    getWishlistMethod = '/Product/GetWishListItems',
    getCountryMethod = '/Order/GetCountries',
    getStateMethod = '/Order/GetStates',
    GetAddressesMethod = '/Order/GetAddresses',
    GetCreditCardMethod = '/Order/GetCreditCards',
    createOrderMethod = '/Order/CreateOrderNew',
    getOrderdeatilsMethod = '/Order/GetOrderdeatils',
    addCCardMethod = '/Order/AddCreditCard',
    addAddressMethod = '/Order/AddAddress',
    shipViaCodeMethod = '/Order/GetShipViaCodes',
    getFavouriteItems = '/Product/GetFavouriteItems',
    removeFavouriteItems = '/Product/RemoveFavouriteItem',
    relatedProductsMethod = '/Product/GetRelatedItems',
    getRecentlyViewedItems = '/Product/GetRecentlyViewedItems',
    addRecentlyViewedItems = '/Product/AddToRecentlyVieweddItem',
    getOrInsertProductRevuew = '/Product/GetProductReviews',
    LoginInfo = '/Login/LoginInfo',
    ProductComposeFileds = '/Order/ProductComposeFileds',
    ComposePreview = '/Order/PreviewUrl',
    setAddress = '/Order/ChangeAddress',
    getSingleProduct = '/Product/GetProductDetails',
    GetPageURLPreview = "/Order/GetPageURL";
getRegisterUrl = "/Home/GetRegisterURL";


//set Default image service
AoaShopping.factory('defaultImg', function () {
    return {
        noImageUrl: "http://avenir-it.com/HRMS/Images/Image-not-available.png"
    };
});

//Accessing all methods
AoaShopping.factory('urlService', ['$http', function ($http) {
    show();
    return {
        dataProvider: function (url, type, params) {
            return $http({
                method: type,
                url: applicationUrl + url,
                params: params,
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            }).success(function (data) {
                return data;
            }).error(function (x) {

            });
        }
    }
}]);

AoaShopping.factory("productCart", function ($http, $log, $q, urlService) {
    function addingToCart(obj, scope, from) {
        if (from == 'delete')
            $('#popLoader').show();
        urlService.dataProvider(addToCartMethod, "POST", obj).success(function (data) {
            if (data == "PRODUCTMEMBER_ONLY") {
                if (scope.sesCustomerId != '') {
                    jAlert('This Product is only for members.');
                } else {
                    jConfirm("This product is for Members Only. \n please login to add to your cart or cancel to return to the previous screen?", function (status) {
                        if (status == true) {
                            var currentUrl = window.location + '';
                            $('#LoginPopup').addClass('is-visible');
                        }
                    });
                }
            }
            if (data.indexOf("REMAINING_") != -1) {
                jAlert('You remain to add upto ' + parseFloat(data.replace('REMAINING_', '')) + ' out of ' + parseFloat(this.currentProduct.StockAvailable) + '!');
            }
            else if (data == "ADDED_FAIL") {
                jAlert('Unable to add product to cart, Please try later.');
            }

            var winLoc = window.location + '',
                wLArray = winLoc.split('/'),
                pageUrl = wLArray.indexOf("Product");

            if (pageUrl > -1) {
                scope.GetCartProducts(from);
            } else {
                scope.getCartData();
            }

            hide();

            if (from == 'delete')
                $('#popLoader').hide();

            if (data == "ADDED_SUCCESSFULLY") {
                /* Deleting Wishlist item once its added to cart */
                if (from == "wishlist")
                    scope.AddToWishList(obj.ProductId, scope.sesCustomerId);

                $("#cartMsg").show(function () {
                    setTimeout(function () { $("#cartMsg").hide(); }, 2000);
                });
            }
        }).error(function () {
            try {
                hide();
                $('#popLoader').hide();
            } catch (e) {

            }
        });
    };
    return {
        currentProduct: '',
        view: true,
        wishlist: false,
        favourite: false,
        userQuantity: '',
        isUmbrella: false,

        ProductAddToCart: function (id, scope, from, event) {
            show();
            var selectedProd = id;
            $('#alrtMsg').empty();
            if ($("#avalQuantity").val() == 0) {
                jAlert("Minimum Quantity Should be 1!");
                return
            }
            var getEvent = window.event || event;
            this.productSetting(from);
            this.getProductItem(id, getEvent).success(function (d) {
                //debugger;
                if ($(getEvent.target).attr("data-umb") != "true" || typeof $(getEvent.target).attr("data-umb") === "undefined") {
                    this.currentProduct = d;
                } else {
                    this.currentProduct = $.grep(d.UmbrellaSubProducts, function (itemType, i) {
                        return itemType.ProductId == selectedProd;
                    });
                    this.currentProduct = this.currentProduct[0];
                    
                };
                var cartArgu = {
                    ProductId: this.currentProduct.ProductId,
                    Quantity: from == "delete" ? 0 : $("#avalQuantity").val() || $("#" + this.currentProduct.ProductId).val() || 1,
                    From: from,
                    StrCustomOrStandard: scope.viewUmbrellProductDD || '',
                    ComposeID: '',
                    shipviacode: scope.shipViaCodeDD || ''
                };
                //console.log(this.currentProduct.Inventoried);

                if (this.currentProduct.Inventoried == true) {
                    if (this.currentProduct.StockAvailable >= 1) {
                        if (this.currentProduct.StockAvailable >= parseFloat($("#avalQuantity").val() || $("#" + this.currentProduct.ProductId).val()) || typeof $("#avalQuantity").val() === "undefined") {
                            addingToCart(cartArgu, scope, from);
                        } else {
                            hide();
                            jAlert('This Product Stock Availability upto ' + parseFloat(this.currentProduct.StockAvailable) + '!');
                            return
                        }
                    } else {
                        //console.log("Check Backorder is available");
                        if (this.currentProduct.BackorderAvailable == true && this.currentProduct.StockAvailable <= 0) {
                            //jConfirm("Are you sure you want to place a backorder for this item?", function (status) {
                            //    if (status == true) {
                            addingToCart(cartArgu, scope, from);
                            //    } else {
                            //        hide();
                            //    }
                            //});
                        } else {
                            hide();
                            jAlert('Out Of Stock!');
                        }
                    }
                } else {

                    addingToCart(cartArgu, scope, from);
                }
            });
        },
        ProductUpdatedFromCart: function () {

        },
        getProductItem: function (itemId, umb) {
            var umbProduct = $(umb.target).attr("data-umb");
            if (umbProduct != "true") {
                var deferred = $q.defer();
                return $http({
                    method: "GET",
                    url: applicationUrl + '/Product/GetProductDetails',
                    params: { ProductId: itemId },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                }).success(function (data) {
                    //console.log("Product");
                    //console.log(data);
                    deferred.resolve(data);
                }).error(function (x) {
                    deferred.reject(x);
                });
                return deferred.promise;
            } else {
                itemId = $(umb.target).attr("data-parenetId")
                var deferred = $q.defer();
                return $http({
                    method: "GET",
                    url: applicationUrl + '/Product/GetSubProductDetails',
                    params: { ProductId: itemId },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                }).success(function (data) {
                    //console.log("Sub Product");
                    //console.log(data);
                    deferred.resolve(data);
                }).error(function (x) {
                    deferred.reject(x);
                });
                return deferred.promise;
            }
        },
        productSetting: function (from) {
            if (from == "wishlist") {
                this.wishlist = true;
            } else if (from == "fav") {
                this.favourite = true;
            } else {
                this.wishlist = false;
                this.favourite = false;
            };
        }

    }
});;
