/* Minification failed. Returning unminified contents.
(2343,41-48): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: selItem
(2436,41-48): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: selItem
 */
var applicationUrl = "https://my.siam.org/Store";

var SIAMShopping = angular.module('SIAMShopping', ['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'
});

//create bookSeries submenu for mobile screen
// plays on page load?
function CreateBookSeriesSubMenu() {
	
	var sub_menu = document.getElementsByClassName("sub_menu");
sub_menu[1].innerHTML = '';

 var childNodes = sub_menu[0].childNodes,
        children = [],
        i = childNodes.length;

    while (i--) {
        if (childNodes[i].nodeType == 1) {
            children.unshift(childNodes[i]);
        }
    }

 for (i = 0; i < children.length; i++) { 
    sub_menu[1].innerHTML += children[i].outerHTML;
}



	//console.log("CreateBookSeriesSubMenu"); 
    //document.getElementsByClassName("slicknav_arrow").onclick=CreateBookSeriesSubMenu();
	//document.getElementsByClassName("bookSeries").href="xyz.php";
};

	
function start_carousel() {
    $('#itemslider').carousel({ interval: 5000 });
    $('#itemslider1').carousel({ interval: 5000 });
    $('#itemslider2').carousel({ interval: 5000 });
    $('#itemslider3').carousel({ interval: 5000 });
    $('#itemslider4').carousel({ interval: 5000 });
    $('.carousel-showmanymoveone1 .item').each(function () {
        var itemToClone = $(this);
        for (var i = 1; i < 1; i++) {
            itemToClone = itemToClone.next();

            if (!itemToClone.length) {
                itemToClone = $(this).siblings(':first');
            }

            itemToClone.children(':first-child').clone()
                .addClass("cloneditem-" + (i))
                .appendTo($(this));
        }
    });
    $('.carousel-showmanymoveone .item').each(function () {
        var itemToClone = $(this);

        for (var i = 1; i < 4; i++) {
            itemToClone = itemToClone.next();

            if (!itemToClone.length) {
                itemToClone = $(this).siblings(':first');
            }

            itemToClone.children(':first-child').clone()
                .addClass("cloneditem-" + (i))
                .appendTo($(this));
        }
    });

}

//Slider
function slideShow() {
    setTimeout(function () {
        var imgArray = $('.slideImg');
        $('#slides').slidesjs({

            width: 870,
            height: 280,

            navigation: {
                active: imgArray.length <= 1 ? false : true,
                // [boolean] Generates next and previous buttons.
                // You can set to false and use your own buttons.
                // User defined buttons must have the following:
                // previous button: class="slidesjs-previous slidesjs-navigation"
                // next button: class="slidesjs-next slidesjs-navigation"
                effect: "slide"
                // [string] Can be either "slide" or "fade".
            },

            effect: {
                slide: {
                    // Slide effect settings.
                    speed: 200
                    // [number] Speed in milliseconds of the slide animation.
                },
                fade: {
                    speed: 50,
                    // [number] Speed in milliseconds of the fade animation.
                    crossfade: false
                    // [boolean] Cross-fade the transition.
                }
            },

            pagination: {
                active: false,
                // [boolean] Create pagination items.
                // You cannot use your own pagination. Sorry.
                effect: "slide"
                // [string] Can be either "slide" or "fade".
            },
            play: {
                active: true,
                // [boolean] Generate the play and stop buttons.
                // You cannot use your own buttons. Sorry.
                effect: "slide",
                // [string] Can be either "slide" or "fade".
                interval: 5000,
                // [number] Time spent on each slide in milliseconds.
                auto: true,
                // [boolean] Start playing the slideshow on load.
                swap: true,
                // [boolean] show/hide stop and play buttons
                pauseOnHover: true,
                // [boolean] pause a playing slideshow on hover
                restartDelay: 2500,
                // [number] restart delay on inactive slideshow

            }

        });
    }, 2000);
    setTimeout(function () {
        var imgArray1 = $('.slideImg1');
        $('#slide1').slidesjs({

            width: 870,
            height: 280,

            navigation: {
                active: imgArray1.length <= 1 ? false : true,
                // [boolean] Generates next and previous buttons.
                // You can set to false and use your own buttons.
                // User defined buttons must have the following:
                // previous button: class="slidesjs-previous slidesjs-navigation"
                // next button: class="slidesjs-next slidesjs-navigation"
                effect: "slide"
                // [string] Can be either "slide" or "fade".
            },

            effect: {
                slide: {
                    // Slide effect settings.
                    speed: 200
                    // [number] Speed in milliseconds of the slide animation.
                },
                fade: {
                    speed: 50,
                    // [number] Speed in milliseconds of the fade animation.
                    crossfade: false
                    // [boolean] Cross-fade the transition.
                }
            },

            pagination: {
                active: false,
                // [boolean] Create pagination items.
                // You cannot use your own pagination. Sorry.
                effect: "slide"
                // [string] Can be either "slide" or "fade".
            },
            play: {
                active: true,
                // [boolean] Generate the play and stop buttons.
                // You cannot use your own buttons. Sorry.
                effect: "slide",
                // [string] Can be either "slide" or "fade".
                interval: 5000,
                // [number] Time spent on each slide in milliseconds.
                auto: true,
                // [boolean] Start playing the slideshow on load.
                swap: true,
                // [boolean] show/hide stop and play buttons
                pauseOnHover: true,
                // [boolean] pause a playing slideshow on hover
                restartDelay: 2500,
                // [number] restart delay on inactive slideshow

            }

        });
    }, 2000);
    setTimeout(function () {
        var imgArray2 = $('.slideImg2');
        $('#slide2').slidesjs({

            width: 870,
            height: 280,

            navigation: {
                active: imgArray2.length <= 1 ? false : true,
                // [boolean] Generates next and previous buttons.
                // You can set to false and use your own buttons.
                // User defined buttons must have the following:
                // previous button: class="slidesjs-previous slidesjs-navigation"
                // next button: class="slidesjs-next slidesjs-navigation"
                effect: "slide"
                // [string] Can be either "slide" or "fade".
            },

            effect: {
                slide: {
                    // Slide effect settings.
                    speed: 200
                    // [number] Speed in milliseconds of the slide animation.
                },
                fade: {
                    speed: 50,
                    // [number] Speed in milliseconds of the fade animation.
                    crossfade: false
                    // [boolean] Cross-fade the transition.
                }
            },

            pagination: {
                active: false,
                // [boolean] Create pagination items.
                // You cannot use your own pagination. Sorry.
                effect: "slide"
                // [string] Can be either "slide" or "fade".
            },
            play: {
                active: true,
                // [boolean] Generate the play and stop buttons.
                // You cannot use your own buttons. Sorry.
                effect: "slide",
                // [string] Can be either "slide" or "fade".
                interval: 5000,
                // [number] Time spent on each slide in milliseconds.
                auto: true,
                // [boolean] Start playing the slideshow on load.
                swap: true,
                // [boolean] show/hide stop and play buttons
                pauseOnHover: true,
                // [boolean] pause a playing slideshow on hover
                restartDelay: 2500,
                // [number] restart delay on inactive slideshow

            }

        });
    }, 2000);
};

var showHide = 0;
$(document).ready(function () {
    setTimeout(function () {
        start_carousel();
    }, 3000);  

    $("#show_banner").on("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;
        }
    });

    //PopUp Product close
    $('#popClose').on("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');
        $('#products_viewbrowse').removeClass('pd_gridView').addClass('pd_listView');

    } else if (id == "pd_gridView") {
        $('#products_view').removeClass('pd_listView').addClass('pd_gridView');
        $('#products_viewbrowse').removeClass('pd_listView').addClass('pd_gridView');
    }
};

// Cart Popup
jQuery(document).ready(function ($) {

    var sesCustomerId = '';
    //close popup
    $('.cart-popup').on('click', function (event) {
        if ($(event.target).is('.cart-popup-close') || $(event.target).is('.cart-popup')) {
            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).on("keyup",function (e) {
        if (e.which == '27') {
            $('.cart-popup').removeClass('is-visible');
        }

    });
    
    $(document).on("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').on("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);
    });

    $("input:file").on("change", function () {
        var data = new FormData();
        var files = $(this).get(0).files;
        if (files.length > 0) {
            data.append("MyImages", files[0]);
        }

        $.ajax({
            url: applicationUrl + "/Product/UploadFile",
            type: "POST",
            processData: false,
            contentType: false,
            data: data,
            success: function (response) {
                ////code after success
                //$("#txtImg").val(response);
                //$("#imgPreview").attr('src', '/Upload/' + response);
                $("#imagepath").val(response);
            },
            error: function (er) {
                alert(er);
            }

        });
    });
});

$(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').on("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=SIAMShopping]');
        var appScope = angular.element(appElement).scope();
        var controllerScope = appScope.$$childHead;

        if ($(this).attr('id') == 'myCart') {
            if (controllerScope.CartDetailsLength == '') {
                $('#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) {
    if ((typeof origArr === "undefined"))
        return [];
    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) {
    $('.slider_book').hide();
    $('.slider_main').hide();
    //$('.search_with_category').hide();

    $('.product_data').show();
    $('.page_title').show();
    $('.sorting_navigation').show();

    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',
		prependTo:'#account_nav_mobile',
		//prependTo:'.site_navigation',
        closeOnClick: true,
        allowParentLinks: true,
		label: "Menu"
    });
	
	$(".slicknav_arrow").remove();
	var anchor = document.getElementsByClassName("bookSeries");
	anchor[1].insertAdjacentHTML('afterend', '<span class="slicknav_arrow" onclick="CreateBookSeriesSubMenu()">►</span>');
	anchor[1].outerHTML = '<a href="#" class="bookSeries" onclick="CreateBookSeriesSubMenu()" style="padding-left: 0px !important">BOOK SERIES</a>'
	
	// add onclick blah for entire button....

	
	// this was working
	//document.getElementsByClassName("slicknav_arrow").onclick=CreateBookSeriesSubMenu();
	//document.getElementsByClassName("bookSeries").href="xyz.php";
    //$(".site_navigation ul li a").click(function (e) {
    //    $(".site_navigation ul li a").removeClass("current");
    //    $(this).addClass("current");

    //});
});

/*
$(document).ready(function () {

    $('.sub_menu').slicknav({
        prependTo:'.bookSeries',
        closeOnClick: true,
        allowParentLinks: true
    });

});
*/

$(window).on('scroll',function () {
    var sticky = $('#site_header'), scroll = $(window).scrollTop();
    if (scroll >= 10) {
        sticky.addClass('headerFixed');
    }
    else { sticky.removeClass('headerFixed'); }
});

// Mobile Account Menu	
/*
$(document).ready(function () {
    $('.account_links').slicknav({
        //prependTo: '#account_nav_mobile', account_links
        //label: 'My Account',
        closeOnClick: true,
        allowParentLinks: true
    });

    $(document).on('click', '.add_credit_cart_btn', function (event) {
        $('#CreditCardForm').show();
        $("#useOtherVal").text("true");
    });
});
*/
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 {
        window.location.href = applicationUrl + href;
    }
}

$(document).ready(function () {
    setTimeout(function () {
        if (sessionStorage.getItem('fromCartPop') == "fromCart") {
            var scope = angular.element(document.getElementById('site_header')).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');
            });
        }
    }, 500);
});

function register() {
    window.location.href = "/Login/Register?return=" + encodeURIComponent('/login?redir=' + window.location);
}

function CALLProxy(method) {
    sessionStorage.removeItem("Format");
    sessionStorage.removeItem("Category");
    sessionStorage.removeItem("Topic");
    sessionStorage.removeItem("member");
    sessionStorage.removeItem("nonmember");


    $.ajax({
        url: applicationUrl + method,
        type: "POST",
        processData: false,
        contentType: false,

        success: function (response) {

            window.location.href = applicationUrl + method;
        },
        error: function (er) {
            alert(er);
        }

    });
}
function GetFAQ() {
    CALLProxy("/Home/FAQ");
}

function GetEbooksInfo() {
    CALLProxy("/Home/Ebooks");
}

function GetTextBooks() {
    CALLProxy("/Home/TextBooks");

}

function GetOnSale() {
    CALLProxy("/Home/OnSale");

}

function GetTitleIndex() {
    CALLProxy("/Home/TitleIndex");

}
function GetAuthor() {

    CALLProxy("/Home/AuthorsEditorsIndex");
}

function BrowseProducts() {

    CALLProxy("/Home/Browse");

}


