﻿/*
* @namespace The base namespace for all Captra javascript projects.
*/
cptr={};
/**
* @namespace Contains basic functionality for all Captra javascript projects.
*/
cptr.util = cptr.util || {};
/**
* Logs a message to the debugger-specific console.
* @param {String} message The message to output to the console.
*/
cptr.util.logToConsole = function (msg) {
    if (typeof (console) != 'undefined') console.log(msg);
};

var currentPage;

function ResizePageContentHeight(page) {
    var $page = $(page),
		$content = $page.children(".ui-content"),
		hh = $page.children(".ui-header").outerHeight() || 0,
		fh = $page.children(".ui-footer").outerHeight() || 0,
		pt = parseFloat($content.css("padding-top")),
		pb = parseFloat($content.css("padding-bottom")),
		wh = window.innerHeight;
    ww = window.innerWidth;
    $content.height(wh - (hh + fh) - (pt + pb));
    $('.captra-header').css('width',ww - 75);
//    var height = $(".ui-scrollview-clip").css('height');
//    if(height > $content.height)
//        $(".ui-scrollview-clip").css("overflow-y", "hidden");
}

    $(window).bind("orientationchange", function (event) {
        ResizePageContentHeight($(".ui-page"));
    });

    $(window).bind("resize", function (event) {
        ResizePageContentHeight($(".ui-page"));
    });

function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    };

function popErrorMessage(errorMessage) {
    jQuery("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>" + errorMessage + "</h1></div>")
        .css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100, "z-index": 999999 })
        .appendTo(currentPage)
        .delay(800)
        .fadeOut(400, function () {
            $(this).remove();
        });
}

