$.blockUI.defaults.applyPlatformOpacityRules = false;
$.blockUI.defaults.css.border = '1px solid #00000';

$(document).ready(function(){
	// png fix
	$(document).pngFix();
	
	// facebox
    $('a[rel*=facebox]').facebox({
    	loadingImage : '/css/lib/facebox/loading.gif',
        closeImage   : '/css/lib/facebox/closelabel.gif'
    }); 

	// external links
	$('a[rel*=external]').click( function() {
		window.open(this.href);
		return false;
	});
	
	// messages
	$('.message').delay(4000).slideUp();
	
	// placeholder
	$('input[type=text][title!=""]').each(function() {
		if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
		if ($(this).val() == $(this).attr('title')) $(this).addClass('exampleText');
	}).focus(switchText).blur(switchText).focus(disableOthers);

	$('form').submit(function() {
		$(this).find('input[type=text][title!=""]').each(function() {
			if ($(this).val() == $(this).attr('title')) $(this).val('');
		});
	});

    $('form#books_search').find('input').focus(function()
    {
        var form = $('form#books_search');
        $('input', form).addClass('disabled');
        
        if($(this).attr('name') == 'isbn')
            $(this).removeClass('disabled');
        else
            $('input:[name=keyword]', form).removeClass('disabled');
    });


    $('.remove-basket-item').live('click', function()
    {
        $.ajax({
            url: $(this).attr('href'),
            success: function(count)
            {
                changeBasketText(parseInt(count));
                highlightBasket();
                $('#basketItems').load('/basket/items/');
            }
        });
        return false;
    });

    $('button.add-basket-item').click(function()
    {
        var form = $(this).parents('form').eq(0);
        $.ajax({
            url: form.attr('action'),
            data: $.param(form.serializeArray()),
            type: "POST",
            success: function(count)
            {
                if (count > 0)
                {
                    window.scroll(0, 0);
                    changeBasketText(parseInt(count));
                    $('#highlight-basket a').addClass('highlighted');
                    $('#quick-basket-content').load('/basket/quick-info', function()
                    {
                        $(this).show();
                    });
                }
            }
        });
        return false;
    });

    $('form#site-search input[name=sitesection]').click(function()
    {
        $('form#site-search').attr('action', $(this).attr('value'));
    });

    $('input[name=shipping-method]').change(function()
    {
        $('#delivery-costs').text($(this).attr('title'));
        $('#total-costs').html((parseFloat($(this).attr('title'))+parseFloat($('#total-costs-main').text())).toFixed(2));
    });

    $('button.edit-user-shipping').live('click', function()
    {
        $('#user-shipping-details').load('/basket/user-shipping');
        return false;
    });

    $('#OrderShippingForm button').live('click', function()
    {
        var form = $(this).parents('form').eq(0);
        $.ajax({
            url: form.attr('action'),
            data: $.param(form.serializeArray()),
            type: "POST",
            success: function(html)
            {
                $('#user-shipping-details').html(html);
            }
        });
        return false;
    });
    
	$("form span.description").each(function() {
		var help_text = $(this).html();
		var input = $(this).prev();
		
		$(this).html('&nbsp;');
		
		if (help_text.length > 0) {
			input.css('width', '150px');
			input.css('margin-right', '5px');
			$(this).show();

			$(this).qtip({
				content: help_text,
			    position: {
			        corner: {
			            target: 'leftMiddle',
			            tooltip: 'topRight'
			        }
			    },
			    style: {
			        name: 'cream',
			        padding: '7px 13px',
			        width: {
			            max: 210,
			            min: 0
			        },
			        tip: true
			    }
			});
		}
	});
	
	// process coupon code
	$('#coupon_process').click(function(event) {
		var code = $(this).siblings('input').val();
		
		if (code && code.length > 0) {
			$.ajax({
			    url:'/coupons/check?coupon_code=' + code, 
			    success: function(response) {
			    	var data = eval(response);
			    	
			        if (data) {
			        	$.blockUI();
			        	window.location.reload();
			        }
			    }
			});
		}
		
		event.preventDefault();
	})
});

function switchText()
{
	if ($(this).val() == $(this).attr('title'))
		$(this).val('').removeClass('exampleText');
	else if ($.trim($(this).val()) == '')
		$(this).addClass('exampleText').val($(this).attr('title'));
}

function disableOthers()
{
	if (this.id == 'search_isbn') {
		$("#search_keyword").addClass('grey-bg');
		$("#search_postcode").addClass('grey-bg');
		
		$("#search_isbn").removeClass('grey-bg');
	} else {
		$("#search_isbn").addClass('grey-bg');
		
		$("#search_keyword").removeClass('grey-bg');
		$("#search_postcode").removeClass('grey-bg');
	}
}

function addItem(id, type)
{
	var qty = $("#basketItemQty").val(); 
	
	$.ajax({url: "/basket/add?id=" + id + "&qty=" + qty + "&type=" + type, context: document.body, success: function(count) {
		if (count > 0) {
			changeBasketText(parseInt(count));
			highlightBasket();
		}
	}});
}