function selectcat(catid) {
    /*
    console.log("select cat clicked");
    var currentUrl = window.location.href;
    console.log(currentUrl);
    if (currentUrl.includes('/Product/viewproduct/')) {
        window.location.href = "https://my-test.siam.org/Store/Home/Browse";
    }
    */

    var i = catid;
    var loc = window.location.href;
    var viewprod = '/Product/viewproduct';
    var viewAuthor = '/Home/AuthorsEditorsIndex';
    var viewTitle = '/home/TitleIndex';
    var viewTextBook = '/Home/TextBooks';
    var bookseries = '/Home/BookSeries';
    var viewOnSale = '/Home/OnSale';
    var FAQ = '/Home/FAQ';
    var EBooks = '/Home/Ebooks';
    var browse = '/Home/Browse';

    $('span.catTags a').trigger("click");
    if (loc.indexOf(EBooks) > -1 || loc.indexOf(FAQ) > -1 || loc.indexOf(viewprod) > -1 || loc.indexOf(viewAuthor) > -1 || loc.indexOf(viewTitle) > -1
        || loc.indexOf(viewTextBook) > -1 || loc.indexOf(bookseries) > -1 || loc.indexOf(viewOnSale) > -1 || i >= 0) {   //MPF: removed  'i==3 || i==2) {' added i>0
        $('.category').each(function () {
            if ($(this).attr('id') == catid) {
                $(this).prop("checked", true);

                if (loc.indexOf(viewOnSale) > -1) {

                } else {
                    $(this).trigger("click");
                }


                sessionStorage.removeItem("Category");
                sessionStorage.setItem('Category', catid);
            }
            else {
                $(this).prop("checked", false);
                //$(this).trigger("click");  //MPF: removed this to prevent event from firing and redirecting
            }
        });
        
    }

    if( loc.indexOf(viewTextBook) > -1 && i == 1){
      
    }
    else if (loc.indexOf(EBooks) > -1 || loc.indexOf(FAQ) > -1 || loc.indexOf(viewprod) > -1 || loc.indexOf(viewAuthor) > -1 || loc.indexOf(viewTitle) > -1
        || loc.indexOf(viewTextBook) > -1 || loc.indexOf(bookseries) > -1 || loc.indexOf(viewOnSale) > -1 ) {

        sessionStorage.setItem('Category', catid);
        //if (i != 3 && i != 2) {
        //    window.location.href = applicationUrl;
       // }
    }
    $(".site_navigation ul li a").each(function (index) {
        // this.removeClass("current");
        $(this).removeClass("current");
    });

    if (catid == 2) {
        $(".site_navigation ul li a.newbooks").addClass("current");
    }
    else if (catid == 3) {
        $(".site_navigation ul li a.forthcoming").addClass("current");
    }
    else if (catid == 0) {
        $(".site_navigation ul li a.onsale").addClass("current");
	}

    if (loc.indexOf(viewprod) > -1) {
        window.location.href = applicationUrl + browse;
    }
}

function swap_view() {
    var series_desc = document.getElementById('info_view');
    series_desc.style.display = 'none';

    var products_view = document.getElementById('products_view');
    products_view.style.display = 'block';
}

//function bookseriesChange() {
//    var productWindow = document.getElementsByClassName("product_details");
//    if (productWindow.length > -1) {
//        document.getElementsByClassName("viewBooks")[0].style.display = "none";
//        var products_view = document.getElementById('products_view');
//        products_view.style.display = 'block';
//    }
//
//}

function showbookseries(item) {
    sessionStorage.removeItem("Format");
    sessionStorage.removeItem("Category");
    sessionStorage.removeItem("Topic");
    sessionStorage.removeItem("member");
    sessionStorage.removeItem("nonmember");

    var id = document.getElementById(item);
    
    var seriesname = id.innerHTML; 

    // MPF: have third party series bypass series pages
    if (seriesname.indexOf('General Interest') > -1 
        || seriesname.indexOf('IAS/Park City Mathematics Series/AMS') > -1 
        || seriesname.indexOf('Johns Hopkins University Press') > -1 
        || seriesname.indexOf('Gilbert Strang Books') > -1 
        || seriesname.indexOf('University of California Press') > -1) {
        sessionStorage.setItem('Format', item);


        if (window.location.href == applicationUrl + "/Home/Browse"
            || window.location.href.split('?')[0].replace(/\/$/, '') == applicationUrl) { // Home without trailing slash or query string
            selectformat(item);
            
        }
        else {
            window.location.href = applicationUrl + "/Home/Browse";
        }

    }
    else {
    	window.location.href = applicationUrl + "/Home/BookSeries/" + item;
	}
}

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function selectformat(item) {

    $('.loadMoreformat').trigger("click");
    var catid = item;

    // MPF: I removed the logic to determine what page was loaded.  The conditional ended up being superfluous 
    var loc = window.location.href;
    var viewprod = '/Product/viewproduct';
    var viewAuthor = '/Home/AuthorsEditorsIndex';
    var viewTitle = '/Home/TitleIndex';
    var viewTextBook = '/Home/TextBooks';
    var viewOnSale = '/Home/OnSale';
    var bookseries = '/Home/BookSeries';
    var FAQ = '/Home/FAQ';
    var EBooks = '/Home/Ebooks';
    var browse = '/Home/Browse';
    
    $('span.catTags a').trigger("click");


    $('.format').each(function () {
        if ($(this).attr('id') == catid){
            sessionStorage.removeItem("Format");
            sessionStorage.setItem('Format', catid);

            $(this).prop("checked", true);
            $(this).trigger("click");

            //window.location.href = applicationUrl;  //mpf: Commented out
        }

        else {
            $(this).prop("checked", false);
            // window.location.href = applicationUrl + "/Home/Browse";
        }
                
    });
}



// Mobile Filter Options
$(window).on("load",function () {
    $('#showFilter').on("click", function (e) {
        $('.left_sidebar').fadeIn('slow', function () {
            $('.left_sidebar').fadeIn('slow');
        });
    });
    $('#hideFilter').on("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");
    //    }
    //});

    var url = window.location.href;
    $(".site_navigation ul li a").each(function (index) {
        // this.removeClass("current");
        $(this).removeClass("current");
    });

    if (url.indexOf("Home/Browse") > -1) {
        $(".site_navigation ul li a.browse").addClass("current");

    }
    else if (url.indexOf("Home/FAQ") > -1) {
        $(".site_navigation ul li a.faq").addClass("current");
    }
    else if (url.indexOf("Home/Ebooks") > -1) {
        $(".site_navigation ul li a.ebooks").addClass("current");
    }

    else if (url.indexOf("Home/AuthorsEditorsIndex") > -1) {
        $(".site_navigation ul li a.authors").addClass("current");
    }
    else if (url.indexOf("Home/TextBooks") > -1) {
        $(".site_navigation ul li a.textbooks").addClass("current");
    }
    else if (url.indexOf("Home/OnSale") > -1) {
        $(".site_navigation ul li a.onsale").addClass("current");
    }

    else if (url.indexOf("Home/TitleIndex") > -1) {
        $(".site_navigation ul li a.titleIndex").addClass("current");
    }
    else if (url.indexOf("Home/BookSeries") > -1) {
        $(".site_navigation ul li a.bookSeries").addClass("current");
    }
    else
        $(".site_navigation ul li a.home").addClass("current");


    var loc = window.location.href;
    var viewprod = '/Product/viewproduct/?ProductId=';
    if (loc.indexOf(viewprod) == -1) {
        var selectedmenu = sessionStorage.getItem('Category');
        if (selectedmenu != undefined && selectedmenu > 0)
            selectcat(selectedmenu);

        var selectedsubmenu = sessionStorage.getItem('Format');
        var i = 0;
        var checkExist = setInterval(function () {
             //MPF: Prod, sometimes, takes multiple seconds to load getItems from cache!!  Allowing up to 5 secounds to load before selecting filter.
            if ( $('#Series_5').length || i > 50) { 
                //console.log('checks: ' + $('input[type="checkbox"]').length);
                clearInterval(checkExist);

                if (selectedsubmenu == null || selectedsubmenu == undefined) {

                }


                if (selectedsubmenu != undefined) {
                    selectedsubmenu = selectedsubmenu.replace(/(^,)|(,$)/g, '');
                }
                if (selectedsubmenu != undefined && selectedsubmenu.length > 0) {

                    selectformat(selectedsubmenu);
                }
            }
            else {
                i++;
                
            }
        }, 100);

    }

});

