-/// <reference path="/scripts/jquery-1.2.6.min.js" />

$(document).ready(function() {
    //homeFeaturePanel();
    //primaryNav();
    chkGiftwrap();
    GiftWrapTextArea();
    deliverycharge();
    slideshow();
    calendar();

    var zIndexNumber = 1000;
    $('div.DateLabel').each(function() {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });

    formElementDefaultText();
    searchResultsList();
    hookUpOrderByDropDown();
    brandList();
    categoryList();
    //promotionsList();
    inputFieldMasks();
    productImageGallery();

    hookUpTermsCondition();
    enableCheckoutAjax();
    ChangeMainImageOnVariationSelected();
    //productImageLink($("#productImage").css("backgroundImage"));
    productImageLink();

});

function chkGiftwrap() {
    $('input.chkGiftwrap').click(function() {
        $('input.updateButton').trigger('click');
    });
}

function GiftWrapTextArea() {
    $('textarea.txtGiftWrapMessage').attr('maxlength', '200');
    $('textarea.txtGiftWrapMessage[maxlength]').keyup(function() {
        var max = parseInt($(this).attr('maxlength'));
        if ($(this).val().length > max) {
            $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        }
        $(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining of 200');
    });
}

function deliverycharge() {
    $('.rdoDeliveryCharge').click(function() {
        $.post("/AjaxCallBacks/DeliveryCharge.aspx", { DeliveryCharge: $(this).val() }, function(url) {
            window.location = url;
            return true;

        });
    });
}

function slideshow() {
    $('.slideshow').after('<div id="nav" class="nav">').cycle({
        fx: 'fade',
        speed: 3000,
        timeout: 5000,
        next: '.slideshow',
        pager: '#nav'
    });
    $('a.sliderlink').click(function() {
        window.location = $(this).attr("href");
    });
}

function calendar() {
    var defaultReminderID = 1427;
    var JSONevents;
    var events = new Array(); //var events = []; //
    if ($('#CalendarEdit').length > 0) {
        var options = {
            navLinks: {
                enableToday: false,
                enableNextYear: false,
                enablePrevYear: false,
                p: '&lsaquo;',
                n: '&rsaquo;',
                t: 'Today',
                showMore: ''
            },
            onMonthChanged: function(dateIn) {

                var events2 = new Array();
                getAllEvents(events2);
                events = events2;
                refreshPopup();
                return true;
            },
            onEventLinkClick: function(event) { return false; },
            onEventBlockClick: function(event) { return false; },
            onEventBlockOver: function(event) { return true; },
            onEventBlockOut: function(event) { return true; },
            onDayLinkClick: function(date) {
                if ($(this).parent("td").hasClass("Inactive"))
                    return false;
                else
                    return true;
            },
            onDayCellClick: function(date) {
                if ($(this).hasClass("Inactive"))
                    return false;
                var d = new Date($(this).attr("date"));
                $("#seledteddate").val(d.toDateString());  //d.toDateString();
                $('td.Selected').removeClass("Selected");
                $(this).toggleClass("Selected");
                $("#Name").val('');
                $("#Event").val(0);
                $("#Gender").val(0);
                $("#AgeRange").val(0);
                $("#PriceRange").val(0);
                $("#ReminderType").val(defaultReminderID);
                $('#chkRecursiveLabel').html('Recurring');
                $('#chkRecursive').attr('checked', false);
                $('#chkRecursive, #chkRecursiveLabel').show();
                $('#btnUpdateCalendar, #btnDeleteCalendar').hide();
                $('#btnAddCalendar').show();

                $('a.popevent').click(function() {
                    for (var i = 0; i < events.length; i++) {
                        if ($(this).attr('id') == 'ev' + events[i].EventID) {
                            $("#Name").val(events[i].Name);
                            $("#Event").val(events[i].EventNodeId);
                            $("#Gender").val(events[i].GenderNodeId);
                            $("#AgeRange").val(events[i].AgeNodeId);
                            $("#PriceRange").val(events[i].PriceRangeNodeId);
                            $("#ReminderType").val(defaultReminderID);
                        }
                    }
                    $('#btnUpdateCalendar, #btnDeleteCalendar').show();
                    $('#btnAddCalendar').hide();
                    $('#chkRecursiveLabel').html('Apply to all recurring');
                    $('#chkRecursive').attr('checked', false);
                    return false;
                });

                if ($(this).hasClass('anEvent')) { $("#EventId").val($(this).attr("id")); }

                return false;
            },
            onDayCellDblClick: function(dateIn) { return true; },
            onEventDropped: function(event, newDate) { return true; },
            onShowMoreClick: function(eventArray) { return true; },

            locale: {
                days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
                daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
                months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                weekMin: 'wk'
            }
        };

        getAllEvents(events);

        $.jMonthCalendar.Initialize(options, events);

        $('#chkRecursiveLabel').html('Recurring');
        $('#chkRecursive').attr('checked', false);
        $('#btnUpdateCalendar, #btnDeleteCalendar').hide();

        $('#btnUpdateCalendar').click(function() {
            var CustomerIdval = $("#CustomerId").val();
            var EventIdval = $("#EventId").val();
            var Nameval = $("#Name").val();
            var Dateval = $("#seledteddate").val();
            var EventNodeId = $("#Event").val();
            var GenderNodeId = $("#Gender").val();
            var AgeRangeNodeId = $("#AgeRange").val();
            var PriceRangeNodeId = $("#PriceRange").val();
            var Recursiveval = $("#chkRecursive").is(":checked");
            var ReminderTypeNodeId = defaultReminderID; //$("#ReminderType").val();
            $.post("/AjaxCallBacks/MyCalendarCallBackUpdate.aspx", {
                CustomerId: CustomerIdval,
                EventId: EventIdval,
                Name: Nameval,
                Date: Dateval,
                Event: EventNodeId,
                Gender: GenderNodeId,
                AgeRange: AgeRangeNodeId,
                PriceRange: PriceRangeNodeId,
                Recursive: Recursiveval,
                ReminderType: ReminderTypeNodeId
            }, function(EventIdval) {
                var events2 = new Array();
                getAllEvents(events2);
                $.jMonthCalendar.Initialize(options, events2);
                events = events2;
                refreshPopup();
                //alert(EventIdval);
                return true;
            });
            return false;
        });

        $('#btnDeleteCalendar').click(function() {
            var EventIdval = $("#EventId").val();
            var Recursiveval = $("#chkRecursive").is(":checked");
            $.post("/AjaxCallBacks/MyCalendarCallBackDelete.aspx", { eid: EventIdval, Recursive: Recursiveval }, function(data) {

                if (data > 0) {
                    window.location = "/myaccount/mycalendar.aspx";
                    return false;
                }
            });

            return false;
        });



        $('#btnAddCalendar').click(function() {

            var CustomerIdval = $("#CustomerId").val();
            var Nameval = $("#Name").val();
            var Dateval = $("#seledteddate").val();
            var EventNodeId = $("#Event").val();
            var GenderNodeId = $("#Gender").val();
            var AgeRangeNodeId = $("#AgeRange").val();
            var PriceRangeNodeId = $("#PriceRange").val();
            var Recursiveval = $("#chkRecursive").is(":checked");
            var ReminderTypeNodeId = defaultReminderID; // $("#ReminderType").val();
            if ((Nameval.length > 0) && (EventNodeId > 0) && (GenderNodeId > 0) && (AgeRangeNodeId > 0) && (PriceRangeNodeId > 0) && (ReminderTypeNodeId > 0)) {
                $.post("/AjaxCallBacks/MyCalendarCallBackInsert.aspx", {
                    CustomerId: CustomerIdval,
                    Name: Nameval,
                    Date: Dateval,
                    Event: EventNodeId,
                    Gender: GenderNodeId,
                    AgeRange: AgeRangeNodeId,
                    PriceRange: PriceRangeNodeId,
                    Recursive: Recursiveval,
                    ReminderType: ReminderTypeNodeId
                }, function(EventIdval) {
                    //if (EventIdval > 0) {
                    var cdate = new Date(Dateval);
                    var aEvents = [{ EventID: EventIdval, "Date": cdate, "Title": cdate.getDate(), URL: "#", "CssClass": "Event"}];
                    $.jMonthCalendar.AddEvents(aEvents);
                    $('#btnUpdateCalendar, #btnDeleteCalendar').show();
                    $('#chkRecursiveLabel').html('Apply to all recurring');
                    $('#chkRecursive').attr('checked', false);
                    $('#btnAddCalendar').hide();
                    var events2 = new Array();
                    getAllEvents(events2);
                    $.jMonthCalendar.Initialize(options, events2);
                    events = events2;
                    refreshPopup();
                    return true;
                    //}
                    //else
                    //    alert('event not added, entry already exist for this date');

                });
            } else {
                alert('Please complete all fields');
                //return false;
            }
            return false;
        });


    }

    refreshPopup();


}

function refreshPopup() {
    $('.DateLabel').each(function() {
        // options
        var distance = 10;
        var time = 250;
        var hideDelay = 500;

        var hideDelayTimer = null;

        // tracker
        var beingShown = false;
        var shown = false;

        var trigger = $('a', this);
        var popup = $('.popup', this).css('opacity', 0);

        // set the mouseover and mouseout on both element
        $([trigger.get(0), popup.get(0)]).mouseover(function() {
            // stops the hide event if we move from the trigger to the popup element
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            // don't trigger the animation again if we're being shown, or already visible
            if (beingShown || shown) {
                return;
            } else {
                beingShown = true;

                // reset position of popup box
                popup.css({
                    top: 0,
                    left: 33,
                    display: 'block' // brings the popup back in to view
                })

                // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
            top: '-=' + distance + 'px',
            opacity: 1
        }, time, 'swing', function() {
            // once the animation is complete, set the tracker variables
            beingShown = false;
            shown = true;
        });
            }
        }).mouseout(function() {
            // reset the timer if we get fired again - avoids double animations
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            // store the timer so that it can be cleared in the mouseover if required
            hideDelayTimer = setTimeout(function() {
                hideDelayTimer = null;
                popup.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function() {
                    // once the animate is complete, set the tracker variables
                    shown = false;
                    // hide the popup entirely after the effect (opacity alone doesn't do the job)
                    popup.css('display', 'none');
                });
            }, hideDelay);
        });
    });
}