function popMessage(Message) {
    jQuery("<div class='ui-loader ui-overlay-shadow ui-body-a ui-corner-all'><h1>" + Message + "</h1></div>")
        .css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100, "z-index": 999999 })
        .appendTo(currentPage)
        .delay(800)
        .fadeOut(400, function () {
            $(this).remove();
        });
    }


    $(document).bind("mobileinit", function () {
        //apply overrides here
        $.mobile.defaultPageTransition = 'fade';
        $.mobile.loadingMessage = "Loading. Please wait...";
        //$.mobile.page.prototype.options.degradeInputs.date = true;
        $(document).bind("pageshow", function () {
            ResizePageContentHeight($(".ui-page"));
        });
        $(document).bind("pageinit", function () {
            $('.headerCaptraIcon').click(function (event) {
                var $page = $(".ui-page");
                $content = $page.children(".ui-content"),
		        hh = $page.children(".ui-header").outerHeight() || 0,
		        fh = $page.children(".ui-footer").outerHeight() || 0,
		        pt = parseFloat($content.css("padding-top")),
		        pb = parseFloat($content.css("padding-bottom")),
		        wh = window.innerHeight;
                ww = window.innerWidth;
                var height = (wh - (hh + fh) - (pt + pb));
                if ($("#menu:hidden").length > 0) {
                    $("#menu").show().animate({
                        opacity: 1,
                        left: "0px",
                        top: "51px",
                        width: "100%",
                        height: height

                    });
                } else {
                    $("#menu").show().animate({
                        opacity: 0,
                        left: "0px",
                        top: "51px",
                        width: "0",
                        height: 0

                    });
                }
            });
        });

        $('#nav-more').live('click', function () {
            $('#main-menu')
            .css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100, "z-index": 999999 })
            .appendTo(currentPage);
        });

        $('#tapToCheckout').live('click', function () {
            currentPage = this.parentNode;
            $.mobile.changePage('/cart/'
                            , { changeHash: true,
                                transition: "slide"
                            }
                        );
        });

        $('.buyThisPhoto').live('click', function () {
            var digitalResourceGuid = $(this).attr('id');
            $.mobile.showPageLoadingMsg();
            GetCartItemEditor(0, digitalResourceGuid);
        });

        function GetCartItemEditor(cartItemId, digitalResourceGuid) {
            var url = '/EditCartItem?cartItemId=' + cartItemId + '&digitalResourceGuid=' + digitalResourceGuid;
            $('#page-cartEditor').remove();
            $.mobile.loadPage(url, { reloadPage: false, loadMsgDelay: 0 }).done(function (url, options, newPage, dupCachedPage) {

                $('#cancelCartEditor').click(function () {
                    $('#page-cartEditor').slideUp('slow', function () {
                        $('#page-cartEditor').remove();
                    });
                });

                $("#updatecart").button().click(function () {
                    var post = $(this).attr("name") + "=" + $(this).val();
                    var form_data = $('#page-cartEditor form').serialize() + "&" + post;
                    $.mobile.showPageLoadingMsg();
                    $.post($('form').attr('action'), form_data, function (data) {
                        if (data) {
                            if (data.error) {
                                alert(data.errormessage);
                                return;
                            }
                            $.mobile.hidePageLoadingMsg();
                            $('#page-cartEditor').slideUp('slow', function () {
                                $('#page-cartEditor').remove();
                                if ($('#photoPreviewContainer').length > 0) {
                                    $('#photoPreviewContainer').hide();
                                    $('.mobile-overlay').fadeOut();
                                    $('.mobile-overlay').remove();
                                    popMessage('Successfully added to cart');
                                } else if ($('#page-mobileCart').length > 0) {
                                    $.mobile.changePage(document.location.href, { reloadPage: true, changeHash: true });
                                }
                            });

                        }
                        else {


                        }
                    });
                    return false;

                });

                $('.ui-btn-left').remove();
                newPage.show();
            });
        }

        $('.closePreview').live('click', function () {

            $('#photoPreviewContainer').hide();
            $('.mobile-overlay').fadeOut();
            $('.mobile-overlay').remove();

        });
        $('.shareThisPhoto').live('click', function () {
            var digitalResourceGuid = $('#previewImageMobile').data('resourceguid');
            window.location = '/SharePhoto/' + digitalResourceGuid;
        });

        //Page specific scripts
        var refreshPhotosTimerId = null;
        function refreshPhotos() {
            var currentPage = Number($('#currentPageIndex').val());
            gotoPage(currentPage);
        }

        function gotoPage(pageIndex) {
            var eventId = $('#eventId').val();
            var navtabPhotos = $('#nav-photos');

            var url = '/Photos/' + eventId + '?renderPartial=true&pageIndex=' + pageIndex;
            navtabPhotos.attr('href', '/Photos/' + eventId + '?pageIndex=' + pageIndex);
            $.mobile.showPageLoadingMsg();
            $.ajax({
                type: 'GET',
                global: false,
                async: true,
                url: url,
                dataType: 'html',
                success: function (result) {
                    $.mobile.hidePageLoadingMsg();
                    var newPage = $(result);
                    newPage = newPage.hide();

                    $('#eventPhotosContainer').remove();
                    $('.ui-scrollview-view').append(newPage);
                    newPage.fadeIn(1000);
                    $('#page-EventPhotos').trigger('pageinit');


                },
                error: function (result) {
                    $.mobile.hidePageLoadingMsg();
                }
            });
        }

        $('#page-TaggedPhotos').live('pageinit', function (event) {
            currentPage = this;

            $("img.lazyload").each(function () {
                $(this).attr("src", $(this).attr("original"));
                $(this).removeAttr("original");
            });
        });


        $('#page-cropPhoto').live('pageshow', function (event) {
            currentPage = this;
            $('#cropTarget').attr('src', $('#previewPhoto').attr('src'));
            $('#photoPreviewContainer').hide();
            $('.mobile-overlay').remove();
        });
        $('#page-makeKeyTag').live('pageshow', function (event) {
            currentPage = this;
            $('#photoPreviewContainer').hide();
            $('.mobile-overlay').remove();
        });
        $('#page-deletePhoto').live('pageshow', function (event) {
            currentPage = this;
            $('#photoPreviewContainer').hide();
            $('.mobile-overlay').remove();
        });
        $('#page-EventPhotos').live('pageinit', function (event) {
            currentPage = this;
            //if(refreshPhotosTimerId == null) 
            //   refreshPhotosTimerId = setInterval(refreshPhotos, 20000);

            var angle = 0;

            function showCoords(c) {
                $('#x').val(c.x);
                $('#y').val(c.y);
                $('#x2').val(c.x2);
                $('#y2').val(c.y2);
                $('#w').val(c.w);
                $('#h').val(c.h);
            };

            $('#btnCrop').click(function () {
                $('#cropTarget').Jcrop({
                    onChange: showCoords,
                    onSelect: showCoords
                });
            });

            $('#btnRotate').click(function () {
                rotatePhoto(90);
            });

            $('#btnRotateReverse').click(function () {
                rotatePhoto(-90);
            });
            function rotatePhoto(rotateByAngle) {
                $.mobile.loadingMessage = "Rotating photo. Please wait...";
                $.mobile.showPageLoadingMsg();
                $('#previewPhoto').rotate({ angle: angle, animateTo: angle + rotateByAngle, easing: $.easing.easeInOutExpo,
                    callback: function () {
                        angle += rotateByAngle;

                        var digitalResourceGuid = $('#previewPhoto').data('resourceguid');
                        $.ajax({
                            type: 'POST',
                            global: false,
                            async: true,
                            url: '/Events/Photo',
                            dataType: 'json',
                            data: { rotateresource: true, digitalResourceGuid: digitalResourceGuid, angle: rotateByAngle
                            },
                            success: function (result) {
                                $.mobile.hidePageLoadingMsg();
                                $.mobile.loadingMessage = "Loading. Please wait...";
                                if (result.success) {
                                    if ($('#IsLoggedInMerchant').val() == "True")
                                        showImage(digitalResourceGuid, true);
                                    angel = 0;
                                } else {
                                    popErrorMessage('Oops. Our bad. Something went wrong trying to rotate the photo. Please try again.');
                                }
                            },
                            error: function (result) {
                                $.mobile.hidePageLoadingMsg();
                                //jsonFail(result);
                                //popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.');
                            }
                        });

                    }
                })
            }
            $('#btnAutoDetect').click(function () {

                $.ajax({
                    type: 'GET',
                    global: false,
                    async: true,
                    url: '/DigitalKeyTag/AutoDetectKeyTag',
                    dataType: 'json',
                    data: { resourceGuid: digitalResourceGuid
                    },
                    success: function (result) {
                        if (result.error) {
                            alert(result.errormessage);
                        } else {
                            if (result.tagFound) {
                                alert('tag found');
                            } else {
                                alert('Auto detect of tag failed. Please key in either the Code or the ID');
                            }
                        }
                    },
                    error: function (result) {
                        //jsonFail(result);
                        //popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.');
                    }
                });


            });

            $('#btnMakeKeyTag').click(function () {

                var keyCode = $('#digitalKeyCode').val();
                var keyID = $('#digitalKeyID').val();
                currentPage = $('#makeKeyTag');
                $.ajax({
                    type: 'POST',
                    global: false,
                    async: true,
                    url: '/DigitalKeyTag/MakeResourceKeyTag',
                    dataType: 'json',
                    data: { ResourceGuid: digitalResourceGuid, DigitalKeyTagId: keyID, DigitlKeyCode: keyCode },
                    success: function (result) {
                        if (result.error) {
                            popErrorMessage(result.errormessage);
                        } else {
                            if (result.tagFound) {
                                popMessage('Successfully made into a Key Tag');
                                document.location = '/Photos/0';
                            } else {
                                popErrorMessage('Invalid Key ID or Code entered.');
                            }
                        }
                    },
                    error: function (result) {
                        //jsonFail(result);
                        //popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.');
                    }
                });


            });

            $('#nextPhoto').click(function () {
                var resourceGuid = $('#previewPhoto').data('resourceguid');
                var nextImageResourceGuid = $('#' + resourceGuid).parents('li').next().children('a').data('resourceguid');
                if (nextImageResourceGuid != null)
                    showImage(nextImageResourceGuid);
            });

            $('#prevPhoto').click(function () {
                var resourceGuid = $('#previewPhoto').data('resourceguid');
                var prevImageResourceGuid = $('#' + resourceGuid).parents('li').prev().children('a').data('resourceguid');
                if (prevImageResourceGuid != null)
                    showImage(prevImageResourceGuid);
            });

            function showImage(resourceGuid, refresh) {

                if (refresh == null)
                    refresh = false;

                var containerWidth = $('#photoPreviewContainer').width();

                var imgSrc = '';
                //if (containerWidth > 320)
                imgSrc = '/Events/DesktopResourcePreviewImage?resourceGuid=' + resourceGuid;
                //else
                //    imgSrc = '/Events/MobileResourcePreviewImage?resourceGuid=' + resourceGuid;

                if (refresh)
                    imgSrc = imgSrc + '&uid' + event.timeStamp;

                $('.shareThisPhoto').attr('id', resourceGuid);
                $('.buyThisPhoto').attr('id', resourceGuid);
                $('#deleteresource').val(resourceGuid);
                $('#cropresource').val(resourceGuid);

                $.mobile.showPageLoadingMsg();
                var pic_real_width, pic_real_height;
                $("<img/>") // Make in memory copy of image to avoid css issues
                    .attr("src", imgSrc)
                    .load(function () {

                        pic_real_width = this.width;   // Note: $(this).width() will not
                        pic_real_height = this.height; // work for in memory images.
                        var left = (containerWidth / 2) - (pic_real_width / 2)
                        var newImage = $('<img alt="image" class="ui-shadow" id="previewPhoto" data-resourceguid="' + resourceGuid + '" src="' + imgSrc + '" />');

                        $('#currentPhoto').css('left', left.toString() + 'px');
                        $('#photoPreviewContainer').show();
                        $('#previewPhoto').fadeOut();
                        $('#previewPhoto').remove();

                        newImage.hide();
                        newImage.appendTo('#previewPhotoWrapper');
                        $("#previewPhotoWrapper img").css('max-width', pic_real_width);
                        $('#previewPhoto').fadeIn();
                        $('#photoTools').width(pic_real_width);
                        $.mobile.hidePageLoadingMsg();
                    });

            }
            $(".photoThumbnail").click(function () {
                $('.buyThisPhoto ').hide();
                $('#page-EventPhotos').append('<div class="mobile-overlay"></div>');
                var $page = $(".ui-page"),
                angel = 0;
                $content = $page.children(".ui-content"),
		        hh = $page.children(".ui-header").outerHeight() || 0,
		        fh = $page.children(".ui-footer").outerHeight() || 0,
		        pt = parseFloat($content.css("padding-top")),
		        pb = parseFloat($content.css("padding-bottom")),
		        wh = window.innerHeight;
                var height = wh - (hh + fh) - (pt + pb)

                $('#photoPreviewContainer').height(height);
                $('#currentPhoto').height(height);

                var resourceGuid = $(this).data('resourceguid');
                $('#photoPreviewContainer').children().show();
                showImage(resourceGuid);

                $('.buyThisPhoto').show().css('top', 0);

            });
            $(".button-pager").click(function () {
                var page = $(this).data('page');
                gotoPage(page);
            });

            $("#pageNext").click(function () {
                var currentPage = Number($('#currentPageIndex').val());
                var totalPages = Number($(this).data('totalcount'));
                if (currentPage + 1 < totalPages)
                    gotoPage(currentPage + 1);
            });

            $("#pagePrev").click(function () {
                var currentPage = Number($('#currentPageIndex').val());
                if (currentPage > 0)
                    gotoPage(currentPage - 1);
            });


            $("img.lazyload").each(function () {
                $(this).attr("src", $(this).attr("original"));
                $(this).removeAttr("original");
            });

            // set interval 
            //var tid = setInterval(fetchImages, 10000);
            function fetchImages() {
                $.ajax({
                    type: 'GET',
                    global: false,
                    async: true,
                    url: '/Events/RefreshPhotos?eventid=@(Model.SelectedEvent != null ? Model.SelectedEvent.Id : 0)',
                    dataType: 'json',
                    success: function (result) {
                        for (var i = 0; i < result.length; i++) {
                            var id = $('#' + result[i].ResourceGuid)
                            if (id.length == 0) {
                                $.ajax({
                                    type: 'GET',
                                    global: false,
                                    context: result[i],
                                    async: true,
                                    url: '/Events/ResourceThumbnail?resourceGuid=' + result[i].ResourceGuid,
                                    dataType: 'text',
                                    success: function (url) {
                                        var photoid = $('#' + this.ResourceGuid)
                                        if (photoid.length == 0) {
                                            $('.gallery ul').append($('<li><a class="ui-link" data-rel="dialog" data-transition="pop" href="/' + this.ResourceGuid + '"><img id="' + this.ResourceGuid + '" class="lazyload ui-shadow" alt="image" src="' + url + '"></a></li>').hide().fadeIn(2000));

                                            $('html, body').animate({
                                                scrollTop: $('#' + this.ResourceGuid).offset().top
                                            }, 2000);

                                        }
                                    },
                                    error: function (result) {
                                        //popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.');
                                        abortTimer();
                                    }
                                });
                            }
                        }
                    },
                    error: function (result) {
                        //popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.');
                        abortTimer();
                    }
                });
            }

            function abortTimer() { // to be called when you want to stop the timer 
                clearInterval(tid);
            }

        });

        $('#page-Login').live('pageinit', function (event) {
            currentPage = this;

            $(':input').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            });
            $('#Username').focus();
        });

        $('#page-Register').live('pageinit', function (event) {
            currentPage = this;
            $(':input').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            });
            $('#FirstName').focus();
            $('#Email').blur(function () {
                if ($('#Username').val() == '') {
                    $('#Username').val($('#Email').val());
                    $('#Password').focus();
                }
            });

        });

        $('#page-Home').live('pageinit', function (event) {
            currentPage = this;

            // set interval 
            var tid = setInterval(refreshHotSpotThumbnail, 10000);

            function refreshHotSpotThumbnail() {
                $('.hotSpotContainer').each(function (i) {
                    var eventId = $(this).data('eventid');

                    $.ajax({
                        type: 'GET',
                        global: false,
                        async: true,
                        context: $(this),
                        url: '/Home/RefresHotSpot?eventid=' + eventId,
                        dataType: 'json',
                        success: function (result) {
                            if (result != null) {

                                for (var i = 1; i < 5; i++) {
                                    var hotSpotContainer = this.find('.hotSpotPreview').find('.HotSpot' + i + 'Url');
                                    var hotSpot = this.find('.hotSpotPreview').find('.HotSpot' + i + 'Url >img');
                                    var updatedHotSpot = $('<img  src="' + eval('result.HotSpot' + i + 'Url') + '" alt="Hot Spot ' + i + '" />');
                                    updatedHotSpot.hide().appendTo(hotSpotContainer).delay(1500).fadeIn(2000);
                                    hotSpot.fadeOut(2000, function () {
                                        $(this).remove();
                                    })
                                }

                                $('#hotspotMainUrl').attr('href', result.HotSpotMainUrl);

                            }
                        },
                        error: function (result) {
                            $.mobile.hidePageLoadingMsg();
                        }
                    });

                });
            }

        });
        $('#page-ordersummary').live('pageinit', function (event) {
            currentPage = this;

            $('.startCheckout').live('tap', function (event) {
                $('#startCheckout').submit();
            });
        });

        $('#page-mycaptrakey').live('pageinit', function (event) {
            currentPage = this;
            $('#tapToCheckout').hide();

        });

        $('#page-EventEdit').live('pageinit', function (event) {
            currentPage = this;
            $(':input').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            });


            $('#tapToCheckout').hide();

            $('.deleteEvent').live('tap', function () {
                var eventId = this.id.split('_')[1];
                if (confirm("Are you sure you  would like to Delete this Event and all the photos contained in it?")) {
                    window.location = '/Events/DeleteEvent/' + eventId;
                }
            });

        });

        $('#page-EventEdit').live('pageshow', function (event) {
            var message = $('#page-message').text();
            if (message != '')
                popMessage(message);

        });

        $('#page-ShippingAddress').live('pageinit', function (event) {
            currentPage = this;
            $(':input[type="text"]').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            });


            $('#btnContinue1').live('click', function () {
                var addressId = $('#selectShippingAddress').val();
                if (addressId != '') {
                    window.location = '/Checkout/SelectShippingAddress?addressId=' + addressId
                    return;
                }

                $('#shipAddress-Step1').hide();
                $('#shipAddress-Step2').show();
            });

            $('#NewAddress_Email').focus();
            $('#selectShippingAddress').change(function () {
                var addressId = $(this).val();
                window.location = '/Checkout/SelectShippingAddress?addressId=' + addressId
            });

            $('#NewAddress_Email').blur(function () {
                var email = $(this).val();

                if ((email != '') && (isValidEmailAddress(email))) {

                    $(this).removeClass('ui-error');
                    $.mobile.showPageLoadingMsg();
                    $.ajax({
                        cache: false,
                        type: "GET",
                        url: '/Customer/CheckEmailAddress',
                        data: "emailAddress=" + email,
                        success: function (data) {
                            $.mobile.hidePageLoadingMsg();
                            if (data.alreadyExist) {
                                $('#name-info').hide();
                                $('#Email').val(email);
                                $('#login-container').show();
                                $('#password').focus();
                                $("#login").click(function () {
                                    var post = "isJson=true";
                                    var form_data = $('#login-container form').serialize() + "&" + post;

                                    $.post($('#login-container form').attr('action'), form_data, function (data) {
                                        if (data) {
                                            if (data.error) {
                                                alert(data.errorMessage);
                                                return;
                                            }
                                        }
                                    });
                                });
                            } else {
                                $('#login-container').hide();
                                $('#name-info').show();
                                $('#NewAddress_FirstName').focus();

                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            $.mobile.hidePageLoadingMsg();
                            alert('Failed to check email address.');
                        }
                    });
                } else {
                    $(this).addClass('ui-error');
                }
            });


        });
        $('#page-BillingAddress').live('pageinit', function (event) {
            currentPage = this;
            $(':input').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);

                $('#btnContinue1').live('click', function () {

                    var addressId = $('#selectBillingAddress').val();
                    if (addressId != '') {
                        window.location = '/Checkout/SelectBillingAddress?addressId=' + addressId
                        return;
                    }

                    $('#billAddress-Step1').hide();
                    $('#billAddress-Step2').show();
                });
            });
            //$.mobile.page.prototype.options.backBtnText = "Order Summary";

            $('#selectBillingAddress').change(function () {
                var addressId = $(this).val();

                window.location = '/Checkout/SelectBillingAddress?addressId=' + addressId
            });
        });

        $('#page-PaymentInfo').live('pageinit', function (event) {
            currentPage = this;
            $(':input').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            });
        });

        $('#page-MerchantManager').live('pageinit', function () {
            currentPage = this;
            $('#btnAddKeyTags').click(function () {
                var orderQty = $('input[name=addKeyTags]:checked').val();
                if (orderQty != null) {
                    if (confirm('Are you sure you want to add ' + orderQty + ' Captra Key Tags?')) {
                        popMessage('Adding Captra Keys. This may take a moment. Please wait...');
                        $.mobile.showPageLoadingMsg();
                        $.ajax({
                            type: 'GET',
                            global: false,
                            async: true,
                            url: '/DigitalKeyTag/Order?qty=' + orderQty,
                            success: function (result) {
                                $.mobile.hidePageLoadingMsg();
                                if (result.error)
                                    popErrorMessage('Oops. Our bad. Something went wrong. Please try again.' + result.message);
                                else {
                                    popMessage('Successfully added ' + orderQty + ' Captra Key Tags');
                                    document.location = '/DigitalKeyTag/Manager'
                                }
                            },
                            error: function (result) {
                                $.mobile.hidePageLoadingMsg();
                                popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.' + result.message);
                            }
                        });
                    }
                } else {
                    popErrorMessage('Please select a quantity');
                }
            })
        });

        $('#page-cartEditor').live('pageinit', function (event) {
            if ($('#ProductVariantId').val() <= 0) {
                $('#Quantity').parents('.ui-select').hide();
                $('#updatecart').parents('.ui-btn').hide();
                $('#finalPrice').hide();
            }

            $('#ProductVariantId').change(function () {
                if ($('#ProductVariantId').val() <= 0) {
                    $('#Quantity').parents('.ui-select').hide();
                    $('#updatecart').parents('.ui-btn').hide();
                    $('#finalPrice').hide();
                } else {
                    $('#Quantity').parents('.ui-select').show();
                    $('#updatecart').parents('.ui-btn').show();
                    $('#finalPrice').show();
                    updateCart();
                }
            });
            $('#Quantity').change(function () { updateCart(); });

            $.mobile.hidePageLoadingMsg();
        });

        $('#page-cartEditor').live('pageshow', function (event) {
            updateCart();
        });
        function updateCart() {
            var productVariantId = $('#ProductVariantId').val();
            if (productVariantId > 0) {
                var qty = $('#Quantity').val();
                var resourceGuid = $('#DigitalResourceGuid').val();
                var cartItemId = $('#CartItemid').val();

                $.ajax({
                    type: 'GET',
                    global: false,
                    async: true,
                    url: '/ShoppingCart/GetFinalPrice',
                    dataType: 'json',
                    data: { productVariantId: productVariantId, qty: qty, resourceGuid: resourceGuid, cartItemId: cartItemId
                    },
                    success: function (result) {
                        $('#finalPrice').text(result.price);
                    },
                    error: function (result) {
                        //jsonFail(result);
                        //popErrorMessage('Oops. Our bad. Something went wrong. Please try again later.');
                    }
                });
            }
        }
        $('#page-mobileCart').live('pageinit', function (event) {
            currentPage = $(this);
            var selectField = document.getElementById('discountcouponcode');
            if (selectField != null) {
                selectField.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                selectField.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            }

            $('.discountCodeLink').click(function () {
                $('#discountBox').toggle();
            });

            $('#discountBox').hide();

        });

        $('#page-mobileCart').live('pageshow', function (event) {
            $('#discountBox').hide();
            ResizePageContentHeight($(".ui-page"));
        });

        $('#page-PasswordRecovery, #page-PasswordRecoveryConfirm').live('pageinit', function (event) {
            currentPage = this;
            $(':input').each(function (index) {
                this.addEventListener('touchstart' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
                this.addEventListener('mousedown' /*'mousedown'*/, function (e) {
                    e.stopPropagation();
                }, false);
            });
        });

        $('.cartItemButton:not(.cartItemDelete)').live('click', function () {
            cartItemId = $(this).parent().attr('id').split('_')[1];
            $.mobile.showPageLoadingMsg();
            GetCartItemEditor(cartItemId, null);

        });

        $('.cartItemDelete').live('click', function () {
            $($(this).parent()).fadeOut('fast', function () {
                $(this).siblings('.deleteCartItem').fadeIn('fast', function () {
                    $(this).children().show();
                });
            });

        });
        $('.cartItem').live('swipe', function () {
            $(this).fadeOut('fast', function () {
                $(this).siblings('.deleteCartItem').fadeIn('fast', function () {
                    $(this).children().show();
                });
            });
        });

        $('.cancelItemDelete').live('click', function () {
            $(this).parent().fadeOut('fast', function () {
                $(this).parent().siblings('.cartItem').fadeIn('fast');
            });
        });




    });

    function showCoords(c) {
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#x2').val(c.x2);
        $('#y2').val(c.y2);
        $('#w').val(c.w);
        $('#h').val(c.h);
    };

    