$(window).on('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 = 'email') {
        var VSubject = tittle;
        var Vbody = 'Check out this product on the SIAM Marketplace! ' + 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.7.6
 (c) 2010-2018 Google, Inc. http://angularjs.org
 License: MIT
*/
(function(n,e){'use strict';function m(d,k,l){var a=l.baseHref(),h=d[0];return function(f,b,c){var d,g;c=c||{};g=c.expires;d=e.isDefined(c.path)?c.path:a;e.isUndefined(b)&&(g="Thu, 01 Jan 1970 00:00:00 GMT",b="");e.isString(g)&&(g=new Date(g));b=encodeURIComponent(f)+"="+encodeURIComponent(b);b=b+(d?";path="+d:"")+(c.domain?";domain="+c.domain:"");b+=g?";expires="+g.toUTCString():"";b+=c.secure?";secure":"";b+=c.samesite?";samesite="+c.samesite:"";c=b.length+1;4096<c&&k.warn("Cookie '"+f+"' possibly not set or overflowed because it was too large ("+
c+" > 4096 bytes)!");h.cookie=b}}e.module("ngCookies",["ng"]).info({angularVersion:"1.7.6"}).provider("$cookies",[function(){var d=this.defaults={};this.$get=["$$cookieReader","$$cookieWriter",function(k,l){return{get:function(a){return k()[a]},getObject:function(a){return(a=this.get(a))?e.fromJson(a):a},getAll:function(){return k()},put:function(a,h,f){l(a,h,f?e.extend({},d,f):d)},putObject:function(a,d,f){this.put(a,e.toJson(d),f)},remove:function(a,h){l(a,void 0,h?e.extend({},d,h):d)}}}]}]);m.$inject=
["$document","$log","$browser"];e.module("ngCookies").provider("$$cookieWriter",function(){this.$get=m})})(window,window.angular);
//# sourceMappingURL=angular-cookies.min.js.map
;
SIAMShopping.controller('SIAMShoppingController',
    ['$scope'
        , '$filter'
        , '$http'
        , 'urlService'
        , '$timeout'
        , '$rootScope'
        , '$window'
        , 'productCart'


        , function ($scope
            , $filter
            , $http
            , urlService
            , $timeout
            , $rootScope
            , $window
            , productCart
            , $routeParam) {
            "use strict"
            //Global Variables
            $scope.thisday = new Date();
            $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;

            //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") {
                    $scope.sortType = 'MinListPrice'
                    //if ($scope.sesUserIsMember == '1')
                    //    $scope.sortType = 'MinMemberPrice' //MemberPrice
                    //else
                    //    $scope.sortType = 'MinListPrice' //Price
                    $scope.sortReverse = false;
                }
                else if ($scope.sortBy == "PriceHL") {
                    $scope.sortType = 'MinListPrice'
                    //if ($scope.sesUserIsMember == '1')
                    //    $scope.sortType = 'MinMemberPrice'
                    //else
                    //    $scope.sortType = 'MinListPrice'
                    $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);
                        })
                    }

                });
            }

            $scope.limit = 3;
            $scope.Booklimit = 3;
            $scope.BookLength = 0;

            // loadMore function
            $scope.loadMore = function ($event) {

                var type = $($event.currentTarget).attr('data-type');

                if (type == "Subject") {
                    $scope.Topics = $scope.catList.Topics;
                    $scope.limit = $scope.Topics.length;
                }
                else if (type == "Books") {
                    $scope.Formats = $scope.catList.Formats;
                    $scope.Booklimit = $scope.Formats.length;
                    $scope.BookLength = $scope.Formats.length;
                }

            }
            $scope.loadLess = function ($event) {
                var type = $($event.currentTarget).attr('data-type');
                if (type == "Subject") {
                    if ($scope.limit > 3)
                        $scope.limit = 3;
                }
                else if (type == "Books") {
                    if ($scope.Booklimit > 3)
                        $scope.Booklimit = 3;
                }

            }

            urlService.dataProvider(categoryMethod, "GET", '').then(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(',');


                    SelectCategory("TopicCode", SelectedTopics, $scope.catList.Topics);
                }

                $scope.Topics = $scope.catList.Topics;



                /*Member for block*/
                if (sessionStorage.getItem("member") != null) {
                    if (sessionStorage.getItem("member")) {
                        $(".memberproducts").prop("checked", true);
                    }
                }
                if (sessionStorage.getItem("nonmember") != null) {
                    if (sessionStorage.getItem("nonmember")) {
                        $(".nonmemberproducts").prop("checked", true);
                    }
                }
                //end

                //dropdown filling
                var categeriesDdl = [];

                var def = {};
                def["Description"] = "All";
                def["type"] = "All";
                categeriesDdl.push(def);

                $.each($scope.Formats, function (index, value) {

                    var formats = {};
                    formats["Description"] = value.Description;
                    formats["type"] = "format:" + value.FormatId;
                    categeriesDdl.push(formats);
                });

                $.each($scope.Categories, function (index, value) {

                    var categories = {};
                    categories["Description"] = value.CategoryName;
                    categories["type"] = "category:" + value.CategoryId;
                    categeriesDdl.push(categories);
                });

                $.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;
                // Patrick
                //console.log("$scope: " + Object.values( $scope) );
                //console.log("$scope.Formats: " + $scope.Formats);
                
                //end
                if (null != $scope.Formats) {
                    $scope.BookLength = $scope.Formats.length;
                  
                }
                if (null != $scope.Topics) {
                    $scope.TopLength = $scope.Topics.length;

                }
                $scope.BookLength = 16;
                $scope.TopLength = 37;
            });

            if (!String.prototype.parseNETDate) {
                String.prototype.parseNETDate = function () {
                    if (this.indexOf('-') == -1) {
                        return new Date(parseInt(this.slice(6, 19)));
                    } else {
                        return new Date(parseInt(this.slice(6, 20)));
                    }
                };
            }


            //Get sessioninfo
            $scope.sessionInfo = function () {
                urlService.dataProvider(sessionMethod, "POST", '').then(function (data) {

                    //patrick
                    if (data[0] != null) {
                        $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();
                            $scope.getCountries();
                            $scope.getStates();*/
                    }
                });
            }
            $scope.sessionInfo();



            // Products data from factory Service
            var featuredProductsBanner = [];
            var newProductBanner = [];
            var forcomingProductBanner = [];
            var conferencesForBanner = [];


            $scope.listProducts = function () {

                urlService.dataProvider(allProductsMethod, "POST", '').then(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, "PublishDate": i.PublishDate });
                            }
                            if (i.IsNew == true) {
                                ////debugger;
                                newProductBanner.push({ "ProductImage": i.ProductImage, "ProductId": i.ProductId, "ShortDescription": i.ShortDescription, "ProductName": i.ProductName, "PublishDate": i.PublishDate.parseNETDate() });
                            }
                            if (i.IsForthcoming == true) {
                                forcomingProductBanner.push({ "ProductImage": i.ProductImage, "ProductId": i.ProductId, "ShortDescription": i.ShortDescription, "ProductName": i.ProductName, "PublishDate": i.PublishDate });
                            }
                            if (i.SubSystem == 'MTG') {

                                conferencesForBanner.push({ "ProductImage": i.ProductImage, "ProductId": i.ProductId, "ShortDescription": i.ShortDescription, "ProductName": i.ProductName, "PublishDate": i.PublishDate });
                            }
                        });

                        ////console.log('featuredProductsBanner : ' + featuredProductsBanner);
                        ////console.log('newProductBanner : ' + newProductBanner);
                        ////console.log('forcomingProductBanner : ' + forcomingProductBanner);
                        //$.grep($scope.Products, function (i) {
                        //    if (i.IsNew == true) {
                        //        newProductBanner.push({ "ProductImage": i.ProductImage, "ProductId": i.ProductId, "ShortDescription": i.ShortDescription, "ProductName": i.ProductName });
                        //    }
                        //});
                        //$.grep($scope.Products, function (i) {
                        //    if (i.IsForthComing == true) {
                        //        forcomingProductBanner.push({ "ProductImage": i.ProductImage, "ProductId": i.ProductId, "ShortDescription": i.ShortDescription, "ProductName": i.ProductName });
                        //    }
                        //});
                    }

                    //get customer information
                    //$scope.sessionInfo();
                });
            };
            $scope.listProducts();


            $scope.FeatureProductImages = featuredProductsBanner;
            $scope.NewProductImages = newProductBanner;
            $scope.ForthcomingProductImages = forcomingProductBanner;
            $scope.ConferencesProductImages = conferencesForBanner;

            //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"
                }).then(function (response) {
                    $scope.Products = response.data;
                    $scope.totalProducts = $scope.Products.length;
                    hide();
                }).catch(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 = 10;
                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) {
                ////debugger;
                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") {
                            if (value == 1)
                                str += " (obj.IsTextBook=='True') ||";
                            else if (value == 2)
                                str += " (obj.IsNew==1) ||";
                            else if (value == 3)
                                str += " (obj.IsForthcoming==1) ||";
                            else if (value == 0)  // MPF: was 4
                                str += " (obj.IsOnSale==1) ||";
                            else if (value == 5)
                                str += " (obj.IsStudentPrice=='True') ||";
                        }
                        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);
                    }
                }
                if (products != null) {
                    var items = $.grep(products, function (obj) {
                        return eval(str);
                    });
                }
                else
                    return null;

                return items;

            }

            //This function for filtering products 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);
                    }
                }

                if ((typeof products === "undefined"))
                    return [];

                var items = $.grep(products, function (obj) {
                    return eval(str);
                });
                return items;

            }


            //MPF:  For a booksale, I added the items below to force product selection on page load instead of waiting for the category menu to load then fire.
            // There is an issue where the category menu sometimes takes a long time to load and then an doc.ready js, which would select the category, fails to fire.
            $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 && window.location.href.indexOf('/Home/OnSale') <= -1) {  //MPF: Added href check for onsale
                     
                    formatIds = localStorage.getItem("FormatID");
					if(formatIds !=null )
					{
						if(formatIds!="0")
						{
							
						$scope.Formats = $scope.catList.Formats;
						$scope.Booklimit = $scope.Formats.length;
						}
                    $('.format').each(function () {
                        if ($(this).attr('id') == formatIds) {
							
                            //localStorage.setItem("FormatID", catid);
                            sessionStorage.removeItem("Format");
                            sessionStorage.setItem('Format', formatIds);

                            $(this).prop("checked", true);
                            $(this).trigger("click");

                        }
                        else {
                            $(this).prop("checked", false);
                            //$(this).trigger("click");
                        }
                       
                    });
					 localStorage.setItem("FormatID", 0);
					}
                }

                if (selectedCategories.length > 0 || (formatIds!=null && formatIds!="0") || window.location.href.indexOf('/Home/OnSale') > -1 ) {  //MPF:  Added href check for onsale
						
						
                    $(".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;

                    }

                    //MPF: added this to force the sale page to load even when categorymenu loads last/long
                    if (window.location.href.indexOf('/Home/OnSale') > -1) {
                        categoryIds = categoryIds + '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).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>";
                    });

                    //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;
                        }
                    }
                    $('.slider_book').hide(); /*For new and Forthcoming book sliding*/
                    $('.slider_main').hide();
                    // $('.search_with_category').hide();

                    $('.product_data').show();
                    $('.page_title').show();
                    $('.sorting_navigation').show();

                }
                else {
                    //clearing
                    sessionStorage.removeItem("Format");
                    sessionStorage.removeItem("Category");
                    sessionStorage.removeItem("Topic");
                    sessionStorage.removeItem("member");
                    sessionStorage.removeItem("nonmember");

                    $('.search_with_category').show();
                    var loc = window.location.href;
                    if (loc.indexOf('AuthorsEditorsIndex') > -1 || loc.indexOf('TitleIndex') > -1
                        || loc.indexOf('TextBooks') > -1 || loc.indexOf('/Home/Browse') > -1 || loc.indexOf('/Home/FAQ') > -1 || loc.indexOf('/Home/Ebooks') > -1 || loc.indexOf('/Home/OnSale') > -1   ) {
                    }
                    else {
                        $('.slider_book').show(); /*For new and Forthcoming book sliding*/
                        $('.slider_main').show();
                        $('.product_data').hide();
                        $('.page_title').hide();
                        $('.sorting_navigation').hide();
                    }
                }
                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;

                    var dpc = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                    if (dpc > $scope.Products.length)
                        dpc = $scope.Products.length;
                    $scope.pageDynamicCount = dpc;
                }

                if ($scope.pageSize > $scope.totalProducts) {
                    $scope.pageDynamicCount = $scope.totalProducts;
                }

                $scope.totalProducts = $scope.Products.length;

                if ($scope.pageSize == 'all')
                    $scope.pageDynamicCount = $scope.totalProducts;

                if ($scope.pageDynamicCount == null)
                    $scope.pageDynamicCount = $scope.pageSize;

				
                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
                //
                sessionStorage.setItem("currentPage", 0);
                sessionStorage.setItem("pageDynCount", $scope.productsPerPage);

                show();
                $scope.BindProducts();
                var loc = window.location.href;

                var viewAuthor = '/Home/AuthorsEditorsIndex';
                var viewTitle = '/Home/TitleIndex';
                var viewTextBook = '/Home/TextBooks';
                var viewBrowse = '/Home/Browse';
                var bookseries = '/Home/BookSeries';
                var viewOnSale = 'Home/OnSale';
                var faq = '/Home/FAQ';
                var ebooks = '/Home/Ebooks';
                var viewprod = '/Product/viewproduct';

                if (loc.indexOf(viewOnSale) > -1 && $event.target.id == 0) {
                    return;
                }

                //MPF:  When on the Textbook page and filtering by textbook, don't redirect to browse, swap view and stay
                if ( loc.indexOf(viewTextBook) > -1  && $event.target.id == 1 ) {
                    return;
                }

                //MPF:  When on a series page and filtering by any series, don't redirect to browse
                else if ( loc.indexOf(bookseries) > -1 && $(event.target).hasClass('format')) {
                    return;
                }

                else if (loc.indexOf(viewAuthor) > -1 || loc.indexOf(viewTitle) > -1 || loc.indexOf(viewTextBook) > -1
                     || loc.indexOf(bookseries) > -1 || loc.indexOf(faq) > -1 || loc.indexOf(ebooks) > -1
                    || loc.indexOf(viewprod) > -1 || loc.indexOf(viewOnSale) > -1 ) { // || loc.indexOf(viewBrowse) > -1 

                    //debugger;
                    window.location.href = applicationUrl + '/Home/Browse';
                }
            }

            $scope.getItemBySubMenu = function (item) {
                $('.format').each(function () {
                    if ($(this).attr('id') == item) {
                        $(this).prop("checked", true);
                        $(this).trigger("click");
                    }
                    else {
                        $(this).prop("checked", false);
                        $(this).trigger("click");
                    }
                });
            }
            
            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();
                if (topSearch != undefined) {
                    topSearch = topSearch.trim();
                    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().toLowerCase();
                        var category = $("#CategorySearch").val();

                        //if "All" 
                        if (category == "All") {
                            var products = $.grep($scope.TempProducts, function (obj, index) {
                                return obj.AuthorName.toLowerCase().indexOf(searchWord) !== -1
                                    || obj.ProductName.toLowerCase().indexOf(searchWord) !== -1
                                    || obj.Topics.toLowerCase().indexOf(searchWord) !== -1
                                    || obj.ShortDescription.toLowerCase().indexOf(searchWord) !== -1
                                    || obj.ProductCode.toLowerCase().indexOf(searchWord) !== -1
                                    || obj.ISBN.indexOf(searchWord) !== -1
                                    || obj.Keywords.toLowerCase().indexOf(searchWord) !== -1
                                    || obj.MCCDescriptions.toLowerCase().indexOf(searchWord) !== -1
                            });

                            $scope.Products = unique(products);
                            console.log("Print");
                            console.log(products);
                            console.log(searchWord);

                            //Searching with Category 
                            var searchedProducts = factorialSearch(products, searchWord);

                            //Search Dropdown other than all option
                            if (!(typeof searchedProducts === "undefined")) {
                                var Names = [];
                                Names = getDataInArray(searchedProducts);
                                $("#search1").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 {
                                                if ($scope.pageSize == 'all') // Added to prevent pageDynamicCount value to became NaN
                                                    $scope.pageSize = $scope.totalProducts; //
                                                $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                                            }
                                            $scope.pageStartIndex = $scope.currentPage * $scope.productsPerPage + 1;
                                        }
                                    }
                                });
                            }

                        }//"All" End
                        else { //Other than "All" Option Start
                            var catArr = category.split(':');
                            var products = $.grep($scope.TempProducts, function (obj, index) {

                                if (catArr[0] == "Author") {

                                    return obj.AuthorName.toLowerCase().indexOf(searchWord) !== -1
                                }
                                else if (catArr[0] == "Title") {
                                    return obj.ProductName.toLowerCase().indexOf(searchWord) !== -1
                                }
                                else if (catArr[0] == "Topic") {
                                    //Add Related Property and change obj.Property in below line
                                    return obj.Topics.toLowerCase().indexOf(searchWord) !== -1 
                                        || obj.ShortDescription.toLowerCase().indexOf(searchWord) !== -1
                                        || obj.Keywords.toLowerCase().indexOf(searchWord) !== -1
                                        || obj.MCCDescriptions.toLowerCase().indexOf(searchWord) !== -1
                                }
                                else if (catArr[0] == "Keyword") {
                                    //Add Related Property and change obj.Property in below line
                                    return obj.Topics.toLowerCase().indexOf(searchWord) !== -1
                                        || obj.ShortDescription.toLowerCase().indexOf(searchWord) !== -1
                                        || obj.Keywords.toLowerCase().indexOf(searchWord) !== -1
                                        || obj.MCCDescriptions.toLowerCase().indexOf(searchWord) !== -1
                                }
                                else if (catArr[0] == "OrderCode") {
                                    //Add Related Property and change obj.Property in below line
                                    return obj.ProductCode.toLowerCase().indexOf(searchWord) !== -1
                                }

                                else 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 == catArr[1]
                                }
                            });
                            $scope.Products = unique(products);
                            console.log("Print");
                            console.log(products);
                            console.log(searchWord);

                            //Searching with Category 
                            var searchedProducts = factorialSearch(products, searchWord);

                            //Search Dropdown other than all option
                            if (!(typeof searchedProducts === "undefined")) {
                                var Names = [];
                                Names = getDataInArray(searchedProducts);
                                $("#search1").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 {
                                                if ($scope.pageSize == 'all') // Added to prevent pageDynamicCount value to became NaN
                                                    $scope.pageSize = $scope.totalProducts; //
                                                $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;
                        $scope.productsPerPage = $scope.pageSize;
                        $scope.pageStartIndex = 1;
                        $scope.currentPage = 0;
                    } 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;
            $scope.TotalMPrice = 0;
            $scope.TotalLPrice = 0;

            //Adding Product To Cart
            $scope.getCartData = function () {
                urlService.dataProvider(cartDetailsMethod, "POST", '').then(function (data) {

                    if (data == "ADDED_FAIL") {
                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalMPrice = 0;
                        $scope.TotalLPrice = 0;
                        $scope.TotalItems = 0;
                        $scope.CartDetailsLength = '';
                        jAlert('Unable to get cart details,Please try later.');
                    }
                    else if (data != "NO_DETAILS_FOUND") {

                        var totalCartPrice = 0, totalItems = 0;
                        var totalMCPrice = 0, totalLCPrice = 0;


                        $scope.CartDetails = data;
                        $scope.CartDetailsLength = data.length;
                        $scope.TotalItems = data.length;


                    } else {

                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalMPrice = 0;
                        $scope.TotalLPrice = 0;
                        $scope.CartDetailsLength = '';
                    }

                });
            };
            $scope.getCartData();
            //AddToCart
            $scope.AddToCart = function ($event, from) {
                productCart.ProductAddToCart($event.target.id, $scope, from, $event);
            };

            //Open Cart
            $scope.OpenCart = function () {
                window.location = applicationUrl + "/Login";
                ///* 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');
                    return;
                } 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).then(function (data) {

                                    $scope.getCartData();
                                    $('#popLoader').hide();
                                });
                            } else {
                                //if ($scope.product.BackorderAvailable == true) {
                                if ($scope.CartDetails[i].product.BackorderAvailable == true) {
                                    urlService.dataProvider(addToCartMethod, "POST", cartArgu).then(function (data) {

                                        $scope.getCartData();
                                        $('#popLoader').hide();
                                    });
                                } else {
                                    $('#popLoader').hide();
                                    //jAlert(' This Product Stock Availability upto ' + avlQty + '!');
                                    jAlert('There are only ' + avlQty + ' left in stock. Please lower your quantity selection.');
                                    errorFlag = true;
                                    return false;
                                }
                            }
                        } else {
                            //if ($scope.product.BackorderAvailable == true) {
                            if ($scope.CartDetails[i].product.BackorderAvailable == true) {
                                urlService.dataProvider(addToCartMethod, "POST", cartArgu).then(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).then(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).then(function (status) {

                    if (status == 3) {//Already Added
                    }

                });
            };

            //get WishList Products
            $scope.GetWishListItems = function (customerId) {
                var getWishListArgu = { CustomerID: customerId };
                urlService.dataProvider(getWishlistMethod, "POST", getWishListArgu).then(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", '').then(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 }).then(function () {
                                if (data != "fail") {
                                    //jAlert("Address Changed Successfully!");
                                    $scope.taxShippingPrice();
                                    $scope.getCartData();
                                    $('#popLoader').hide();
                                }
                                //else{
                                //    jAlert("Please try again!");
                                //}

                            }).catch(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;

                        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"
                        }).then(function (response) {
                            if (response.data != "ADDED_FAIL") {
                                $scope.getTaxData = response.data;
                                $scope.shippingHandling = response.data.TotalShipping;
                                $scope.Tax = response.data.TotalTax;
                                $scope.CouponSaving = response.data.Coupons.length == 0 ? null : response.data.Coupons[0].Amount;
                                $scope.CouponSavingDesc = response.data.Coupons.length == 0 ? null : response.data.Coupons[0].Description;
                            } else {
                                $('#popLoader').hide();
                                jAlert('Internal Technical Error. Please try again!');
                                taxErrorFlag = false;
                                return false;
                            }
                            $('#popLoader').hide();
                        }).catch(function (x) {
                            jAlert(x);
                        });
                        return taxErrorFlag;
                    }

                });
            };
            // End

            //Get Credit Card Details
            $scope.getCreditCardDetails = function () {
                urlService.dataProvider(GetCreditCardMethod, "POST", "").then(function (data) {
                    $scope.cCard = data;
                    //console.log($scope.cCard.length);

                    if ($scope.cCard.length == 0)
                        $("#useOtherVal").text("true");
                });
            };

            //End

            //Apply coupon
            $scope.ApplyCoupon = function () {
                var coupon = $("#txtCoupon").val();
                $('#popLoader').show();

                if (coupon != "") {
                    urlService.dataProvider(applyCouponforOrder, "POST", { coupon: coupon }).then(function (resultdata) {
                        if (resultdata.Success == true) {
                            $scope.CouponApplied = true;
                            $scope.shippingHandling = resultdata.Result.TotalShipping;
                            $scope.Tax = resultdata.Result.TotalTax;
                            $scope.CouponSaving = resultdata.Result.Coupons.length == 0 ? null : resultdata.Result.Coupons[0].Amount;
                            $scope.CouponSavingDesc = resultdata.Result.Coupons.length == 0 ? null : resultdata.Result.Coupons[0].Description;
                        }
                        else {
                            $scope.CouponApplied = false;
                        }
                        $('#popLoader').hide();
                    }).catch(function (ex) {
                        $('#popLoader').hide();
                    });
                }
                else {
                    $('#popLoader').hide();
                    jAlert('Please enter coupon to apply!');
                }
            };

            //Create Order
            $scope.placeOrder = function () {
                $('#popLoader').show();
                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 {
                        $('#popLoader').hide();
                    }
                } 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).then(function (data) {
                        if (data.Success != true) {
                            jAlert(data.ErrorMessage);
                            //if (data != true) {
                            //jAlert('Please enter valid details!');
                            $('#popLoader').hide();
                            clearCC();
                            //}
                        }
                        else {
                            createOrderItem();
                        }
                    }).catch(function (errorx) {
                        clearCC();
                        $('#popLoader').hide();
                        jAlert(errorx);
                    });
                }

                function createOrderItem() {
                    $('#popLoader').show();
                    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).then(function (d) {
                        //if (d != "ADDED_FAIL") {
                        if (d.Success == true) {
                            $scope.finalOrderNumber = d.OrderNumber;
                            sessionStorage.setItem('orderNumber', $scope.finalOrderNumber);
                            $('.cart-popup').removeClass('is-visible');
                            window.location = applicationUrl + '/Product/orderConfirmation';
                            clearCC();
                            $('#popLoader').hide();
                        } else {
                            $('#popLoader').hide();
                            hide();
                            //clearCC();
                            //jAlert('Unable to place order Please try again!');
                            jAlert(d.ErrorMessage);

                            //$('.cart-popup').trigger('click');
                        }
                    }).catch(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 () {
                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!');
                } 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;
            };

            //function clearCC() {
            //    $("#CCName").val('');
            //    $("#CCNumber").val('');
            //    $("#CCcvv").val('');
            //    $("#months").val("string:Month");
            //    $("#years").val('string:Year');
            //};


            //End

            //Getting Countries
            $scope.getCountries = function () {
                urlService.dataProvider(getCountryMethod, 'POST', '').then(function (data) {
                    var CountryList = $.grep(data, function (i) {
                        return i.CountryCode != "[ALL]";
                    });
                    $scope.CountryList = CountryList.sort()
                    //$scope.Countrys = "All Countries";

                });
            };

            //Getting States
            $scope.getStates = function () {
                urlService.dataProvider(getStateMethod, 'POST', '').then(function (data) {
                    if (data != 'ADDED_FAIL') {
                        $scope.StateList = data;
                        $scope.TmpStateList = data;
                        //$scope.States = $scope.StateList[0];
                    }
                    else {
                        //if states not available
                        //$scope.StateList = [{ StateDescription: 'No States Available' }];
                        $scope.inputEnbl = true;
                        $("input#States").val('');
                    }
                });
            };

            $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;
                var AllCountry = $('#Countrys').val();
                if (AllCountry != "") {
                    urlService.dataProvider(getStateMethod, 'POST', { countrycode: a.CountryCode }).then(function (data) {
                        if (data != 'ADDED_FAIL') {
                            $scope.StateList = data;
                            $scope.States = $scope.StateList;

                            var result = $.grep($scope.StateList, function (e) { return e.CountryCodeString == a.CountryCode });
                            if (result.length != 0) {
                                $scope.StateList = result;
                                $scope.States = $scope.StateList;
                            } else {
                                //if states not available
                                //$scope.StateList = [{ StateDescription: 'No States Available' }];
                                $scope.inputEnbl = true;
                                $("input#States").val('');
                            }
                        } else {
                            //if states not available
                            //$scope.StateList = [{ StateDescription: 'No States Available' }];
                            $scope.inputEnbl = true;
                            $("input#States").val('');
                        }
                    });
                    return
                }
                else {
                    $scope.inputEnbl = true;
                    $("input#States").val('');
                }
                //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;
                //} else {
                //    //if states not available
                //    //$scope.StateList = [{ StateDescription: 'No States Available' }];
                //    $scope.inputEnbl = true;
                //    $("input#States").val('');
                //}

            };
            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!');
                } else {
                    $('#States').next().empty();
                }
                if ($('#States').val() == "undefined") {
                    stateCode = '';
                } 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).then(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", '').then(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');
                        }
                    }).catch(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();
                    if ($scope.pageSize == 'all') // Added to prevent pageDynamicCount value to became NaN
                    {
                        $scope.pageSize = $scope.totalProducts; //
                        $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                        $scope.pageSize = 'all'
                    }
                    else {
                        $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                    }
                }
            });
            show();
            //delay in function, to get the DOM elements

            if (window.location.search != '') {

                sessionStorage.removeItem("Format");
                sessionStorage.removeItem("Category");
                sessionStorage.removeItem("Topic");
                sessionStorage.removeItem("member");
                sessionStorage.removeItem("nonmember");

                $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]).prop("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).prop("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).prop("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).prop("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().toString() == "memberproducts" || decodeURIComponent(item).toLowerCase().toString() == "member products")
                                            $('input[id="memberUser"]').prop("checked", true);
                                        else
                                            $('input[id="nonMemberUser"]').prop("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', '').then(function (data) {
                    $scope.shipViaCode = data;
                    $scope.shipViaCodeDD = $scope.shipViaCode[0];
                }).catch(function (x) {
                });
            };

            //get Favourites Products
            $scope.GetFavouriteItems = function (Masterid) {
                var getFavouritesArgu = { masterid: Masterid };
                urlService.dataProvider(getFavouriteItems, "POST", getFavouritesArgu).then(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 () {
                var currentUrl = window.location + ''
                window.location.href = "/Login/?returnURL=" + currentUrl + "/&SSOL=Y" ;
            }

            $scope.Login = function () {
                $scope.UserId = '';
                var username = $scope.UserName;
                if (isNumeric(username) == 1) {
                    $scope.UserId = lpad(username, 8);
                }
                else {
                    $scope.UserId = username;
                }

                function isNumeric(input) {
                    return (input - 0) == input && (input + '').replace(/^\s+|\s+$/g, "").length > 0;
                }

                function lpad(value, padding) {
                    var zeroes = "0";
                    for (var i = 0; i < padding; i++) { zeroes += "0"; }
                    return (zeroes + value).slice(padding * -1);
                }


                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.UserId, Password: $scope.Password, CurrentUrl: currentUrl, RememberMe: ChkRememberMe };
                    urlService.dataProvider(LoginInfo, "POST", commeArgu).then(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;
                        }

                    });

                }
                 
            };

            //get Favourites Products
            $scope.GetBookSeriesItems = function (Masterid) {
                var getFavouritesArgu = { masterid: Masterid };
                urlService.dataProvider(getBookSeriesMethod, "POST", '').then(function (data) {
                    $scope.BookSeriesItems = data;
                });//for
            };
            $scope.GetBookSeriesItems();
        }]);;