function getAllEvents(events) {
    var CustomerIdval = $("#CustomerId").val();

    $.getJSON("/AjaxCallBacks/MyCalendarCallBacks.aspx?cid=" + CustomerIdval,
    function(data) {

        for (var i = 0, len = data.length; i < len; ++i) {
            events[i] = {
                "EventID": data[i].EventId,
                "Name": data[i].Name,
                "StartDateTime": new Date(data[i].startYear, data[i].startMonth - 1, data[i].startDay),
                "Title": data[i].Title,
                "Description": data[i].Description,
                "URL": "#",
                "CssClass": "Events",
                "RecursiveGroupId": data[i].RecursiveGroupId,
                "EventNodeId": data[i].EventNodeId,
                "GenderNodeId": data[i].GenderNodeId,
                "AgeNodeId": data[i].AgeNodeId,
                "PriceRangeNodeId": data[i].PriceRangeNodeId,
                "RecursiveGroupId": data[i].RecursiveGroupId,
                "ReminderNodeId": data[i].ReminderNodeId
            };
        }
        $.jMonthCalendar.ReplaceEventCollection(events);
        $('#statusbar').css({ "background": "none" });
        return true;
    });
}
/*************************************************************/
/******** Ant's stuff ****************************************/
/*************************************************************/

function formElementDefaultText() {
    $('#searchTerms').focus(function() {
        var tempText = $(this).val();
        $(this).val("");
        $(this).blur(function() {
            if ($(this).val() == "") {
                $(this).val(tempText)
            }
        });
    });
}