function changeBasketText(count)
{
	$("#highlight-basket a").html('My basket (' + count + ')');
}

function highlightBasket()
{
	$("#highlight-basket").addClass('highlight-basket').delay(2000).queue(function () {
		$(this).removeClass('highlight-basket');
	});
}
function changeItem(id, type)
{
	var qty = $("#basketQty_" + id).val(); 
	$.ajax({url: "/basket/add?id=" + id + "&qty=" + qty + "&type=" + type, context: document.body, success: function(){
		$('#basketItems').load('/basket/items/', function() {
		});
	}});
}
function changeShippinCosts(totalCosts)
{
	var shppingCosts = new Array("2.99", "4.95", "5.96", "9.96");
	var shippment = $('#billing-info input:radio:checked').val();
	
	$('#delivery-costs').html(shppingCosts[shippment]);
	changeTotalCosts(parseFloat(shppingCosts[shippment]), parseFloat(totalCosts));	
}
function changeTotalCosts(shippingCosts, totalCosts)
{
	total = totalCosts + shippingCosts;
	$('#total-costs').html(total.toFixed(2));
}

// map wrapper 
// using Bing maps API

var map =
{
    points	   : {}
    ,routes    : []
    ,mapviewer : false
    ,cache     : []
    
    ,load: function(routes)
    {
        this.routes = routes;
    }
    ,draw: function(route)
    {
        this.drawMap();
        this.drawPoints(route, this);
    }
    ,drawMap: function()
    {
    	this.mapviewer = new VEMap('mapviewer');
    	this.mapviewer.SetCredentials(MAP_KEY);
    	this.mapviewer.LoadMap(new VELatLong(54.58479674367873, -4.899902343750017));
    	
    	this.getTiles();
    	this.mapviewer.HideMiniMap();
    	this.mapviewer.Hide3DNavigationControl();
    	this.mapviewer.HideScalebar();
    	
    	this.mapviewer.AttachEvent("onendzoom", this.storeBoundLocations);
    	this.mapviewer.AttachEvent("onendpan", this.storeBoundLocations);
    }
    ,getTiles: function()
    {
       var tileSourceSpec = new VETileSourceSpecification("lidar", 
           "http://ecn.t0.tiles.virtualearth.net/tiles/r%4.png?g=41&productSet=mmOS"
	   );
       
       tileSourceSpec.NumServers = 1;
       tileSourceSpec.MinZoomLevel = 11;
       tileSourceSpec.MaxZoomLevel = 15;
       tileSourceSpec.Opacity = 1;

       this.mapviewer.AddTileLayer(tileSourceSpec, true);
    } 
    ,loadJson: function(route, callback)
    {
        var _this = this;
        $.getJSON('/upload/route_gpxs/' + route + '.json', null, function(routePoints)
        {
            _this.points[route] = routePoints;
            callback(route, _this);
        });
    }
    ,redrawPoints: function(route)
    {
        this.mapviewer.removeAllOverlays();
        this.drawPoints(route, this);
    }
    ,drawPoints: function(route, instance)
    {
        if (!instance.points[route]) {
            this.loadJson(route, this.drawPoints);
        }
        else
        {
            var points = [];
            var descriptionIndex = 1;
            
            jQuery.each(instance.points[route], function(index, routePoint) {
            	var point = new VELatLong(routePoint.latitude, routePoint.longitude);
                points.push(point);
                
                if (routePoint.description.length) {
                    var marker = new VEShape(VEShapeType.Pushpin, point);
                    marker.SetDescription(routePoint.description);
                    instance.mapviewer.AddShape(marker);
                }
            });
            
            var poly = new VEPolyline(
        		route, points,  
        		new VEColor(255,0,0,1), // color
        		4						// width
    		);
            
            instance.mapviewer.AddPolyline(poly);
            instance.mapviewer.SetMapView(points);
        }
    }
    ,drawRoutes: function(routes) {
    	this.drawMap();
    	this.routesCache = routes;
    	this.routesPoints = [];
    	this.routesCount = 0;
    	
    	for (var k in routes) {
    	    if (routes.hasOwnProperty(k)) {
    	    	++this.routesCount;
    	    }
    	}

    	for (var id in routes) {
    		this.loadJson(id, this.drawMarker);
    	}
    }
    ,drawMarker: function(route, instance) {
		var routePoint = instance.points[route][0];
    	var point = new VELatLong(routePoint.latitude, routePoint.longitude);

        var marker = new VEShape(VEShapeType.Pushpin, point);
        marker.SetTitle(instance.routesCache[route]);
        
        instance.routesPoints.push(point);
        instance.mapviewer.AddShape(marker);
        
        if (instance.routesPoints.length == instance.routesCount) { 
        	instance.mapviewer.SetMapView(instance.routesPoints);
        }
    }
    ,storeBoundLocations: function()
    {
    	var view = map.mapviewer.GetMapView();
    	document.getElementById('search_map_locations').value = "(" + view.TopLeftLatLong.toString() + '|' + view.BottomRightLatLong.toString() + ")";
    }
};