SIAMShopping.controller('viewProductController',
    ['$http'
        , '$scope'
        , 'urlService'
        , 'productCart'
        , '$cookies'
        
        , '$rootScope'
        , '$window'
        , function ($http
            , $scope
            , urlService
            , productCart
            , $location
            , $cookies
            
            , $rootScope
            , $window) {

            "user strict";
            // , '$cookieStore'
            // , $cookieStore
            //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.currentPage = 0;
            $scope.ordersPerPage = 2;
            $scope.Orders = '';
            $scope.pageSize = "2";
            $scope.pageStartIndex = '';
            $scope.pageDynamicCount = $scope.ordersPerPage;
            $scope.totalOrders = '';
            $scope.currentdate = new Date();
            $scope.IsOrderHistoryByDates = false;
            $scope.IsSearchOrderHistory = false;

            var noimgurl = applicationUrl + '/Images/Image-not-available.png';
            var wL = window.location + '';
            var wLArray = wL.split('/');

            //getCategories
            urlService.dataProvider(categoryMethod, "GET", '').then(function (data) {
                $scope.catList = data;
            });

            //Cart Implementation
            var lSRcentItem = [];
            $scope.listProducts = function () {
                urlService.dataProvider(allProductsMethod, "POST", '').then(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();
                });
            };
            if (window.location.href.indexOf("OrderHistory") == -1)
                $scope.listProducts();

            //Get sessioninfo
            $scope.sessionDetails = function () {
                urlService.dataProvider(sessionMethod, "POST", '').then(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;

                    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];
                            var isprodmemonly = window.location.search.split("=")[2];
                        }
                        else {
                            var cprt = sessionStorage.getItem("UMBID");
                            var isprodmemonly = sessionStorage.getItem("UMBID_IsMem") == "true" ? true : false;

                        }
                        show();
                        if ($scope.sesUserIsMember != "1" && isprodmemonly) {
                            jAlert('This Product is only for members.');
                            sessionStorage.removeItem("CustomPro");
                            return false
                        } else {
                            $scope.ProductCompose(cprt, '', cprt, isprodmemonly);
                        }
                    }
                });

            }
            $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").replace("/", "");

            //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"
                    }).then(function (response) {

                        if (response.data != "ERROR_FAIL") {
                            $scope.viewProduct = response.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"
                                }).then(function (response) {
                                    $scope.viewUmbrellProducts = response.data;
                                }).catch(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.');
                        }
                    }).catch(function (x) {
                    });
                })();
            };

            $scope.IsUmbrellaProductTrue = true;
            $scope.IsUmbrellaProductElements = false;
            $scope.IsUmbrellaProductAddToCart = false;

            $scope.onProductChange = function ($event) {
                $(".preImageLoader").show();
                /* To Open Popup after login */
                setTimeout(function () {
                    if ($scope.sesCustomerId == '') {
                        sessionStorage.setItem("UMBID", $(".ProductCompose").attr("data-prdId"));
                        sessionStorage.setItem("UMBID_IsMem", $(".ProductCompose").attr("data-ismem"));
                    }
                }, 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 {
                    $('#viewUmbrellProductDD').removeAttr('style');
                }
                //This will define the Zoom Image change state
                //child = 1;
                //zoomImage("On Change");
                function isUmbrellaProdTrue() {
                    if ($("#viewUmbrellProductDD").val() == "" && $("#viewUmbrellProductDD").is(":visible") == true) {
                        //jAlert("Please select Post Card Message!");
                        $scope.IsUmbrellaProductTrue = true;
                        $scope.IsUmbrellaProductElements = false;
                        $scope.IsUmbrellaProductAddToCart = false;
                        $scope.viewUmbrellSelectProduct = $scope.viewUmbrellProducts;
                        //This will define the Zoom Image change state
                        //child = 0;
                        //zoomImage("viewUmbrellProductDD index 0");
                        updateRatings($scope.viewProduct.Rating);
                        $scope.productRatingCount = $scope.viewProduct.RatingCount;
                        $scope.loadReviews($scope.id, 9);

                    }
                    if ($("#prdQuantity").val() == "") {
                        //jAlert("Please select Quantity!");
                        $scope.IsUmbrellaProductTrue = true;
                        $scope.IsUmbrellaProductElements = false;
                        $scope.IsUmbrellaProductAddToCart = false;
                        $scope.viewUmbrellSelectProduct = $scope.viewUmbrellProducts;
                        //This will define the Zoom Image change state
                        //child = 0;
                        //zoomImage("prdQuantity index 0");
                        $(".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='" + noimgurl + "' 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
                        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='" + noimgurl + "' 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='" + noimgurl + "' 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() != "") {

                        $.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);
                            }
                        });

                        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='" + noimgurl + "' 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='" + noimgurl + "' alt='' />");
                                }
                                $(".preImageLoader").hide();
                            }, 2000);
                            $(".preImageLoader").hide();
                        }

                        //Enable data divs for umbrella products
                        $scope.IsUmbrellaProductTrue = false;
                        $scope.IsUmbrellaProductElements = true;
                        $scope.IsUmbrellaProductAddToCart = true;

                    } else {
                        isUmbrellaProdTrue();
                        $(".preImageLoader").hide();
                    }
                }

            };

            //viewUmbrellProductsShortDescription
            urlService.dataProvider(cartDetailsMethod, "POST", '').then(function (data) {
                $scope.viewCartData = data;
            });

            //Getting Cart details  
            $scope.TotalPrice = 0;
            $scope.TotalMPrice = 0;
            $scope.TotalLPrice = 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"
                }).then(function (response) {

                    if (response.data == "ADDED_FAIL") {
                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalMPrice = 0;
                        $scope.TotalLPrice = 0;

                        $scope.TotalItems = 0;
                        $scope.CartDetailsLength = '';
                        jAlert('Unable to get cart details,Please try later.');
                    }
                    else if (response.data != "NO_DETAILS_FOUND") {

                        if (from == "delete" || from == "update") {
                            $scope.viewCartData = response.data;
                        }
                        $scope.CartDetails = response.data;
                        $scope.CartDetailsLength = response.data.length;
                        $scope.TotalItems = response.data.length;

                    }
                    else {

                        $scope.CartDetails = [];
                        $scope.TotalPrice = 0;
                        $scope.TotalMPrice = 0;
                        $scope.TotalLPrice = 0;
                        $scope.TotalItems = 0;
                        $scope.CartDetailsLength = '';

                    }

                }).catch(function (x) {
                });
            }
            $scope.GetCartProducts();
            $scope.cartSuccess = '';



            //Adding Product To Cart
            $scope.AddToCart = function (productid, $event, from) {

                // public JsonResult Validatecart(string ProductId) {
                $http({
                    method: "GET",
                    url: applicationUrl + '/Product/Validatecart',
                    params: { ProductId: productid },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                }).then(function (response) {
                    if (response.data != null && response.data.Success == true) {
                        if (response.data.AllowtoCart == false)
                            alert("Please complete purchase of existing items from the cart or remove them from cart before buying a book");
                        else
                            productCart.ProductAddToCart(productid, $scope, from, $event);

                    } else {
                      
                    }
                    }).catch(function (x) {
                      //  console.log("/Product/Validatecart : Last Error"); //ends up catch 
                });
                
            };

            //Patrick validate the add to cart button 
            $scope.AddToCartValid = function (viewProduct) {

                var today = new Date();
                today = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(),
                    today.getUTCHours(), today.getUTCMinutes(), today.getUTCSeconds());

                var PreorderdotNetDate = viewProduct.PreorderAvailableDateCustom;
                var PreorderAvailableDatejavaScript;

                if (PreorderdotNetDate != null) {
                    PreorderAvailableDatejavaScript = new Date(parseInt(PreorderdotNetDate.substr(6)));
                    PreorderAvailableDatejavaScript = Date.UTC(PreorderAvailableDatejavaScript.getUTCFullYear(), PreorderAvailableDatejavaScript.getUTCMonth(), PreorderAvailableDatejavaScript.getUTCDate(),
                        PreorderAvailableDatejavaScript.getUTCHours(), PreorderAvailableDatejavaScript.getUTCMinutes(), PreorderAvailableDatejavaScript.getUTCSeconds());
                }

                var PublishdotNetDate = viewProduct.PublishDateCustom;
                var PublishDatejavaScript;

                if (PublishdotNetDate != null) {
                    PublishDatejavaScript = new Date(parseInt(PublishdotNetDate.substr(6)));
                    PublishDatejavaScript = Date.UTC(PublishDatejavaScript.getUTCFullYear(), PublishDatejavaScript.getUTCMonth(), PublishDatejavaScript.getUTCDate(),
                        PublishDatejavaScript.getUTCHours(), PublishDatejavaScript.getUTCMinutes(), PublishDatejavaScript.getUTCSeconds());
                }

                if (viewProduct.ProductCode == 'SE0028') {
                    return "ebook";
                }

                if (today < PublishDatejavaScript || viewProduct.ADD_TO_CART_FLAG == 'N' || (viewProduct.StockAvailable < 1 && viewProduct.BackorderAvailable == 0 )) {
                    return "unavailable";
                }

                if ((PublishDatejavaScript < today && today < PreorderAvailableDatejavaScript && PreorderAvailableDatejavaScript != null && viewProduct.BackorderAvailable == 1 && viewProduct.ADD_TO_CART_FLAG == 'Y')) {
                    return "preorder";
                }

                if (today > PreorderAvailableDatejavaScript || (PreorderAvailableDatejavaScript == null && today > PublishDatejavaScript)) {

                    if (viewProduct.StockAvailable > 10) {
                        return "available";
                    }

                    if (viewProduct.StockAvailable < 1 && viewProduct.BackorderAvailable == 1) {
                        return "backorder";
                    }

                    if (viewProduct.StockAvailable <= 10) {
                        return "lessthanx";
                    }
                }

                if (viewProduct.StockAvailable == null && viewProduct.BackorderAvailable == null && PublishDatejavaScript == null && PreorderAvailableDatejavaScript == null && viewProduct.ProductCode == null) {
                    return "loading";
                }

                return "error007"; // Book Set Up Error: 007 Please contact customer service. 

            };

            //Open Cart
            $scope.OpenCart = function () {
                window.location = applicationUrl + "/Login";
            }

            //Update Cart
            $scope.UpdateToCart = function (from) {
                if ($('#shipViaCodeDD').val() == "") {
                    $('#shipViaCodeDD').css('box-shadow', '0px 0px 2px #FF0000');
                    return;
                } 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).then(function (data) {

                                    if (viewcartflag) {
                                        from = "viewcart";
                                    }

                                    $scope.GetCartProducts(from);
                                    $('#popLoader').hide();
                                });

                            } else {
                                if (bo == "true") {
                                    urlService.dataProvider(addToCartMethod, "POST", cartArgu).then(function (data) {

                                        if (viewcartflag) {
                                            from = "viewcart";
                                        }

                                        $scope.GetCartProducts(from);
                                        $('#popLoader').hide();
                                    });
                                } else {
                                    $('#popLoader').hide();
                                    //jAlert(' This Product Stock Availability upto ' + avlQty + '!');
                                    jAlert('There are only ' + avlQty + ' left in stock. Please lower your quantity selection.');
                                    errorFlag = true;
                                    return false;
                                }
                            }
                        } else {
                            if (bo == "true") {
                                urlService.dataProvider(addToCartMethod, "POST", cartArgu).then(function (data) {

                                    if (viewcartflag) {
                                        from = "viewcart";
                                    }

                                    $scope.GetCartProducts(from);
                                    $('#popLoader').hide();
                                });
                            } else {
                                $('#popLoader').hide();
                                jAlert(' Product Available in minimum quantities of 1 !');
                                errorFlag = true;
                                return false;
                            }
                        }
                    } else {
                        urlService.dataProvider(addToCartMethod, "POST", cartArgu).then(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", "").then(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;
            };

            //Add WishList Products
            $scope.AddToWishList = function (wId, CustomerID, x, from) {
                var tempWishListArry = '';
                var wishlistId = '';
                if (from == "recent") {
                    tempWishListArry = $scope.recentView;
                    //select & unselect wishlist icon
                    $.grep($scope.recentView, function (i) {
                        if (i.ProductId == wId) {
                            if (i.IsInWishList != true) {
                                i.IsInWishList = true;
                            }
                            else {
                                i.IsInWishList = false;
                            }
                        }
                    });
                }
                else if (from == "related") {
                    //select & unselect wishlist icon
                    $.grep($scope.relatedView, function (i) {
                        if (i.ProductId == wId) {
                            if (i.IsInWishList != true) {
                                i.IsInWishList = true;
                            }
                            else {
                                i.IsInWishList = false;
                            }
                        }
                    });
                };

                // '1' for add, '2' for remove
                var addWishArgu = { ProductId: wId, CustomerID: CustomerID, From: 2 };
                urlService.dataProvider(saveWishlistMethod, "POST", addWishArgu).then(function (status) {

                    //if (status == 2) {
                    //    jAlert('removed successfully');
                    //}

                    //Scope Refreshed
                    //$scope.listProducts();

                    //for Adding to Wish List
                    $scope.GetWishListItems(CustomerID);
                });
            };
            $scope.GetWishListItems = function (customerId) {
                var getWishListArgu = { CustomerID: customerId };
                urlService.dataProvider(getWishlistMethod, "POST", getWishListArgu).then(function (data) {
                    if (data.length == 0) {
                        sessionStorage.removeItem("wData");
                    }
                    $scope.WishListItems = unique(data);
                });
            };
            //Only at WishList Page checking by Url
            var indexWishUrl = wLArray.indexOf("WishList");
            if (wLArray[indexWishUrl] == "WishList") {
                $scope.GetWishListItems($scope.sesCustomerId);
            };


            var shipCustId = '';
            //Get Shipping & Billing Address
            urlService.dataProvider(GetAddressesMethod, "POST", '').then(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 }).then(function () {
                        if (data != "fail") {
                            $scope.taxShippingPrice();
                            //$scope.getCartData();
                            $scope.GetCartProducts();
                            $('#popLoader').hide();
                        }
                    }).catch(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"
                    }).then(function (response) {
                        if (response.data != "ADDED_FAIL") {
                            $scope.getTaxData = response.data;
                            $scope.shippingHandling = response.data.TotalShipping;
                            $scope.Tax = response.data.TotalTax;
                            $scope.CouponSaving = response.data.Coupons.length == 0 ? null : response.data.Coupons[0].Amount;
                        } else {
                            jAlert('Internal Technical Error. Please try again!');
                            taxErrorFlag = false
                            return false;
                        }
                        $('#popLoader').hide();
                    }).catch(function (x) {
                        jAlert(x);
                    });
                    return taxErrorFlag;
                }

            });

            //Apply coupon
            $scope.ApplyCoupon = function () {
                var coupon = $("#txtCoupon").val();
                $('#popLoader').show();

                if (coupon != "") {
                    urlService.dataProvider(applyCouponforOrder, "POST", { coupon: coupon }).then(function (resultdata) {
                        if (resultdata.Success == true) {

                            $scope.CouponApplied = true;
                            $scope.shippingHandling = resultdata.Result.TotalShipping;
                            $scope.Tax = resultdata.Result.TotalTax;
                            $scope.CouponSaving = resultdata.Result.Coupons.length == 0 ? null : resultdata.Result.Coupons[0].Amount;
                            $scope.CouponSavingDesc = resultdata.Result.Coupons.length == 0 ? null : resultdata.Result.Coupons[0].Description;
                        }
                        else {
                            $scope.CouponApplied = false;
                        }
                        $('#popLoader').hide();
                    }).catch(function (ex) {
                        $('#popLoader').hide();
                    });
                }
                else {
                    $('#popLoader').hide();
                    jAlert('Please enter coupon to apply!');
                }
            };

            //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 {
                        $('#popLoader').hide();
                    }
                } 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).then(function (data) {
                        if (data.Success != true) {
                            jAlert(data.ErrorMessage);
                            //if (data != true) {
                            //jAlert('Please enter valid details!');
                            $('#popLoader').hide();
                            clearCC();
                            //}
                        }
                        else {
                            createOrderItem();
                        }
                    }).catch(function (errorx) {
                        clearCC();
                        $('#popLoader').hide();
                        jAlert(errorx);
                    });
                }

                function createOrderItem() {
                    $('#popLoader').show();
                    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).then(function (d) {
                        if (d.Success == true) {
                            //if (d != "ADDED_FAIL") {
                            $scope.finalOrderNumber = d.OrderNumber;
                            sessionStorage.setItem('orderNumber', $scope.finalOrderNumber);
                            $('.cart-popup').removeClass('is-visible');
                            window.location = applicationUrl + '/Product/orderConfirmation';
                            clearCC();
                            $('#popLoader').hide();
                        } else {
                            hide();
                            $('#popLoader').hide();
                            //clearCC();
                            //jAlert('Unable to place order Please try again!');
                            jAlert(d.ErrorMessage);

                            //$('.cart-popup').trigger('click');
                        }
                    }).catch(function (x) {
                        hide();
                        $('#popLoader').hide();
                        clearCC();
                        jAlert(x.ErrorMessage);
                    });
                }
            };

            $scope.orderResponse = function () {

                urlService.dataProvider(getOrderdeatilsMethod, "POST", "").then(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) {
                //debugger;
                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();
                    if (searchWord != undefined && searchWord.length > 0)
                        searchWord = searchWord.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 != undefined && category.length > 0) ? 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;
                }
            }

            $scope.digitalDownloads = function () {
                show();
                urlService.dataProvider(GetDigitalDownloads, "POST", "").then(function (data) {
                    $('#popLoader').hide();
                    if (data.length > 0) {
                        $('#divDigitalDownloads').show();
                        $('#ShowDDtitle').show();
                        $('#ShowNoDDtitle').hide();
                        $scope.repDigitalDownloads = data;
                        //console.log(data); 
                    }
                    else {
                        $('#divDigitalDownloads').hide();
                        $('#ShowDDtitle').hide();
                        $('#ShowNoDDtitle').show();
                        //jAlert('No Digital Downloads Found!');
                        //window.location.href = applicationUrl;
                    }
                    hide();
                }).catch(function (ex) {
                    hide();
                });
            }

            $scope.orderHistory = function (pageno, pagesize) {
                if (pagesize != undefined)
                    $scope.ordersPerPage = pagesize;
                if (pageno != undefined)
                    $scope.currentPage = pageno;

                show();

                urlService.dataProvider(GetOrderHistory, "POST", { pageno: $scope.currentPage, pagesize: $scope.ordersPerPage }).then(function (odata) {
                    //console.log(odata);
                    if (odata.length > 0) {
                        $('#ShowOHtitle').show();
                        $('#ShowNoOHtitle').hide();
                        $('#divOrderHistory').show();

                        $scope.repOrderHistory = odata;
                        $scope.Orders = odata;
                        $scope.totalOrders = $scope.Orders.length;
                        $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                        if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                            $scope.pageDynamicCount = $scope.totalOrders;
                        } else {
                            $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                        }

                        if (odata.Coupons != null && odata.Coupons != undefined) {
                            $scope.repCpSaving = odata.Coupons.length == 0 ? null : odata.Coupons[0].Amount;
                            $scope.repCpSavingDesc = odata.Coupons.length == 0 ? null : odata.Coupons[0].Description;
                        }
                        //console.log(odata);

                        for (j = 0; j < odata.length; j++) {
                            if (odata[j].Products != null && odata[j].Products != undefined) {
                                if (odata[j].Products.length > 0) {
                                    for (i = 0; i < odata[j].Products.length; i++) {
                                        //
                                        if (odata[j].Products[i].TrackingNo != null && odata[j].Products[i].TrackingNo.length > 0) {
                                            var re = /TRACK_NO/gi;
                                            str = str.replace("&amp;", "&");
                                            var newstr = encodeURI(str.replace(re, odata[j].Products[i].TrackingNo));
                                            odata[j].Products[i].TrackURL = newstr;
                                        }
                                        else {
                                            odata[j].Products[i].TrackURL = "";
                                        }
                                    }
                                }
                            }
                        }
                        //console.log(odata);
                    }
                    else {
                        $('#ShowOHtitle').hide();
                        $('#ShowNoOHtitle').show();
                        $('#divOrderHistory').hide();
                        //jAlert('No Order History Found!');
                        //window.location.href = applicationUrl;
                    }
                    hide();
                }).catch(function (ex) {
                    hide();
                });
            }

            // Order History Search Based on Category
            $scope.SearchOrderHistory = function (pageno, pagesize) {
                if (pagesize != undefined)
                    $scope.ordersPerPage = pagesize;
                if (pageno != undefined)
                    $scope.currentPage = pageno;

                var sWord = $("#SearchOrderHistory").val().trim();
                var sType = $("#SearchType").val();

                $("#SearchStartDate").val("");
                $("#SearchEndDate").val("");

                show();

                if (sWord != "") {
                    urlService.dataProvider(GetSearchedOrderHistoryDetails, "POST", { searchWord: sWord, searchType: sType, pageno: $scope.currentPage, pagesize: $scope.ordersPerPage })
                        .then(function (searchedResults) {
                            if (searchedResults.length > 0) {
                                $('#ShowOHtitle').show();
                                $('#ShowNoOHtitle').hide();
                                $('#divOrderHistory').show();
                                $scope.IsSearchOrderHistory = true;

                                $scope.repOrderHistory = searchedResults;
                                $scope.Orders = searchedResults;
                                $scope.totalOrders = $scope.Orders.length;
                                $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                                if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                                    $scope.pageDynamicCount = $scope.totalOrders;
                                } else {
                                    $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                                }

                                if (searchedResults.Coupons != null && searchedResults.Coupons != undefined) {
                                    $scope.repCpSaving = searchedResults.Coupons.length == 0 ? null : searchedResults.Coupons[0].Amount;
                                    $scope.repCpSavingDesc = searchedResults.Coupons.length == 0 ? null : searchedResults.Coupons[0].Description;
                                }

                                for (j = 0; j < searchedResults.length; j++) {
                                    if (searchedResults[j].Products != null && searchedResults[j].Products != undefined) {
                                        if (searchedResults[j].Products.length > 0) {
                                            for (i = 0; i < searchedResults[j].Products.length; i++) {

                                                if (searchedResults[j].Products[i].TrackingNo != null && searchedResults[j].Products[i].TrackingNo.length > 0) {
                                                    var re = /TRACK_NO/gi; str = str.replace("&amp;", "&"); var newstr = str.replace(re, searchedResults[j].Products[i].TrackingNo);
                                                    searchedResults[j].Products[i].TrackURL = newstr;
                                                }
                                                else {
                                                    searchedResults[j].Products[i].TrackURL = "";
                                                }
                                            }
                                        }
                                    }
                                }
                                //console.log(searchedResults);
                            }
                            else {
                                $('#ShowOHtitle').hide();
                                $('#ShowNoOHtitle').show();
                                $('#divOrderHistory').hide();
                                //jAlert('No Order History Found!');
                            }
                            hide();
                        }).catch(function (ex) {
                            hide();
                        });
                }
                else {
                    hide();
                    jAlert('Please enter data for search!');
                }
            }

            // Order History Full Details
            $scope.orderFullDetails = function (orNo, pageno, pagesize) {
                if (pagesize != undefined)
                    $scope.ordersPerPage = pagesize;
                if (pageno != undefined)
                    $scope.currentPage = pageno;

                var sWord = orNo;
                var sType = "OrderNo";

                $("#SearchStartDate").val("");
                $("#SearchEndDate").val("");

                show();

                if (sWord != "") {
                    urlService.dataProvider(GetSearchedOrderHistoryDetails, "POST", { searchWord: sWord, searchType: sType, pageno: $scope.currentPage, pagesize: $scope.ordersPerPage })
                        .then(function (searchedRs) {
                            if (searchedRs.length > 0) {
                                $('#ShowOHtitle').show();
                                $('#ShowNoOHtitle').hide();
                                $('#divOrderHistory').show();
                                $scope.IsSearchOrderHistory = true;

                                $scope.repOrderHistory = searchedRs;
                                $scope.Orders = searchedRs;
                                $scope.totalOrders = $scope.Orders.length;
                                $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                                if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                                    $scope.pageDynamicCount = $scope.totalOrders;
                                } else {
                                    $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                                }

                                if (searchedRs.Coupons != null && searchedRs.Coupons != undefined) {
                                    $scope.repCpSaving = searchedRs.Coupons.length == 0 ? null : searchedRs.Coupons[0].Amount;
                                    $scope.repCpSavingDesc = searchedRs.Coupons.length == 0 ? null : searchedRs.Coupons[0].Description;
                                }

                                for (j = 0; j < searchedRs.length; j++) {
                                    if (searchedRs[j].Products != null && searchedRs[j].Products != undefined) {
                                        if (searchedRs[j].Products.length > 0) {
                                            for (i = 0; i < searchedRs[j].Products.length; i++) {

                                                if (searchedRs[j].Products[i].TrackingNo != null && searchedRs[j].Products[i].TrackingNo.length > 0) {
                                                    var re = /TRACK_NO/gi; str = str.replace("&amp;", "&"); var newstr = str.replace(re, searchedRs[j].Products[i].TrackingNo);
                                                    searchedRs[j].Products[i].TrackURL = newstr;
                                                }
                                                else {
                                                    searchedRs[j].Products[i].TrackURL = "";
                                                }
                                            }
                                        }
                                    }
                                }
                                //console.log(searchedRs);
                            }
                            else {
                                $('#ShowOHtitle').hide();
                                $('#ShowNoOHtitle').show();
                                $('#divOrderHistory').hide();
                                //jAlert('No Order History Found!');
                            }
                            hide();
                        }).catch(function (ex) {
                            hide();
                        });
                }
                else {
                    hide();
                    jAlert('Please enter data for search!');
                }
            }

            // Order History Search Based on Dates
            $scope.SearchOrderHistoryByDates = function (pageno, pagesize) {
                if (pagesize != undefined)
                    $scope.ordersPerPage = pagesize;
                if (pageno != undefined)
                    $scope.currentPage = pageno;

                var sDate = $("#SearchStartDate").val();
                var eDate = $("#SearchEndDate").val();

                $("#SearchOrderHistory").val("");
                $("#SearchType").val("OrderNo");

                var datefrom = new Date(Date.parse(sDate));
                var dateto = new Date(Date.parse(eDate));

                show();

                if (sDate != "") {
                    if (eDate != "") {
                        if (sDate != "" & eDate != "") {
                            if (datefrom > dateto) {
                                hide();
                                jAlert('Start Date Should be less than or equal to End Date');
                            }
                            else {
                                urlService.dataProvider(GetSearchedOrderHistoryDetailsByDates, "POST", { startDate: sDate, endDate: eDate, pageno: $scope.currentPage, pagesize: $scope.ordersPerPage })
                                    .then(function (searchedDetails) {
                                        if (searchedDetails.length > 0) {
                                            $('#ShowOHtitle').show();
                                            $('#ShowNoOHtitle').hide();
                                            $('#divOrderHistory').show();
                                            $scope.IsOrderHistoryByDates = true;

                                            $scope.repOrderHistory = searchedDetails;
                                            $scope.Orders = searchedDetails;
                                            $scope.totalOrders = $scope.Orders.length;
                                            $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                                            if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                                                $scope.pageDynamicCount = $scope.totalOrders;
                                            } else {
                                                $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                                            }

                                            if (searchedDetails.Coupons != null && searchedDetails.Coupons != undefined) {
                                                $scope.repCpSaving = searchedDetails.Coupons.length == 0 ? null : searchedDetails.Coupons[0].Amount;
                                                $scope.repCpSavingDesc = searchedDetails.Coupons.length == 0 ? null : searchedDetails.Coupons[0].Description;
                                            }

                                            for (j = 0; j < searchedDetails.length; j++) {
                                                if (searchedDetails[j].Products != null && searchedDetails[j].Products != undefined) {
                                                    if (searchedDetails[j].Products.length > 0) {
                                                        for (i = 0; i < searchedDetails[j].Products.length; i++) {

                                                            if (searchedDetails[j].Products[i].TrackingNo != null && searchedDetails[j].Products[i].TrackingNo.length > 0) {
                                                                var re = /TRACK_NO/gi; str = str.replace("&amp;", "&"); var newstr = str.replace(re, searchedDetails[j].Products[i].TrackingNo);
                                                                searchedDetails[j].Products[i].TrackURL = newstr;
                                                            }
                                                            else {
                                                                searchedDetails[j].Products[i].TrackURL = "";
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            //console.log(searchedDetails);
                                        }
                                        else {
                                            $('#ShowOHtitle').hide();
                                            $('#ShowNoOHtitle').show();
                                            $('#divOrderHistory').hide();
                                            //jAlert('No Order History Found!');
                                        }
                                        hide();
                                    }).catch(function (ex) {
                                        hide();
                                    });
                            }
                        }
                        else {
                            hide();
                            jAlert('Please select both dates to search!');
                        }
                    }
                    else {
                        hide();
                        jAlert('Please select both dates to search!');
                    }
                }
                else {
                    hide();
                    jAlert('Please select dates to search!');
                }
            }

            // Order History Reset
            $scope.SearchReset = function (pageno, pagesize) {
                if (pagesize != undefined)
                    $scope.ordersPerPage = pagesize;
                if (pageno != undefined)
                    $scope.currentPage = pageno;

                var sWord = "";
                var sType = "";

                $("#SearchOrderHistory").val("");
                $("#SearchType").val("OrderNo");

                $("#SearchStartDate").val("");
                $("#SearchEndDate").val("");

                show();

                urlService.dataProvider(GetSearchedOrderHistoryDetails, "POST", { searchWord: sWord, searchType: sType, pageno: $scope.currentPage, pagesize: $scope.ordersPerPage })
                    .then(function (searchResults) {
                        if (searchResults.length > 0) {
                            $('#ShowOHtitle').show();
                            $('#ShowNoOHtitle').hide();
                            $('#divOrderHistory').show();

                            $('.sorting_navigation').show();
                            $('#searchCategoryDiv').show();
                            $('.searchDatesDiv').show();

                            $scope.IsSearchOrderHistory = false;
                            $scope.IsOrderHistoryByDates = false;

                            $scope.repOrderHistory = searchResults;
                            $scope.Orders = searchResults;
                            $scope.totalOrders = $scope.Orders.length;
                            $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                            if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                                $scope.pageDynamicCount = $scope.totalOrders;
                            } else {
                                $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                            }

                            if (searchResults.Coupons != null && searchResults.Coupons != undefined) {
                                $scope.repCpSaving = searchResults.Coupons.length == 0 ? null : searchResults.Coupons[0].Amount;
                                $scope.repCpSavingDesc = searchResults.Coupons.length == 0 ? null : searchResults.Coupons[0].Description;
                            }

                            for (j = 0; j < searchResults.length; j++) {
                                if (searchResults[j].Products != null && searchResults[j].Products != undefined) {
                                    if (searchResults[j].Products.length > 0) {
                                        for (i = 0; i < searchResults[j].Products.length; i++) {

                                            if (searchResults[j].Products[i].TrackingNo != null && searchResults[j].Products[i].TrackingNo.length > 0) {
                                                var re = /TRACK_NO/gi; str = str.replace("&amp;", "&"); var newstr = str.replace(re, searchResults[j].Products[i].TrackingNo);
                                                searchResults[j].Products[i].TrackURL = newstr;
                                            }
                                            else {
                                                searchResults[j].Products[i].TrackURL = "";
                                            }
                                        }
                                    }
                                }
                            }
                            //console.log(searchResults);
                        }
                        else {
                            $('#ShowOHtitle').hide();
                            $('#ShowNoOHtitle').show();
                            $('#divOrderHistory').hide();
                            //jAlert('No Order History Found!');
                        }
                        hide();
                    }).catch(function (ex) {
                        hide();
                    });
            }

            // Order Re-order
            $scope.orderReorder = function (orNo, pageno, pagesize) {

                if ($scope.ordersPerPage == undefined)
                    $scope.ordersPerPage = pagesize;
                if ($scope.currentPage == undefined)
                    $scope.currentPage = pageno;

                var OrderNumber = orNo;

                show();

                urlService.dataProvider(GetOrderReorder, "POST", { ordernumber: OrderNumber, pageno: $scope.currentPage, pagesize: $scope.ordersPerPage })
                    .then(function (data) {

                        if (data == "NO_PRODUCTS_FOUND" || data == "NO_PRODUCTS_ADDED") {
                            jAlert('Unable to add products in cart. May be product not found / discontinued / for members only / low in stock than required quantity.');
                        }

                        if (data == "ALL_PRODUCTS_DISCONTINUED") {
                            jAlert('All order products have been discontinued.');
                        }

                        if (data == "ALL_PRODUCTS_MEMBER_ONLY") {
                            jAlert('All order products are only for members.');
                        }

                        if (data == "ALL_PRODUCTS_STOCK_LOW") {
                            jAlert('All order products are out of stock.');
                        }

                        if (data == "NO_PRODUCTS_FOUND") {
                            jAlert('No Products found to ReOrder');
                        }

                        $scope.GetCartProducts();

                        if (data == "SOME_ADDED_SUCCESSFULLY" || data == "SOME_PRODUCTS_DISCONTINUED" || data == "SOME_PRODUCTS_MEMBER_ONLY" || data == "SOME_PRODUCTS_STOCK_LOW") {
                            $("#cartMsg").show(function () {
                                jAlert('Only valid order products are added to cart. Products which are discontinued / for members only / low in stock than required quantity are not added to cart.');
                                setTimeout(function () { $("#cartMsg").hide(); }, 2000);
                            });
                        }

                        if (data == "ALL_ADDED_SUCCESSFULLY") {
                            $("#cartMsg").show(function () {
                                setTimeout(function () { $("#cartMsg").hide(); }, 2000);
                            });
                        }

                        hide();
                    }).catch(function (ex) {
                        hide();
                    });
            }

            // Order Inovice
            $scope.orderInvoiceByOrNo = function (orNo) {
                show();

                var orDate = $('#orderInvoice').data('orderdate');

                urlService.dataProvider(GetOrderInvoiceByOrNo, "POST", { OrderNumber: orNo, OrderDate: orDate })
                    .then(function (sResults) {
                        $('#ShowOHtitle').show();
                        $('#divOrderHistory').show();
                        $scope.repOrderData = sResults;
                        window.location = applicationUrl + '/Order/OrderInvoice';
                        hide();
                    }).catch(function (ex) {
                        hide();
                    });
            }

            $scope.orderInvoice = function () {

                urlService.dataProvider(getOrderdeatilsMethod, "POST", "").then(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');
            }

            // Orders Navigation START
            $scope.prevPage = function () {
                if ($scope.currentPage > 0) {
                    $scope.currentPage--;
                    sessionStorage.setItem("currentPage", $scope.currentPage);

                    if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                        $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                        $scope.pageDynamicCount = $scope.totalOrders;
                    } else {
                        $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                        $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                        sessionStorage.setItem("pageDynCount", $scope.pageDynamicCount);
                    }
                    if ($scope.IsSearchOrderHistory) {
                        $scope.SearchOrderHistory($scope.currentPage, $scope.pageSize);
                    }
                    else if ($scope.IsOrderHistoryByDates) {
                        $scope.SearchOrderHistoryByDates($scope.currentPage, $scope.pageSize);
                    }
                    else {
                        $scope.orderHistory($scope.currentPage, $scope.pageSize);
                    }
                }
            };

            $scope.prevPageDisabled = function () {
                return $scope.currentPage === 0 ? "disabled" : "";
            };

            $scope.pageCount = function () {
                if ($scope.ordersPerPage == 0) {
                    return 0;
                }
                return Math.ceil($scope.totalOrders / $scope.ordersPerPage) - 1;
            };

            $scope.nextPage = function () {

                if ($scope.currentPage < $scope.pageCount()) {
                    $scope.currentPage++;
                    sessionStorage.setItem("currentPage", $scope.currentPage);

                    if ($scope.currentPage == parseInt($scope.totalOrders / parseInt($scope.pageSize))) {
                        $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                        $scope.pageDynamicCount = $scope.totalOrders;
                    } else {
                        $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                        $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                        sessionStorage.setItem("pageDynCount", $scope.pageDynamicCount);
                    }
                    if ($scope.IsSearchOrderHistory) {
                        $scope.SearchOrderHistory($scope.currentPage, $scope.pageSize);
                    }
                    else if ($scope.IsOrderHistoryByDates) {
                        $scope.SearchOrderHistoryByDates($scope.currentPage, $scope.pageSize);
                    }
                    else {
                        $scope.orderHistory($scope.currentPage, $scope.pageSize);
                    }
                }
                //paging();
            };

            $scope.nextPageDisabled = function () {
                return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
            };

            $scope.range = function () {

                var rangeSize = 15;
                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.totalOrders / parseInt($scope.pageSize))) {
                    $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                    $scope.pageDynamicCount = $scope.totalOrders;
                } else {
                    $scope.pageStartIndex = $scope.currentPage * $scope.ordersPerPage + 1;
                    $scope.pageDynamicCount = parseInt($scope.pageSize) * ($scope.currentPage + 1);
                    sessionStorage.setItem("pageDynCount", $scope.pageDynamicCount);
                }
                sessionStorage.setItem("currentPage", $scope.currentPage);
                if ($scope.IsSearchOrderHistory) {
                    $scope.SearchOrderHistory($scope.currentPage, $scope.pageSize);
                }
                else if ($scope.IsOrderHistoryByDates) {
                    $scope.SearchOrderHistoryByDates($scope.currentPage, $scope.pageSize);
                }
                else {
                    $scope.orderHistory($scope.currentPage, $scope.pageSize);
                }
            };

            $scope.numberOfPages = function () {
                return Math.ceil($scope.Orders.length / $scope.pageSize);
            }
            //

            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', '').then(function (data) {
                $scope.CountryList = data;
                $scope.Countrys = $scope.CountryList[0];

            });

            urlService.dataProvider(getStateMethod, 'POST', '').then(function (data) {
                if (data != 'ADDED_FAIL') {
                    $scope.StateList = data;
                    $scope.TmpStateList = data;
                    //$scope.States = $scope.StateList[0];
                }
                else {
                    //if states not available
                    //$scope.StateList = [{ StateDescription: 'No States Available' }];
                    $scope.inputEnbl = true;
                    $("input#States").val('');
                }
            });

            $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', { countrycode: a.CountryCode }).then(function (data) {
                        if (data != 'ADDED_FAIL') {
                            $scope.StateList = data;
                            //$scope.States = $scope.StateList[0];
                            var result = $.grep($scope.StateList, 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('');
                            }
                        }
                        else {
                            //if states not available
                            //$scope.StateList = [{ StateDescription: 'No States Available' }];
                            $scope.inputEnbl = true;
                            $("input#States").val('');
                        }
                    });
                }
                else {
                    $scope.inputEnbl = true;
                    $("input#States").val('');
                }
                //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!');
                } else {
                    $('#States').next().empty();
                }
                if ($('#States').val() == "undefined") {
                    stateCode = '';
                } 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).then(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", '').then(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');
                        }
                    }).catch(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', '').then(function (data) {
                    $scope.shipViaCode = data;
                    $scope.shipViaCodeDD = $scope.shipViaCode[0];
                }).catch(function (x) {
                });
            }
            $scope.shipViaCodeClient();

            //get Favourites Products
            $scope.GetFavouriteItems = function (Masterid) {
                var getFavouritesArgu = { masterid: Masterid };
                urlService.dataProvider(getFavouriteItems, "POST", getFavouritesArgu).then(function (data) {
                    $scope.FavouriteItems = unique(data);
                });
            }

            //Delete Favourite Item
            $scope.DeleteFavouriteItem = function (productid) {
                $('#popLoader').show();
                var removeFavouriteArgu = { productid: productid };
                urlService.dataProvider(removeFavouriteItems, "POST", removeFavouriteArgu).then(function (data) {
                    $('#popLoader').hide();
                }).catch(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).then(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).then(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).then(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')) + 3;
                $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).then(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 () {
                var currentUrl = window.location + ''
                window.location.href = "/Login/?returnURL=" + currentUrl + "/&SSOL=Y" ;
            }

            $scope.Login = function () {
                $scope.UserId = '';
                var username = $scope.UserName;
                if (isNumeric(username) == 1) {
                    $scope.UserId = lpad(username, 8);
                }
                else {
                    $scope.UserId = username;
                }

                function isNumeric(input) {
                    return (input - 0) == input && (input + '').replace(/^\s+|\s+$/g, "").length > 0;
                }

                function lpad(value, padding) {
                    var zeroes = "0";
                    for (var i = 0; i < padding; i++) { zeroes += "0"; }
                    return (zeroes + value).slice(padding * -1);
                }

                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.UserId, Password: $scope.Password, CurrentUrl: currentUrl, RememberMe: ChkRememberMe };
                    urlService.dataProvider(LoginInfo, "POST", commeArgu).then(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).then(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) + '!');
                            jAlert('There are only ' + parseFloat(data.replace('REMAINING_', '')) + ' left in stock. Please lower your quantity selection.');
                        }
                        else if (data == "ADDED_FAIL") {
                            jAlert('Unable to add product to cart,Please try later.');
                        }
                        //$scope.getCartData();
                        $scope.GetCartProducts();
                        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).then(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) + '!');
                                jAlert('There are only ' + parseFloat(data.replace('REMAINING_', '')) + ' left in stock. Please lower your quantity selection.');
                            }
                            else if (data == "ADDED_FAIL") {
                                jAlert('Unable to add product to cart,Please try later.');
                            }
                            //$scope.getCartData();
                            $scope.GetCartProducts();
                            hide();

                            if (data == "ADDED_SUCCESSFULLY") {
                                $("#cartMsg").show(function () {
                                    setTimeout(function () { $("#cartMsg").hide(); }, 2000);
                                });
                            }

                        });
                        //    } else {
                        //        hide();
                        //    }
                        //});
                    } else {
                        hide();
                        jAlert('Out Of Stock!');
                    }
                }
            };


            $scope.ComposeAddCart = function ($event, from) {
                //console.log('adding to cart');
                $scope.ComposePreview();
                alert("adding to cart");
                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.");
                }

            }

            $scope.GetBookSeriesItems = function (Masterid) {
                var getFavouritesArgu = { masterid: Masterid };
                urlService.dataProvider(getBookSeriesMethod, "POST", '').then(function (data) {
                    $scope.BookSeriesItems = data;
                });//for
            };
            $scope.GetBookSeriesItems();
        }]);

 