function promotionsList() {
    var minHeight = parseInt($('.promotionsList > li:first').css("min-height")); // IE only understands min-height on the first element - rock on!!
    var innerListMinHeight = parseInt($('.promotionsListContent').css("min-height"));

    $('.promotionsList > li').each(function() {
        if (Number(minHeight) < Number($(this).height())) {
            $('.promotionsList > li').css("min-height", $(this).height() + "px");
        }
    });

    $('.promotionsListContent').each(function() {
        if (Number(innerListMinHeight) < Number($(this).height())) {
            $('.promotionsListContent').css("min-height", $(this).height() + "px");
        }
    });
}


function searchResultsList() {
    $(".searchResultsList li").mouseover(function() {
        $(this).addClass("current");
    }).mouseout(function() {
        $(this).removeClass("current");
    }).click(function() {
        var url = $(this).children("div").children("h3").children("a").attr("href");
        location.href = url;
    });
}

function brandList() {
    $(".brandList li").mouseover(function() {
        $(this).addClass("current");
    }).mouseout(function() {
        $(this).removeClass("current");
    }).click(function() {
        var url = $(this).children("a").attr("href");
        location.href = url;
    });
}

function categoryList() {
    $(".categoryList li").mouseover(function() {
        $(this).addClass("current");
    }).mouseout(function() {
        $(this).removeClass("current");
    }).click(function() {
        var url = $(this).children("h3").children("a").attr("href");
        location.href = url;
    });
}


