/*
 * jQuery Animate From To plugin 1.0
 *
 * Copyright (c) 2011 Emil Stenstrom <http://friendlybit.com>
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	$.fn.animate_from_to = function(targetElm, options){
		return this.each(function(){
			animate_from_to(this, targetElm, options);
		});
	};

	$.extend({
		animate_from_to: animate_from_to
	});

	function animate_from_to(sourceElm, targetElm, options) {
        var source = $(sourceElm).eq(0),
            target = $(targetElm).eq(0);

        var defaults = {
            pixels_per_second: 1000,
            initial_css: {
                "background": "#dddddd",
                "opacity": 0.8,
                "position": "absolute",
                "top": source.offset().top,
                "left": source.offset().left,
                "height": source.height(),
                "width": source.width(),
                "z-index": 100000,
                "image": ""
            },
            square: '',
            callback: function(){ return; }
        }
        if (options && options.initial_css) {
            options.initial_css = $.extend({}, defaults.initial_css, options.initial_css);
        }
        options = $.extend({}, defaults, options);

        var target_height = target.innerHeight(),
            target_width = target.innerWidth();

        if (options.square.toLowerCase() == 'height') {
            target_width = target_height;
        } else if (options.square.toLowerCase() == 'width') {
            target_height = target_width;
        }

        var shadowImage = "";
        if (options.initial_css.image != "") {
            shadowImage = "<img src='" + options.initial_css.image + "' style='width: 100%; height: 100%' />";
        }

        var dy = source.offset().top + source.width()/2 - target.offset().top,
            dx = source.offset().left + source.height()/2 - target.offset().left,
            pixel_distance = Math.floor(Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2))),
            duration = (pixel_distance/options.pixels_per_second)*1000,

            shadow = $('<div>' + shadowImage + '</div>')
                .css(options.initial_css)
                .appendTo('body')
                .animate({
                    top: target.offset().top,
                    left: target.offset().left,
                    height: target_height,
                    width: target_width
                }, {
                    duration: duration
                })
                .animate({
                    opacity: 0
                }, {
                    duration: 100,
                    complete: function(){
                        shadow.remove();
                        return options.callback();
                    }
                });
	}
})(jQuery);

String.prototype.strip = function (strRemoveThis) {
    var strTemp = String(this);
    var re = new RegExp(strRemoveThis, 'gi');
    strTemp = strTemp.replace(re, '');
    return strTemp;
}; 
(function () {
/* cookies */
    app = {};
    app.cookie = {};
    app.cookie.get = function (strCookieName) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i += 1) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g,"");
            if (x === strCookieName) {
                return unescape(y);
            }
        }
    };
    app.cookie.set = function (strCookieName, strCookieValue, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        strCookieValue = escape(strCookieValue) + ((exdays === null) ? "" : "; expires="+exdate.toUTCString()) + "; path=/";
        document.cookie = strCookieName + "=" + strCookieValue;
    };
    app.cookie.remove = function (strCookieName) {
        app.cookie.set(strCookieName,'',-1);
    };
    app.basket = {};
    app.basket.deliverycost = 0;
    app.basket.deliverycostget = function () {
        var strDeliveryData = $('#hiddelta').val();
        if (strDeliveryData) {
            var arrItem, arrDeliveryData="", dblDeliveryCost=0;
            arrDeliveryData = strDeliveryData.split(',');
            for (var i=0; i<arrDeliveryData.length; i++) {
                arrItem = arrDeliveryData[i].toLowerCase().split('|');
                if(arrItem[0].toLowerCase() === app.cookie.get('del', 0).toLowerCase()) {
                    dblDeliveryCost = parseFloat(arrItem[1], 10);
                    break;
                }
            }
        }
        return Number(dblDeliveryCost);
    };
    app.basket.items = 0;
    app.basket.quantity = 0;
    app.basket.total = 0;
    app.basket.labels = function () {
        $('.basket').html("<a href='/basket/'>Basket (" + app.basket.quantity + ")</a>");
        if (app.basket.quantity > 0) {
            $('.subtotal span').html(app.basket.total.toFixed(2));
            $('.delivery span').html(app.basket.deliverycost.toFixed(2));
            $('.total span').html((app.basket.total + app.basket.deliverycost).toFixed(2));
        } else {
            $('#basket').replaceWith('<p>There are no items in your basket.</p>')
        }
    }
    app.basket.delivery = function (dblDeliveryCost) {
        var arrDeliveryData = $('#hiddelta').val();
        arrDeliveryData = arrDeliveryData.split(',')
        var arrItem;
        for (var i=0; i<arrDeliveryData.length; i++) {
            if (arrDeliveryData[i]) {
                arrItem = arrDeliveryData[i].split('|');
                if (parseFloat(arrItem[0], 10) === parseFloat(dblDeliveryCost, 10)) {
                    app.basket.deliverycost = parseFloat(arrItem[1], 10);
                    app.cookie.set('del', arrItem[0]);
                    break;
                }
            }
        }
        app.basket.count();
    };
    app.basket.add = function (id, quantity) {
        var intItems = parseInt(app.cookie.get('items'), 10);
        if (!intItems) { intItems = 0 }
        var intLoop = 0, intItem = (intItems + 1), intID = 0, boolExists = false, intQuantity = 0;
        for (intLoop = 1; intLoop <= intItems; intLoop += 1) {
            intID = parseInt(app.cookie.get('item' + intLoop + 'id'), 10);
            if (intID === id) {
                boolExists = true;
                intItem = intLoop;
            }
        }
        if (boolExists === true) {
            intQuantity = parseInt(app.cookie.get('item' + intItem + 'quantity'), 10);
            app.cookie.set('item' + intItem + 'quantity', intQuantity + quantity, 1);
        } else {
            app.cookie.set('item' + intItem + 'id', id, 1);
            app.cookie.set('item' + intItem + 'quantity', quantity, 1);
            app.cookie.set('items', intItem, 1)
        }
        app.basket.count();
        
        $("#itemadd input[type=submit]").animate_from_to(".basket", {
            callback: function(){ wiggle(150, 10, 0); }
        });
    };
    app.basket.remove = function (id) {
        var intItems = parseInt(app.cookie.get('items'), 10);
        var intLoop = 0, intID = 0;
        app.cookie.set('item' + id + 'quantity', 0, 1);
        $('#basketitem-' + id).remove();
        $('#basketgaptop-' + id).remove();
        $('#basketgapbottom-' + id).remove();
        app.basket.count();
    };
    app.basket.update = function (id, quantity) {
        if (parseInt(quantity, 10) === 0) {
            app.basket.remove(id);
        } else {
            app.cookie.set('item' + id + 'quantity', quantity, 1);
            var dblPrice = parseFloat($('#basketitem-' + id + ' .price b').attr('title'), 10);
            var strValue = (parseInt(quantity, 10) * parseFloat(dblPrice, 10)).toFixed(2);
            $('#basketitem-' + id + ' .price b span').text(strValue);
            app.basket.count();
        }
    };
    app.basket.count = function () {
        var intItems = parseInt(app.cookie.get('items'), 10);
        var intLoop = 0, intCount = 0, intQuantity = 0, intSpecific = 0, dblTotal = 0, dblPrice = 1;
        for (intLoop = 1; intLoop <= intItems; intLoop += 1) {
            intSpecific = parseInt(app.cookie.get('item' + intLoop + 'quantity'), 10);
            intQuantity = intQuantity + intSpecific;
            if (intSpecific > 0) {
                intCount = intCount + 1;
                dblPrice = parseFloat($('#basketitem-' + intLoop + ' .price b').attr('title'), 10);
                if (dblPrice) {
                    dblTotal = dblTotal + (intSpecific * dblPrice);
                }
            }
        }
        app.basket.items = intCount;
        app.basket.quantity = intQuantity;
        
        app.basket.total = dblTotal;
        app.basket.labels();
    };
    
})();
    