;
SIAMShopping.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
SIAMShopping.filter("sanitize", ['$sce', function ($sce) {
    return function (htmlCode) {
        return $sce.trustAsHtml(htmlCode);
    }
}]);

SIAMShopping.filter("jsDate", function () {
    return function (x) {
        return new Date(parseInt(x.substr(6)));
    };
});

//Image not available or image link borken 
SIAMShopping.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.on('error', function () { setDefaultImage(el); });

        }

    }
});

//restric Input Limit 
SIAMShopping.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
//SIAMShopping.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;
//            });
//        }
//    }
//}]);
SIAMShopping.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
SIAMShopping.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
SIAMShopping.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
SIAMShopping.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 LoginInfo = '/Login/LoginInfo',

    categoryMethod = '/home/getItems',
    allProductsMethod = '/home/GetProducts',
    getBookSeriesMethod = '/home/GetBookSeries',

    sessionMethod = '/Product/GetSessionInfo',
    addToCartMethod = '/Product/AddProductToCart',
    cartDetailsMethod = '/Product/GetCartDetails',
    saveWishlistMethod = '/Product/SaveWishList',
    getWishlistMethod = '/Product/GetWishListItems',
    getFavouriteItems = '/Product/GetFavouriteItems',
    removeFavouriteItems = '/Product/RemoveFavouriteItem',
    relatedProductsMethod = '/Product/GetRelatedItems',
    getRecentlyViewedItems = '/Product/GetRecentlyViewedItems',
    addRecentlyViewedItems = '/Product/AddToRecentlyVieweddItem',
    getOrInsertProductRevuew = '/Product/GetProductReviews',
    getSingleProduct = '/Product/GetProductDetails',

    getCountryMethod = '/Order/GetCountries',
    getStateMethod = '/Order/GetStates',
    GetAddressesMethod = '/Order/GetAddresses',
    GetCreditCardMethod = '/Order/GetCreditCards',
    GetOrderHistory = '/Order/GetOrderHistory',
    GetSearchedOrderHistoryDetails = '/Order/GetSearchedOrderHistoryDetails',
    GetSearchedOrderHistoryDetailsByDates = '/Order/GetSearchedOrderHistoryDetailsByDates',
    GetOrderReorder = '/Order/OrderReorder',
    GetOrderInvoiceByOrNo = '/Order/GetOrderInvoiceByOrNo',
    GetDigitalDownloads = '/Order/GetOrderedECDFileLinks',
    createOrderMethod = '/Order/CreateOrder',
    applyCouponforOrder = '/Order/ApplyCouponforOrder',
    getOrderdeatilsMethod = '/Order/GetOrderdeatils',
    addCCardMethod = '/Order/AddCreditCard',
    addAddressMethod = '/Order/AddAddress',
    shipViaCodeMethod = '/Order/GetShipViaCodes',
    setAddress = '/Order/ChangeAddress',
    GetPageURLPreview = "/Order/GetPageURL";