/* written in case we need to implement a different version of 2 col lists
function twoColList() {
var minHeight = parseInt($('.list2cols > li:first').css("min-height")); // IE only understands min-height on the first element - rock on!!
$('.list2cols > li').each(function() {
if (Number(minHeight) < Number($(this).height())) {
$('.list2cols > li').css("min-height", $(this).height() + "px");
}
});
}
*/

function homeFeaturePanel() {
    var minHeight = parseInt($('#homeFeature > ul > li:first').css("min-height")); // IE only understands min-height on the first element - rock on!!
    $('#homeFeature > ul > li').each(function() {
        if (Number(minHeight) < Number($(this).height())) {
            $('#homeFeature > ul > li').css("min-height", $(this).height() + "px");
        }
    });
}

function primaryNav() {
    $('#primaryNavigation li').prepend("<div></div>");
    primaryNavMouseOver();
    primaryNavMouseOut();
}

function primaryNavMouseOver() {
    $('#primaryNavigation li a').mouseover(function() {
        var queueNumber = $(this).parent().children("div:first").queue("fx");
        if (!$(this).parent().hasClass("current") && queueNumber < 2) {
            $(this).parent().children("div:first").animate({
                height: "100%"
            }, 200);
        }
        $(this).parent().children("div:first").dequeue();
    });
}

function primaryNavMouseOut() {
    $('#primaryNavigation li a').mouseout(function() {
        if (!$(this).parent().hasClass("current")) {
            var queueNumber = $(this).parent().children("div:first").queue("fx");
            $(this).parent().children("div:first").animate({
                height: "0"
            }, 200);
            $(this).parent().children("div:first").dequeue();
        }
    });
}


/*************************************************************/
/******** Everything else ************************************/
/*************************************************************/
function hookUpTermsCondition() {

    $(".makePaymentForm input[type='checkbox']").click(function() {
        if (this.checked) {
            //alert("i am checked");
            $('.makePaymentForm input[type="submit"]').removeAttr('disabled');
            $('p.tcCheck').removeClass('warning')
        }
        else {
            $('.makePaymentForm input[type="submit"]').attr('disabled', 'disabled');
            $('p.tcCheck').addClass('warning')
        }
    });

}


var processedOrder = false;

function enableCheckoutAjax() {

    if ($('#ByPassEPDQ').text() == '1') {
        if ($('.makePaymentForm').length > 0) {
            $('.makePaymentForm').attr('action', '/bypassepdq.aspx');
            //$('.makePaymentForm input[type="submit"]').removeAttr('disabled');

            $('.makePaymentForm').submit(function() {
                if (!processedOrder) {
                    $(".makePaymentForm input[type='submit']").attr('disabled', 'disabled').val('Processing');
                    $.post("/AjaxCallBacks/CreateBasket.aspx", function(data) {
                        if (data == "Invalid Basket") {
                            window.location = "/checkout/viewbasket.aspx";
                        }
                        else if (data == "Quantities Invalid") {
                            window.location = "/checkout/viewbasket.aspx";
                        }
                        else {
                            $("span.EPQDData").html(data); cons
                            $("input.oid").val(data);
                            processedOrder = true;
                            $('.makePaymentForm').submit();
                        }
                    });

                    return false;
                }
                else {
                    return true;
                }
            });
        }
    }
    else // GOTO Barclays EPDQ payment gateway
    {
        if ($('.makePaymentForm').length > 0) {
            $('.makePaymentForm').attr('action', 'https://secure2.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e');
            //$('.makePaymentForm input[type="submit"]').removeAttr('disabled');

            $('.makePaymentForm').submit(function() {
                if (!processedOrder) {
                    $(".makePaymentForm input[type='submit']").attr('disabled', 'disabled').val('Processing');

                    $.post("/AjaxCallBacks/CreateBasket.aspx", function(data) {
                        if (data == "Invalid Basket") {
                            window.location = "/checkout/viewbasket.aspx";
                        }
                        else if (data == "Quantities Invalid") {
                            window.location = "/checkout/viewbasket.aspx";
                        }
                        else {
                            $("span.EPQDData").html(data);
                            processedOrder = true;
                            $('.makePaymentForm').submit();
                        }
                    });

                    return false;
                }
                else {
                    return true;
                }
            });
        }
    }

}