if(jQuery)(
	function (jQuery) {
		jQuery.extend(jQuery.fn,{
			hint:function (options) {
				jQuery(this).each(function () {
				var settings = jQuery.extend({
					id              : jQuery(this).attr('id'),
					hint            : '',
					hintClass       : 'inactive'
				}, options);
				var strCurrentValue = jQuery(this).attr('defaultValue');
				if (strCurrentValue === "") {
					jQuery(this).addClass(settings.hintClass);
					if (settings.hint === '')
					{
						settings.hint = jQuery(this).attr('defaultValue');
					} else {
						jQuery(this).val(settings.hint);
						jQuery(this).attr('defaultValue', settings.hint);
					}
					jQuery(this).focus( function ()
					{
						if (jQuery(this).val() === "" || jQuery(this).val() === jQuery(this).attr('defaultValue'))
						{
							jQuery(this).val('').removeClass(settings.hintClass);
						}
					});
					jQuery(this).blur( function ()
					{
						if (jQuery(this).val() === "")
						{
							jQuery(this).val(jQuery(this).attr('defaultValue')).addClass(settings.hintClass);
						}
					});
				}
			});
		}
	});
})(jQuery);

function wiggle(wigSpeed, wigHt, wigCount) {
    var $elem = $('.basket'),wigS=wigSpeed, wigH=wigHt;
    var cl = parseInt($elem.position().left, 10);
    $elem.width(160);
    $elem.animate({
        left: cl + wigH
    }, wigS, function() {
        $elem.animate({
            left: cl
        }, wigS, function() {
            if (wigCount < 3 ) {
                wiggle(wigS, wigH, wigCount + 1);
            }
        });
    });
}
$(document).ready(function () {
    $(function () {
        // Set initial value
        app.basket.deliverycost = app.basket.deliverycostget();
        
        function smoothZoom() {
            $('.zoom').smoothZoom({
                width: 592,
                height: 390,
                button_ICON_IMAGE: '/_images/icons.png',
                button_ALIGN: 'top right',
                button_SIZE: 24
            }).removeClass('zoom');
        }
        if (typeof GoogleMapShow == 'function') {
            GoogleMapShow();
        }

        $('#billboard').royalSlider({
            imageAlignCenter: true,
            hideArrowOnLastSlide: true,
            slideshowEnabled: true,
            controlNavEnabled: false,
            slideshowDelay: 5000
        });
		
		$('#txtsearch').hint( { hint: 'search phrase', hintClass: 'inactive' } );
		$('#txtemail').hint( { hint: 'email address', hintClass: 'inactive' } );
		$('#txtlocation').hint( { hint: 'Town or postcode', hintClass: 'inactive' } );

        $('.product-detail-nav ul li:first').addClass('selected');
        $('.product-detail-nav ul li a').each(function (i) {
            $(this).click(function () {
                var strAction = $(this).attr('id');
                strAction = strAction.replace(/product-/gi, '');
                var id = $(this).parent().parent().attr('id');
                id = id.replace(/product-/gi, '');
                $(this).parent().parent().find('li').removeClass('selected');
                $(this).parent().addClass('selected');
                $.ajax({
                    url: '/_cache/product.' + id + '.detail.' + strAction + '.c1.asp',
                    dataType: 'html',
                    type: 'GET',
                    cache: false,
                    async: true,
                    complete: function (XMLHttpRequest, textStatus) { },
                    success: function (html, textStatus, XMLHttpRequest) {
                        $('#product-detail-content').html(html);
                        setTimeout(smoothZoom, 250);
                    },
                    error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); }
                });
                $.ajax({
                    url: '/_cache/product.' + id + '.detail.' + strAction + '.c2.asp',
                    dataType: 'html',
                    type: 'GET',
                    cache: false,
                    async: true,
                    complete: function (XMLHttpRequest, textStatus) { },
                    success: function (html, textStatus, XMLHttpRequest) {
                        $('#product-detail-support').html(html);
                        if ($('#download-thumbs').length > 0) {
                            (function () {
                                var w = 0;
                                /*
                                $('#product-detail-support ul li').each(function () {
                                    w = w + parseInt($(this).outerWidth(true), 10);
                                });
                                $('#product-detail-support ul').width(w);
                                */
                                w = $('#product-detail-support ul li').length;
                                w = w * 165;
                                w = w + 10;
                                $('#product-detail-support ul').width(w);
                            })();
                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); }
                });
                
                return false;
            });
        });
        $('.stitch').each(function () {
            if ($(this).parent().find('span').length === 0) {
                $(this).after('<span></span>');
            }
        });
        /*
        $('.swatch li a').live('click', function () {
            var id = $(this).parent().attr('id');
            id = id.replace(/colour-/gi, '');
            $('#product-detail-support>img').attr('src', '/_product/_colour/' + id + '.png');
            return false;
        });
        */
        $('#colour-thumbs li a').live('click', function () {
            var intProductID = $('.product-detail-nav>ul').attr('id').strip('product-');
            var id = $(this).parent().attr('id').strip('colour-');

            var strURL = "/_cache/product." + intProductID + ".colour." + id + ".asp"
            $.ajax({
                url: strURL,
                dataType: 'html',
                type: 'POST',
                cache: false,
                async: true,
                complete: function (XMLHttpRequest, textStatus) { },
                success: function (html, textStatus, XMLHttpRequest) {
                    $('#product-detail-support').html(html);
                    smoothZoom();
                },
                error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } 
            });
            return false;
        });
        $('#product-detail-content #gallery-thumbs li a').live('click', function () {
            var intProductID = $('.product-detail-nav>ul').attr('id').strip('product-');
            var id = $(this).parent().attr('id').strip('gallery-');

            var strURL = "/_cache/product." + intProductID + ".gallery." + id + ".asp"
            $.ajax({
                url: strURL,
                dataType: 'html',
                type: 'POST',
                cache: false,
                async: true,
                complete: function (XMLHttpRequest, textStatus) { },
                success: function (html, textStatus, XMLHttpRequest) {
                    $('#product-detail-support').html(html);
                    smoothZoom();
                },
                error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } 
            });
            return false;
        });
		/* Accessory gallery */
        $('.accessory .thumbs #gallery-thumbs li a').live('click', function () {
            var id = $(this).parent().attr('id').strip('gallery-');
            var intProductID = $(this).parents('.accessory').attr('id').strip('accessory-');
            var strURL = "/_cache/product." + intProductID + ".gallery." + id + ".asp"
            $.ajax({
                url: strURL,
                dataType: 'html',
                type: 'POST',
                cache: false,
                async: true,
                complete: function (XMLHttpRequest, textStatus) { },
                success: function (html, textStatus, XMLHttpRequest) {
                    $('#accessory-image').html(html.strip("class='zoom'"));
                    smoothZoom();
                },
                error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } 
            });
            return false;
        });
        
        function showLocator() {
            GoogleMapSpecific('locator');
            GoogleMapCenter(52.14694700614783, -0.41649341583251953, 10);
            GoogleMapType('Map');
            $('form#locations').submit(function () {
                var intProductID = 0;
                if ($('#cmbproductid').length > 0) {
                    intProductID = parseInt($('#cmbproductid').val(), 10);
                } else {
                    if ($('.product-detail-nav ul').length > 0) {
                        intProductID = parseInt($('.product-detail-nav ul').attr('id').strip('product-'), 10);
                    }
                }
                GoogleMapLookup({
                    address: $('#txtlocation').val(),
                    success: function (e) {
                        GoogleMapCenter(e.lat, e.lon, 10);
                        $.ajax({
                            url: '/_api/stores.asp',
                            dataType: 'json',
                            type: 'POST',
                            cache: false,
                            async: true,
                            data: {
                                lat: e.lat,
                                lon: e.lon,
                                productid: intProductID
                            },
                            complete: function (XMLHttpRequest, textStatus) { },
                            success: function (json, textStatus, XMLHttpRequest) {
                                map.clearOverlays();
                                var i = 0;
                                if (json.length > 0 ) {
                                    if ($('.storeresults ul').length === 0) {
                                        $('.storeresults').append("<ul class='stores'></ul>");
                                    } else {
                                        $('.storeresults ul').empty();
                                    }
                                }
                                var strItem = '', strLetter = '';
                                for (i = 0; i < json.length; i += 1) {
                                    strLetter = String.fromCharCode(65 + i)
                                    strItem = '';
                                    strItem = strItem + "<li rel='" + json[i].lat + "," + json[i].lon + "'>";
                                    strItem = strItem + "<span class='letter'>" + strLetter + "</span>";
                                    strItem = strItem + "<span class='title'>" + json[i].title + "</span>";
                                    strItem = strItem + "<span class='address'>" + json[i].address + "</span>";
                                    strItem = strItem + "<span class='phone'>" + json[i].phone + "</span>";
                                    strItem = strItem + "</li>";
                                    $('.storeresults ul').append(strItem);
                                    GoogleMapMarkerX({
                                        lat: json[i].lat,
                                        lon: json[i].lon,
                                        icon: {
                                            image: 'http://www.google.com/mapfiles/marker' + strLetter + '.png',
                                            width: 18,
                                            height: 30
                                        }
                                    });
                                }
                                $('.storeresults ul.stores li').click(function () {
                                    var strLoc = $(this).attr('rel');
                                    var varLoc = strLoc.split(',');
                                    GoogleMapCenter(varLoc[0], varLoc[1], 14);
                                });
                            },
                            error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } 
                        });
                    },
                    error: function (e) {
                        map.clearOverlays();
                        $('.storeresults').empty();
                        alert('No matching locations could be found, please try your search again.');
                    }
                });
                return false;
            });
        }
        if ($('#locator').length > 0) {
            $('#locator').parent().append("<div class='fade'></div>");
            showLocator();
        }
        $('.product-detail-action').click(function () {
            $('.product-detail-nav ul li').removeClass('selected');
            $('#product-detail-support').html("<div id='locator' class='map'></div>");
            var html = '';
            html = html + "<div class='panel' id='panel-short'>";
            html = html + "<h1>Store locator</h1>";
            html = html + "<form name='locations' id='locations' action='/store-locator/' method='post'>";
            html = html + "<input type='text' name='location' id='txtlocation' class='rounded' />";
            html = html + "<input class='go' type='submit' name='submit' id='btnsubmit' value='Search' /><br />";
            html = html + "</form>";
            html = html + "<div class='storeresults'></div>";
            html = html + "</div>";
            $('#product-detail-content').html(html);
            $('#locations').css({
                marginTop: '10px'
            });
            $('#txtlocation').hint( { hint: 'Town or postcode', hintClass: 'inactive' } );
            showLocator();
            $('#locator').parent().append("<div class='fade-short'></div>");
            return false;
        });
        
        $('#itemadd input[type=submit]').click(function () {
            var intID = parseInt($('#hidproductid').val(), 10);
            var intQuantity = parseInt($('#txtquantity').val(), 10);
            app.basket.add(intID, intQuantity);
            return false;
        });
        $('#basket .remove').each(function () {
            $(this).click(function () {
                var intID = $(this).parents('tr').attr('id').strip('basketitem-');
                app.basket.remove(intID);
                return false;
            });
        });
        $('#basket .update').each(function () {
            $(this).click(function () {
                var intID = $(this).parents('tr').attr('id').strip('basketitem-');
                var intQuantity = $('#txtquantity-' + intID).val();
                app.basket.update(intID, intQuantity);
                return false;
            });
        });
        $('#cmbdeliverytype').change(function () {
            app.basket.delivery($(this).find(':selected').val());
        });

        app.basket.count();
        
        $('section.content').prepend("<div class='stitched'></div>");
        $('#blogrecent,#blogcategory,#blogarchive', 'section.side').css({ position: 'relative', backgroundColor: 'transparent' }).prepend("<div class='stitched'></div>");
    });
});