//set Default image service
SIAMShopping.factory('defaultImg', function () {
    return {
        noImageUrl: applicationUrl + '/Images/Image-not-available.png'
    };
});

//Accessing all methods
// application/json; charset=utf-8
// 
SIAMShopping.factory('urlService', ['$http', function ($http) {
    show();
    return {
        dataProvider: function (url, type, params) {
            return $http({
                method: type,
                url: applicationUrl + url,
                params: params,
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                dataType: "json"
            }).then(function (response) {
                //console.log("url: " + url );
               // console.log("type: " + type );
               // console.log("params: " + params);
                //console.log("response data: " + response.data);
                //console.log("JSON data: " + JSON.stringify(data, null, "    "));
                //console.log("JSON response data: " + response.data);
                //console.log("JSON err: " + err);
                return response.data; // PATRICK
                }).catch(function (response) {

                  //  console.error('Gists error', response.status, response.data);

                /*.catch(function (x) {
                console.log("Catch Error" );*/
            });
        }
    }
}]);

SIAMShopping.factory("productCart", function ($http, $log, $q, urlService) {
    function addingToCart(obj, scope, from) {
        if (from == 'delete')
            $('#popLoader').show();
        urlService.dataProvider(addToCartMethod, "POST", obj).then(function (data) {
            if (data == "PRODUCTMEMBER_ONLY") {
                if (scope.sesCustomerId != '') {
                    jAlert('This Product is only for members.');
                    hide();
                } 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) + '!');
                jAlert('There are only ' + parseFloat(data.replace('REMAINING_', '')) + ' left in stock. Please lower your quantity selection.');
            }
            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")==-1?wLArray.indexOf("Order"):0;
                

            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);
                });
            }
        }).catch(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();
            $('#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).then(function (d) {

                //  this.getProductItem(id, getEvent).then(function (d) { <- this is failing

               // console.log("Factory: D: " + d); //return stff works its the return repsonse or data that doesnt work right.....
                
                if ($(getEvent.target).attr("data-umb") != "true" || typeof $(getEvent.target).attr("data-umb") === "undefined") {
                    this.currentProduct = d;
                  //  console.log("Factory: data-umb is not true ");
                } else {
                    //this.currentProduct = $.grep(d.UmbrellaSubProducts, function (itemType, i) {
                    //    //console.log($("#prdQuantity").val())
                    //    return (itemType.Option1Subcode == $("#prdQuantity").val())
                    //});
                    this.currentProduct = $.grep(d.UmbrellaSubProducts, function (itemType, i) {
                        //console.log($("#prdQuantity").val())
                      //  console.log("Factory: this.currentProduct " + this.currentProduct );
                        return (itemType.ProductId == id)
                    });
                    this.currentProduct = this.currentProduct[0];
                };


             //   console.log("Factory: AddProduct: " + this.currentProduct);

                var svcode = scope.shipViaCodeDD == undefined ? 'BR_2ND_DAY' : scope.shipViaCodeDD.Code;
                var cartArgu = {
                    ProductId: this.currentProduct.ProductId,
                    Quantity: from == "delete" ? 0 : $("#avalQuantity").val() || $("#" + this.currentProduct.ProductId).val() || 1,
                    From: from,
                    StrCustomOrStandard: scope.viewUmbrellProductDD || '',
                    ComposeID: '',
                    shipviacode: svcode
                };
                //console.log(this.currentProduct.Inventoried);

                if (this.currentProduct.Inventoried == true) {
                    if (this.currentProduct.StockAvailable >= 1) {
                        if (from == "delete")
                        {
                            addingToCart(cartArgu, scope, from);
                        }
                        else 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) + '!');
                            jAlert('There are only ' + parseFloat(this.currentProduct.StockAvailable) + ' left in stock. Please lower your quantity selection.');
                            return
                        }
                    } else {
                        //console.log("Check Backorder is available");
                          addingToCart(cartArgu, scope, from);
                    }
                } 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"
                }).then(function (response) {
                    //console.log("Product");
                    //console.log(data);
                   //console.log("deferred.resolve(response.data);" );
                   //  console.log("Get response.data: " + JSON.stringify(response.data, null, "    "));
                    
                    deferred.resolve(response.data);
                    return deferred.promise;
                    }).catch(function (x) {
                       // console.log("deferred.reject(x);");
                    deferred.reject(x);
                    });
             //   console.log("deferred.promise data-umb: " );
                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"
                }).then(function (response) {
                    //console.log("Sub Product");
                    //console.log(data);
                    
                   // console.log("deferred.resolve(response.data);");
                   // console.log("Get response.data: " + JSON.stringify(response.data, null, "    ") );
                    deferred.resolve(response.data);
                    }).catch(function (x) {
                       // console.log("deferred.reject(x);");
                    deferred.reject(x);
                    });
               // console.log("deferred.promise NOT data-umb: " );
                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;
            };
        }

    }
});;
