﻿var map_canvas;
var map;
var marker = null;
var coloursOut = false;
var related = false;
var basketTimeout = 5000;

$(document).ready(function () {
    $('body').click(function () {
        if (coloursOut) {
            coloursOut = false;
            $('#colourListing').css('display', 'none');
        }
    });

    $('.returnThis').click(function () {
        if ($(this).parent().children('.returns').css('display') == 'block')
            $(this).parent().children('.returns').css('display', 'none');
        else
            $(this).parent().children('.returns').css('display', 'block');
        //$(this).attr('checked', 'checked');
    });

    $('.rtnQtyUp').click(function () {
        var max = $(this).parent().parent().parent().parent().parent().children('td.realQty').text();
        var qtyEl = $(this).parent().parent().children('.rtnQty');
        var qty = parseInt($(qtyEl).text());

        if (qty + 1 <= max) {
            $(qtyEl).text(qty + 1);
            $(this).parent().parent().children('.hdnQty').val(qty + 1);
        }

        return false;
    });

    $('.rtnQtyDown').click(function () {
        var qtyEl = $(this).parent().parent().children('.rtnQty');
        var qty = parseInt($(qtyEl).text());

        if (qty - 1 > 0) {
            $(qtyEl).text(qty - 1);
            $(this).parent().parent().children('.hdnQty').val(qty - 1);
        }

        return false;
    });

    if (typeof ($('.rtnBtn').fancybox) == "function") {
        $('.rtnBtn').fancybox({
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'type': 'inline'
        });

        $('.cancelReason').click(function () {
            $(this).parent().children('textarea').val('');
            $.fancybox.close();
            return false;
        });

        $('.saveReason').click(function () {
            $.fancybox.close();
            return false;
        });
    }

    $("#colourSelect").click(function () {
        $('#colourListing').css('display', 'block');
        coloursOut = true;
        return false;
    });

    $('#colourListing li').click(function () {
        var txt = $(this).children('span').text();

        $('.ddlColour option').removeAttr('selected').each(function () {
            if ($(this).text() == txt) {
                $(this).attr('selected', 'selected')
                $(this).trigger('change');
            }
        });

        $('#colourSelect').text(txt);
        $('#colourListing').css('display', 'none');
    });

    $(".autoClear").focus(function () {
        if (!$(this).attr('originalVal')) {
            $(this).attr('originalVal', $(this).val());
            $(this).val('');
        }
    }).blur(function () {
        if ($.trim($(this).val()).length == 0) {
            $(this).val($(this).attr('originalVal'));
            $(this).removeAttr('originalVal');
        }
    });

    if (typeof $(".carousel").children("ul").jcarousel == 'function') {
        $('.carousel').children("ul").each(function () {
            var liCount = $(this).children('li').length;

            if (liCount == 0)
                $(this).parent().parent().remove();
            else {
                if (liCount <= $(this).parent().attr('visibleItems')) {
                    $(this).parent().parent().children('.nextBut').remove();
                    $(this).parent().parent().children('.prevBut').remove();
                    $(this).css({
                        'list-style-type': 'none'
                    });
                    $(this).children('li').css({
                        'float': 'left'
                    });
                }
                else {
                    $(this).jcarousel({
                        wrap: 'circular',
                        scroll: 3,
                        initCallback: mycarousel_initCallback,
                        buttonNextHTML: null,
                        buttonPrevHTML: null,
                        animation: 1000,
                        easing: 'easeInOutCubic'
                    });
                }
            }
        });
    }

    if (typeof $('a.zoomBut').lightbox == 'function') {
        $('a.zoomBut').lightbox();
    }

    $('.visiblePage:last').addClass('last');

    if (typeof $('.zoomMe').jqzoom == 'function') {
        $('.zoomMe').jqzoom({
            zoomWidth: 335,
            zoomHeight: 350,
            zoomType: 'reverse',
            title: false,
            xOffset: 15,
            yOffset: 80
        });
    }

    setupReturns();
    setupForms();
});

function setupForms() {
    $(window).keypress(function (e) {
        if (e.which == 13)
            return false;
        else
            return true;
    });
    $('.form').find('input').keydown(function (e) {
        if (e.which == 13) {
            if ($(this).parents('.form').find('.formEnter')[0].tagName.toLowerCase() == 'a')
                window.location = $(this).parents('.form').find('.formEnter').attr('href')
            $(this).parents('.form').find('.formEnter').trigger('click');
        }
    });
}

function tryAddToBasket(isRelated) {
    var itemID;
    var option;
    var qty;

    if (!isRelated) {
        itemID = $('.productColours').val();
        option = $('.productSize').val();
        qty = $('.productQty').val();
    }
    else {
        itemID = $('.relatedItem').val();
        option = $('.relatedSize').val();
        qty = $('.relatedQty').val();
    }

    if (itemID.length == 0) {
        if (isRelated)
            alert("Please select an item from the related items drop down.")
        else
            alert("Please select a colour from the colours drop down.");
        return false;
    }
    else if (option.length == 0 || option == 'Size') {
        alert("Please select a size from the sizes drop down.");
        return false;
    }
    else if (isNaN(parseInt(qty)) || parseInt(qty) <= 0) {
        alert("Please enter a valid quantity.");
        return false;
    }

    related = isRelated;
    Baskets.AddToBasket(itemID, option, qty, onAddSucceed, onAddFail);
}