function hookUpOrderByDropDown() {
    //$('form#orderResultsForm input[@type=submit]').remove();

    $('select#orderResults').change(function() {
        $('form#orderResultsForm').submit();
    });
}

function inputFieldMasks() {
    //$.mask.addPlaceholder('8',"[0-9]");
    //$("input.numeric").mask("8");

    $("input.numeric").bind('keypress', function(e) {
        return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
    });
}

// THIS IS THE Product GALLERY
function productImageGallery() {
    $('#productInformation ul img').each(function() {
        var mainImgSrc = $("#productImage").attr('backgroundImage');

        var currentImgSwitch = $(this).attr("src").replace('_Gallery', '_Detail');
        var currentImgSrc = 'url("' + currentImgSwitch + '")';

        $(this).fadeTo("slow", 0.50);
        $(this).mouseover(function() { $(this).fadeTo("fast", 1.00); });
        $(this).mouseout(function() { $(this).fadeTo("fast", 0.50); });

        $(this).click(function() {

            $("#productImage").queue(function() {
                $(this).css("backgroundImage", currentImgSrc);
                productImageLink(currentImgSrc);
                $("#productImage").dequeue();
            });

            return false;
        });


        if (currentImgSrc == mainImgSrc) {
            $(this).fadeTo("fast", 1);
            $(this).unbind("mouseout");
        }

    });
}

function productImageLink() {
    $('#productInformation ul img').click(function() {
        var currentImgSwitch = $(this).attr("src").replace('_Gallery', '');
        var currentImage = '/productimage.aspx?imageurl=' + currentImgSwitch;
        $('#productImageLink').attr('href', currentImage);
    });
}

/*function productImageLink(imageurl) {

$('#productImageLink').click(function() {
var imageUrl = $(this).attr('href');
var urlFirstPart = imageUrl.substring(0, imageUrl.indexOf("=") + 1);

var fullNewUrl;

if (imageurl.indexOf("\"") > -1) {
fullNewUrl = urlFirstPart + imageurl.substring(imageurl.indexOf("(") + 2, imageurl.indexOf(")") - 1);
}
else {
fullNewUrl = urlFirstPart + imageurl.substring(imageurl.indexOf("(") + 1, imageurl.indexOf(")"));
}

// 7 is the length of '_detail'
fullNewUrl = fullNewUrl.substring(0, fullNewUrl.indexOf("_Detail")) + fullNewUrl.substring(fullNewUrl.indexOf("_Detail") + 7, fullNewUrl.length);


$(this).attr('href', fullNewUrl);
});
}*/

function ChangeMainImageOnVariationSelected() {

    $(".extras input[type=radio]").click(function() {

        var variationCheckId = this.value;

        $.post("/AjaxCallBacks/ProductVariationImage.aspx", { variationId: variationCheckId }, function(data) {

        if (data.length > 0) {
            
                var mainImage = $("#productImage"); //This is used a lot, lets store it in a var
                var imageSRC = data; //Get the current URL that includes the folder ID
                var popUpImageSRC;

                popUpImageSRC = imageSRC.replace("_Detail", "");

                imageSRC = "url('" + imageSRC + "');";

                mainImage.removeAttr("style");
                mainImage.attr("style", "background-image:" + imageSRC + "");

                var currentImage = '/productimage.aspx?imageurl=' + popUpImageSRC;
                $('#productImageLink').attr('href', currentImage);

                return false;
            }

            return false;
        });
    });
}
