﻿$(document).ready(function () {

    // Google Mapping Objects
    if ($("#map_canvas").length > 0) {
        var _latlng = new google.maps.LatLng(-34.397, 150.644);
        var _option = { zoom: 8, center: _latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
        var _geocoder = new google.maps.Geocoder();
        var _map = new google.maps.Map(document.getElementById("map_canvas"), _option);
        var _marker = new google.maps.Marker({ map: _map, position: _latlng });

        // Added for static maps
        if ($('#map_canvas').attr('rel')) {
            LoadMap($('#map_canvas').attr('rel'));
        }
    }

    $('a.qrClick').click(function () {
        //Fetch QRCode
        //alert(window.location.protocol + '//' + window.location.hostname);
        $('#imgQrCode').attr({ 'src': 'http://chart.apis.google.com/chart?cht=qr&chs=250x250&chl=http://globalmarketplaceinc.com/QRCoupon.aspx/' + $(this).attr('rel') });

        //Fade in the Popup and add close button
        $('#qrCode').fadeIn().css({ 'width': '250px' }).prepend('<a href="#" class="close"><img src="/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" border="0" /></a>');

        //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accommodate for the padding + border width defined in the css
        var popMargTop = ($('#qrCode').height() + 80) / 2;
        var popMargLeft = ($('#qrCode').width() + 80) / 2;

        //Apply Margin to Popup
        $('#qrCode').css({
            'margin-top': -popMargTop,
            'margin-left': -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer 

        return false;
    });

    $('.popcontact').click(function () {
        var _businessId = $(this).attr('rel'); // Snag company email

        // Render Info
        $.post('/Services/GetGiftCertificateDetails.ashx', { func: 'Contact', couponId: _businessId }, function (response) {

            $('#popcontact').html(response);

            //Fade in the Popup and add close button
            $('#popcontact').fadeIn().prepend('<a href="#" class="close"><img src="/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" border="0" /></a>');

            //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accommodate for the padding + border width defined in the css
            var popMargTop = ($('#popcontact').height() + 80) / 2;
            var popMargLeft = ($('#popcontact').width() + 80) / 2;

            //Apply Margin to Popup
            $('#popcontact').css({
                'margin-top': -popMargTop,
                'margin-left': -popMargLeft
            });

            //Fade in Background
            $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
            $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer

        });
        return false;
    });

    $('.business-images #business-thumbs').find('img').each(function () {

        var _src = $(this).attr('src');
        var _busImg = $(this).parent().prevAll('#business-image:first');

        $(this).click(function () {
            _busImg.attr('src', _src);
            //galClickWrapper();
        });
    });

    function galClickWrapper() {
        $('#business-image').click(function () {

            var _src = $(this).attr('src');

            $(this).click(function () {

                //Fade in Background
                $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
                $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer 

                var _busDiv = $('#business-images'); // Handle for bdiv
                var _busImg = _busDiv.find('img[src*="' + _src + '"]'); // Handle for bimg

                // Toggle Showing
                _busDiv.find('img[src!="' + _src + '"]').each(function () { $(this).hide(); });
                _busImg.show();

                _busDiv.css({
                    height: 'auto',
                    width: 'auto'
                });

                //Fade in the Popup and add close button
                _busDiv.fadeIn().prepend('<a href="#" class="close"><img src="/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" border="0" /></a>');

                //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accommodate for the padding + border width defined in the css
                var popMargTop = (_busDiv.height() / 2);
                var popMargLeft = (_busDiv.width() / 2);

                //Apply Margin to Popup
                _busDiv.css({
                    'margin-top': -popMargTop,
                    'margin-left': -popMargLeft
                });

                //Fade in Background
                //$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
                //$('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer 

                return false;
            });
        });
    } //galClickWrapper();

    // Utilized to create modal popup for login and registration
    $('a.poplight[href^=#]').click(function () {
        var popID = $(this).attr('rel'); //Get Popup Name
        var popURL = $(this).attr('href'); //Get Popup href to define size

        //Pull Query & Variables from href URL
        var query = popURL.split('?');
        if (query[1] != null) {

            var dim = query[1].split('&')[0];
            var popWidth = dim.split('=')[1]; //Gets the first query string value

            if ((query[1].split('&')[1] != null) && (query[1].split('&')[1].split('=')[1] != null)) {
                var map = query[1].split('&')[1].split('=')[1];
                LoadMap(map);
            }
        }

        //Fade in the Popup and add close button
        $('#' + popID).fadeIn().css({ 'width': Number(popWidth) }).prepend('<a href="#" class="close"><img src="/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" border="0" /></a>');

        //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accommodate for the padding + border width defined in the css
        var popMargTop = ($('#' + popID).height() + 80) / 2;
        var popMargLeft = ($('#' + popID).width() + 80) / 2;

        //Apply Margin to Popup
        $('#' + popID).css({
            'margin-top': -popMargTop,
            'margin-left': -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer 

        return false;
    });


    //Close Popups and Fade Layer
    $('a.close, #fade').live('click', function () { //When clicking on the close or fade layer...

        $('#fade , .popup_block').fadeOut(function () {
            $('#fade, a.close').remove();
        }); //fade them both out

        //$('#map_canvas').children().remove(); // To be thorough

        return false;
    });

    // Default to General information on load
    $('.main-info').show();

    // Exposes div for advertiser registration
    $('#advertise').click(function () {
        if ($('.div-notify').is(':visible')) {
            $('.div-notify').fadeOut('slow', function () {
                $('.div-advertise').fadeIn();
            });
        }
        else {
            $('.div-advertise').slideToggle('slow');
        }
    });

    // Exposes div for notifications
    $('#notify').click(function () {
        if ($('.div-advertise').is(':visible')) {
            $('.div-advertise').fadeOut('slow', function () {
                $('.div-notify').fadeIn();
            });
        }
        else {
            $('.div-notify').slideToggle('slow');
        }
    });

    // ===== Coupon Gallery Functions ====== PUBLIC PORTION OF WEBSITE ======
    // Checks for saved cookies and loads information to screen
    // Happens on the navigation click
    if ($('.shoppinglist').length != 0) {
        $.post('/Services/SaveCoupons.ashx', { func: 'LoadCoupons' }, function (response) {
            if ((response.length > 0) && (response != null)) {
                var _clean = response.replace(/{/g, '').replace(/}/g, '').replace(/"/g, '');
                var _parts = _clean.split('|');

                // Count
                if (_parts[1].length > 0) {
                    var _value = _parts[1].split(':');
                    $('.shoppinglist').html('Saved Coupons: ' + _value[1] + ' items');
                }

                if (_parts[0].length > 0) {
                    // Toggle Buttons
                    var _troggle = _parts[0].split(':')[1].split(',');
                    $('.addtolist').each(function () {
                        var _btn = $(this);
                        // Compare to all listed
                        for (var t = 0; t < _troggle.length; t++) {
                            if (_troggle[t] == _btn.attr('rel')) {
                                _btn.attr({ src: '/images/added-to-list.png' });
                            }
                        }
                    });
                }
            }
        });
    }

    function addtolistClick() {
        $('.addtolist').each(function () {

            var _this = $(this);
            $(_this).attr({ src: '/images/add-to-list.png' }).css('cursor', 'pointer');
            //setTimeout(function () { $(_this).attr({ cursor: 'pointer' }); }, 250); // Set Pointer Cursor (for dynamics!)

            $(this).click(function () {

                $(this).attr({ src: '/images/loading.gif' }).css('cursor', 'default'); // Progress Indicator

                var _couponId = $(this).attr('rel');

                $.post('/Services/SaveCoupons.ashx', { func: 'Save', couponId: _couponId }, function (response) {

                    var _clean = response.replace(/{/g, '').replace(/}/g, '').replace(/"/g, '');
                    var _parts = _clean.split('|');

                    var _value = _parts[1].split(':');
                    $('.shoppinglist').html('Saved Coupons: ' + _value[1] + ' items');

                    var _isNew = _parts[2].split(':')[1];

                    //$('.addtolist').each(function () {
                    setTimeout(function () {

                        if (_isNew == 1) $(_this).attr({ src: '/images/added-to-list.png' }).css('cursor', 'pointer');

                        else $(_this).attr({ src: '/images/add-to-list.png' }).css('cursor', 'pointer');

                    }, 500);
                    //});
                });

            });
        });
    }

    addtolistClick();

    $('.clear-cookie').click(function () {
        $.post('/Services/SaveCoupons.ashx', { func: 'Clear' }, function (response) {
            if (response != null) {
                var _clean = response.replace(/{/g, '').replace(/}/g, '').replace(/"/g, '');
                var _value = _clean.split(':');
                $('.shoppinglist').html('');

                addtolistClick();
            }
        });
    });

    $('.view-cookie').click(function () {
        $.post('/Services/SaveCoupons.ashx', { func: 'View', couponId: _couponId }, function (response) {
            if (response != null) {
                var _clean = response.replace(/{/g, '').replace(/}/g, '').replace(/"/g, '');
                var _parts = _clean.split('|');
                var _value = _parts[1].split(':');
                $('.shoppinglist').html('Saved Coupons: ' + _value[1] + ' items');

            }
        });
    });

    // Load Map Function
    function LoadMap(_address) {

        if (_address.length > 0) {

            _geocoder.geocode({ 'address': _address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    _option = { zoom: 12, center: results[0].geometry.location, mapTypeId: google.maps.MapTypeId.ROADMAP }; // recenter this way works best

                    // Must reset map obj
                    //_map = null; delete _map; $('#map_canvas').children().remove();
                    _map = new google.maps.Map(document.getElementById("map_canvas"), _option);

                    _marker = new google.maps.Marker({ map: _map, position: results[0].geometry.location });
                }
                else {
                    // TODO: Handle Geocoding Error
                    $('#map_canvas').children().remove();
                    $('#map_canvas').html('<span style="display: block; text-align: center; margin: 232px 0px; color: red; font-size: 18px;">Error looking up address.</span>');
                }
            });

        }
    }

    // ===== Gift Certificate Functions ======

    // Takes User to Purchase
    function _imgBuyBtn() {
        $('.imgBuyBtn').each(function () {

            $(this).click(function () {

                // Get Form Values
                var _name = $(this).attr('id');
                var _rate = $("input[name='rate-" + _name + "']:checked").val();
                var _amnt = $("input[name='amnt-" + _name + "']").val();

                if (_rate != undefined && _amnt.length > 0 && _name.length > 0) {
                    //_line += _certificate + "=" + _rate + "x" + _amount;
                    var _data = $(this).attr('rel') + '=' + _rate + 'x' + _amnt;
                    // Post Request
                    $.post('/Checkout.aspx', { type: 'giftcertificate', data: _data }, function () {
                        window.location = '/Checkout.aspx';
                        //alert("Added to Basket");
                    });
                }
                else {
                    alert("Please Finish Selection. Pick an amount and specify a quantity.");
                }
            });
        });
    } // A Hook Wrapper for the Buy Button
    _imgBuyBtn();

    // Shows popup with more Gift Certificate Information
    $('.imgMoreBtn').each(function () {
        $(this).click(function () {

            var couponId = $(this).attr('rel');

            // Send Request for GiftCertificate
            $.post('/Services/GetGiftCertificateDetails.ashx', { func: 'Lookup', couponId: couponId }, function (response) {

                $('#popcertificate').html(response);

                //Fade in the Popup and add close button
                $('#popcertificate').fadeIn().prepend('<a href="#" class="close"><img src="/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" border="0" /></a>');

                //Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accommodate for the padding + border width defined in the css
                var popMargTop = ($('#popcertificate').height() + 80) / 2;
                var popMargLeft = ($('#popcertificate').width() + 80) / 2;

                //Apply Margin to Popup
                $('#popcertificate').css({
                    'margin-top': -popMargTop,
                    'margin-left': -popMargLeft
                });

                //Fade in Background
                $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
                $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer

                // Hook up handles
                _imgBuyBtn();
                hookRemainingGC();
            });

            return false;
        });
    });

    // ===== Hookups for Remaining GC =====

    //var _rate = $("input[name='rate-" + _name + "']:checked").val();
    //var _amnt = $("input[name='amnt-" + _name + "']").val();

    function hookRemainingGC() {
        $('.radCertificateValue').each(function () {

            $(this).click(function () {
                updateSelection($(this));
            });

        });

        $('.txtCertificateAmnt').each(function () {

            $(this).keyup(function () {

                updateSelection($(this));

            });

        });
    } hookRemainingGC();

    function updateSelection(_this) {

        var bkdwn = $(_this).attr('name').split('-');
        var _id = bkdwn[1];
        // Validate input
        var _input = $("input[name='amnt-" + _id + ((bkdwn.length > 2) ? "-pop" : "") + "']").val();

        if (!isNaN(parseInt(_input))) {

            var _rad = parseInt($("input[name='rate-" + _id + ((bkdwn.length > 2) ? "-pop" : "") + "']:checked").attr('id')); // Set by db
            // Compute total
            $('#rem-' + _id + ((bkdwn.length > 2) ? "-pop" : "")).html(newTotal(parseInt($('#oldrem-' + _id + ((bkdwn.length > 2) ? "-pop" : "")).val()), _rad, parseInt(_input)));
            // If too much...
        }
    }

    function newTotal(start, radio, input) {
        var _total = start - input;
        return (_total > 0) ? _total : "Currently Sold Out";
    }

    // ===== End Gift Certificate Functions =====

});

