﻿// ------------------------------------------------------------------------------------------
// Copyright AspDotNetStorefront.com, 1995-2011.  All Rights Reserved.
// http://www.aspdotnetstorefront.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
function $bindMethod(object, method) {
    return function () {
        return method.apply(object, arguments);
    };
}

function $window_addLoad(handler) {
    if (window.addEventListener) {
        window.addEventListener('load', handler, false);
    }
    else if (document.addEventListener) {
        document.addEventListener('load', handler, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', handler);
    }
    else {
        if (typeof window.onload == 'function') {
            var oldload = window.onload;
            window.onload = function () {
                oldload();
                handler();
            }
        }
        else { window.onload = init; }
    }
}

function $getElement(id, handler) {
    var el = document.getElementById(id);
    return el;
}

var Keys = {
    Enter: 13
}

function $handleSearchEnterKey(id, handler) {
    var el = $getElement(id);
    if (el) {
        var delKeypress = function (e) {

            var keyCode;
            if (e && e.which) {
                keyCode = e.which;
            }
            else if (typeof (event) != 'undefined') {
                keyCode = event.keyCode;
            }

            // we must manually invoke the Page_ClientValidate
            // method here since relying on the normal behavior
            // is not guaranteed to set the appropriate validation flags
            // to stop the postback.
            if (keyCode == Keys.Enter) {
                if (typeof (Page_ClientValidate) != 'undefined') {
                    if (Page_ClientValidate() == false) {
                        return;
                    }
                }
                handler();
                return false;
            }
        }
        el.onkeypress = delKeypress;
    }
}

//This function is assoicated with onclick event of color size
//Used in ShoppingCart.cs
function PopulateSizeDropDownBasedOnColor(colorValue, ObjJSON1, sizeDdlId) {
    var ddl = document.getElementById(sizeDdlId);
    ddl.length = 1;
    var arr = ObjJSON1[colorValue];
    if (arr !== undefined) {
        for (var i = 0; i < arr.length; i++) {
            var opt = document.createElement("option");
            ddl.options.add(opt);
            opt.text = arr[i].Text;
            opt.value = arr[i].Value;
        }
    }
}

//implement Tier Pricing
//Following codes are getting used in Deal/Side Deal/Product Detail/Product Selection
function setTierBindassPrice(elemName, prefixElemName, youSaveElem, arrayName, index) {
    if (!index || index >= arrayName.length) {
        index = 0;
    }

    if (arrayName.length > 1) {
        var interval = 3000;
        if (index == 0) {
            interval = 5000;
        }

        $("#" + elemName).html(arrayName[index].Price);
        $("#" + prefixElemName).html(arrayName[index].Prefix);

        if ($("#" + prefixElemName).hasClass('ThreeRight') == false) {
            $("#" + prefixElemName).addClass('ThreeRight');
        }

        $("#" + youSaveElem).html(arrayName[index].YouSave);
        setTimeout(function () {
            setTierBindassPrice(elemName, prefixElemName, youSaveElem, arrayName, index + 1);
        }, interval);
    } else {
        //if only 1 element is passed
        $("#" + elemName).html(arrayName[index].Price);
        $("#" + youSaveElem).html(arrayName[index].YouSave);
    }
};

//Following function is to provide expand and collapse feature to product description in 
// ProductDetails and MainDeal
$(document).ready(function () {
    $('.head-text').click(function () {
        $('.product-content').toggle();
        if ($(this).hasClass('expanded')) {
            $(this).addClass('collapsed').removeClass('expanded');
        }
        else {
            $(this).addClass('expanded').removeClass('collapsed');
        }
    });
});

//Following function is generic function to show the time left for deal to end
//This function is getting used in following files
//1. sideDeal.default.xml.config
//2. Deal.default.xml.config
//3. productDetail.default.xml.config
function getDealDurationLeft(elem, dealStartDateTime, dealEndDateTime) {
    $.ajax({
        url: siteBase + "SalesStatistics.ashx",
        type: "GET",
        data: {
            "StartDateTime": dealStartDateTime,
            "EndDateTime": dealEndDateTime,
            "Context": "DealEndsDuration"
        },
        error: function (response) {
            //alert("error in deal duration date");
        },
        success: function (response) {
            var hrs = parseInt(response.DealTimeHrs);
            var mins = parseInt(response.DealTimeMins);
            var DealEndDate = response.DealEndDate;
            setDealDuration(elem, hrs, mins, DealEndDate);
        },
        async: true
    });
};

function setDealDuration(elem, hrs, mins, DealEndDate) {
    if (hrs > 23) {
        $("." + elem).html(DealEndDate);
    }
    else if (hrs <= 23 && mins > -1) {
        var h = hrs;
        if (hrs >= 0 && hrs <= 9) {
            h = "0" + h;
        }

        var m = mins; ;
        if (mins >= 0 && mins <= 9) {
            m = "0" + m;
        }

        $("." + elem).html(" in " + h + " Hrs " + m + " Mins");
    }
    else {
        $("." + elem).html(" in 00 Hrs 00 Mins");
    }

    if (hrs == 0) {
        if (mins == -1) {
            window.location.href = siteBase;
            return;
        } else {
            mins = mins - 1;
        }
    } else {
        if (mins > 0) {
            mins = mins - 1;
        }
        else {
            mins = 59;
            hrs = hrs - 1;
        };
    }
    setTimeout(function () {
        setDealDuration(elem, hrs, mins, DealEndDate);
    }, 60000);
}

//Following function is generic function to show the deal progressbar statuc
//This function is getting used in following files
//1. sideDeal.default.xml.config
//2. Deal.default.xml.config
//3. productDetail.default.xml.config
function getDealProgressBarStatus(elem, dealId, productId) {
    $.ajax({
        url: siteBase + "SalesStatistics.ashx",
        type: "GET",
        data: {
            "DealId": dealId,
            "ProductId": productId,
            "Context": "DealProgressBar"
        },
        error: function (response) {
            //alert("error in deal progress bar");
        },
        success: function (response) {
            $("#" + elem).css({ "width": response.DealSold + "%" });
        },
        async: true
    });
};

//Function for Tier Pricing getting called from Shopping Cart
function CreateTierPriceDialog(price, qtyId) {
    var url = siteBase + "ProductTierPrice.aspx?price=" + price + "&qtyId=" + qtyId;
    CreateDialogMaster(url, 'Discount Details', 220);
}

//Function is getting used in Discuss this deal
function CreateStealStats(dealId, productId) {
    var url = siteBase + "StealStats.aspx?DealId=" + dealId + "&ProductId=" + productId;
    CreateDialogMaster(url, 'Stats of the steal');
}

// In Discuss this deal
function ImageGalleryDialog(isDeal, id, prodId, name, variant) {
    if (isDeal == 'true') {
        CreateDialogForDeal(id, name, isDeal);
    } else {
        CreateDialogForProduct(prodId, name, variant);
    }
}

//Function is getting used in Discuss this deal
function CreateDialogForDeal(id, name, isDeal) {
    var url = siteBase + "/imagegallery.aspx?ID=" + id + "&IsDeal=" + isDeal;
    if (name != '') {
        url = url + "&ImageFilenameOverride=" + name;
    }
    CreateDialogMaster(url, 'Image Gallery');
}

//Function is getting used in dealProduct and ProductVariant configuration file
function CreateDialogForProduct(id, name, variant) {
    var url = siteBase + "imagegallery.aspx?ID=" + id + "&ForVariant=" + variant;
    if (name != '') {
        url = url + "&ImageFilenameOverride=" + name;
    }
    CreateDialogMaster(url, 'Image Gallery');
}

//In check out one page
function CreateDialogForgetPassword() {
    var url = siteBase + "PasswordRecovery.aspx";
    CreateDialogMaster(url, 'Forgot Password', 450);
}

//Base method which is invoked
function CreateDialogMaster(url, mytitle, mywidth) {
    if (mywidth == null) {
        mywidth = 580;
    }
    $("#ImageGalleryDialog").empty();
    $("#ImageGalleryDialog").load(url).dialog(
    {
        autoOpen: false,
        modal: true,
        title: mytitle,
        position: ['center', 50],
        resizable: false,
        height: 650,
        width: mywidth,
        zindex: 9999,
        open: function (event, ui) {
            $('.ui-dialog-buttonpane').hide();
        },
        close: function (event, ui) {
            $("#ImageGalleryDialog").empty();
        }
    });

    $('#ImageGalleryDialog').dialog('open');
}

function CreateMessageDialog(titleText, messageData) {
    $('#ImageGalleryDialog').empty().html(messageData);
    $("#ImageGalleryDialog").dialog({
        autoOpen: false,
        modal: true,
        title: titleText,
        resizable: false,
        position: ['center'],
        height: 140,
        width: 250,
        zindex: 9999,
        close: function (event, ui) {
            $("#ImageGalleryDialog").empty();
        },
        open: function (event, ui) {
            $buttonPane = $(this).next();
            $buttonPane.find('button:first').addClass('ui-state-default').addClass('ui-priority-primary');
        },
        buttons: {
            OK: function () {
                $(this).dialog("close");
            }
        }
    });

    $('#ImageGalleryDialog').dialog('open');
}

// Following function are used in IWantOne.ascx 
function AddToWishList(pId, vId, cId) {
    var service = new ActionService();
    if (service) {
        service.AddToWishlist(pId, vId, cId, AddToWishlistComplete);
    }
}

function AddToWishlistComplete(result) {
    CreateMessageDialog('Message', result);
}

//GENERIC FUNCTION TO LIMIT CHRACTER INPUTS
function limitChars(textid, limit, infodiv) {
    var text = $('#' + textid).val();
    var textlength = text.length;
    if (textlength == 0) {
        $('#' + infodiv).html('upto ' + limit + ' characters!');
        $('#' + infodiv).show();
    }
    else if (textlength > limit) {
        $('#' + infodiv).html('You cannot write more then ' + limit + ' characters!');
        $('#' + textid).val(text.substr(0, limit));
        $('#' + infodiv).show();
        return false;
    }
    else {
        $('#' + infodiv).html('You have ' + (limit - textlength) + ' characters left.');
        $('#' + infodiv).show();
        return true;
    }
}

function CreateInviteFriendDialog(mytitle, ProductId) {
    var url = siteBase + "InviteFriend.aspx";
    if (ProductId != null && ProductId != '') {
        url = url + "?ProductId=" + ProductId;
    }

    if (mytitle != null || mytitle == '') {
        mytitle = "Your purchase can be absolutely FREE";
    }

    var mywidth = 850;
    InitInviteFriendDialog(url, mytitle, mywidth);
    $('#ImageGalleryDialog').dialog('open');
}

function InitInviteFriendDialog(url, mytitle, mywidth) {
    if (mywidth == null) {
        mywidth = 580;
    }

    var el = document.createElement("iframe");
    el.setAttribute('id', 'ifrm');
    el.setAttribute('src', url);
    el.setAttribute('frameborder', "0");
    el.setAttribute('width', (mywidth - 20) + "px");
    el.setAttribute('height', "670px");
    el.setAttribute('allowtransparency', "true");
    el.setAttribute('hspace', "0");
    el.setAttribute('vspace', "0");
    el.setAttribute('align', "middle");
    el.setAttribute('scrolling', "no");
    el.setAttribute('marginwidth', "0");
    el.setAttribute('marginheight', "0");

    $("#ImageGalleryDialog").empty();
    $("#ImageGalleryDialog").append(el);
    $("#ImageGalleryDialog").dialog(
    {
        autoOpen: false,
        modal: true,
        title: mytitle,
        position: ['center', 10],
        height: 650,
        width: mywidth,
        zindex: 9999,
        open: function (event, ui) {
            $('.ui-dialog-titlebar').css('font-weight', '600');
            $('.ui-dialog-titlebar').css('font-size', '18px');
            $('.ui- corner-all').css('margin-bottom', '5px');
        },
        close: function (event, ui) {
            $("#ImageGalleryDialog").dialog("close");
        }
    });
}