function onAddSucceed(msg) {
    if (msg == 'ok') {
        if (!related) {
            var img = $('img[id*=imgCollectionImage]').attr('src');
            img = img.replace('/product/', '/thumbnail/');

            $('#addedToBasket #basketAddedItem').html("<img src='" + img + "' />");
            $('#addedToBasket .itemName').html($('h2').text());
            $('#addedToBasket .size').html($('.productSize').val());
            $('#addedToBasket .qty').html($('.productQty').val());
            $('#addedToBasket .colour').html($('.productColours option:selected').text());
            $('#addedToBasket .cost').html('&pound;' + ($('input[id*=hdnPrice]').val() * $('.productQty').val()).toFixed(2));
        }
        else {
            var img = $('img[id*=relatedImg]').attr('src');

            $('#addedToBasket #basketAddedItem').html("<img src='" + img + "' />");
            $('#addedToBasket .itemName').html($('.relatedItem option:selected').text());
            $('#addedToBasket .size').html($('.relatedSize').val());
            $('#addedToBasket .qty').html($('.relatedQty').val());
            $('#addedToBasket .colour').html($('.productColours option:selected').text());
            $('#addedToBasket .cost').html('&pound;' + ($('input[id*=hdnRelatedPrice]').val() * $('.relatedQty').val()).toFixed(2));
        }
        $.fancybox(
		    '<div class="addedToBasket clearfix" style="display: block;">' + $('#addedToBasket').html() + '</div>',
		    {
		        'autoDimensions': true
		    }
	    );

        setTimeout('$.fancybox.close()', basketTimeout);
    } else {
	if (msg == '0') {
        	alert('Sorry this size is currently out of stock.');
    	} else {
        	alert('Sorry there are only ' + msg + ' left.  Please change your order quantity.');
	}	
    }
}

function onAddFail(msg) {
    alert(msg.get_message());
}

function mycarousel_initCallback(carousel) {
   var container = $(carousel.container).parent().parent();
   $(container).children('.nextBut').bind('click', function() {
        carousel.next();
        return false;
    });

    $(container).children('.prevBut').bind('click', function() {
        carousel.prev();
        return false;
    });
};

function setupMap(map_id, store_id, store_name, lat, lng) {
    var options = {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map_canvas = document.getElementById(map_id);
    map = new google.maps.Map(map_canvas, options);

    setMapLocation(store_id, store_name, lat, lng);
}

function setMapLocation(store_id, store_name, lat, lng) {
	if(marker != null)
		marker.setMap(null);
	
	marker = new google.maps.Marker({
		title       : store_name,
		position    : new google.maps.LatLng(lat, lng)
});

    $('ul.stockistList li').removeClass('selected');
    $('li#' + store_id).addClass('selected');
	
	marker.setMap(map);
	
	var bounds = new google.maps.LatLngBounds();
	
	bounds.extend(marker.getPosition());
	map.fitBounds(bounds);
	google.maps.event.addListener(map, 'bounds_changed', function(event) {
		if (map.getZoom() > 16)
			map.setZoom(16);
		google.maps.event.clearListeners(map, 'bounds_changed');
	});
    map.setCenter(bounds.getCenter());
}

function setupReturns() {
    $('#saveAndPrint, #email').click(function() {
        if ($('.returnThis input:checked').length == 0) {
            alert('Please select at least one item to return.');
            return false;
        }
        var ids = new Array();
        var reasons = new Array();
        var actions = new Array();
        var explanations = new Array();
        var quantities = new Array();
        var url = "/multiprint.aspx?orderNumber=" + $('input[id*=hdnOrderNumber]').val();
        var arg = 'resizable=yes, toolbar=yes,location=no,directories=no,addressbar=no,scrollbars=yes,status=no,menubar=yes,top=10,left=10';

        $('.returnThis input:checked').each(function() {
            var parent = $(this).parent().parent();

            ids.push($(parent).find('input[id*=hdnBasketItemID]').val());
            reasons.push($(parent).find('.rtnReasons').children(':selected').text());
            actions.push($(parent).find('.rtnActions').children(':selected').text());
            explanations.push($(parent).find('.rtnReason').val().replace(/,/g, '[comma]'));
            quantities.push($(parent).find('.rtnQty').text());
        });

        createCookie('ids', ids.toString(), 7);
        createCookie('reasons', reasons.toString(), 7);
        createCookie('actions', actions.toString(), 7);
        createCookie('explanations', explanations.toString(), 7);
        createCookie('quantities', quantities.toString(), 7);

        if ($(this).attr('id') == 'email') {
            url += '&customer=' + $('input[id*=CustomerIDField]').val() + '&email=1';
            arg += ',width=10,height=10';

            if (!confirm('By continuing your returns form will be emailed to your registered email address.'))
                return false;
        }

        window.open(url, "_blank", arg);

        return false;
    });
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
