$(function() {
    
    $('a#process-import')
        .click(function() {
            if(confirm('Are you sure?')) {
                $(this).after('<p>Please wait...</p>');
                $(this).remove();
                return true;
            }
            else {
                return false;
            }
        });
    
    // Linear metres/quantity progressive enhancement
    var meterLengthText = $('span#meter-length').text();
    if(meterLengthText.match(/\d+(?:\.\d+)?/)) {
        var meterLength = meterLengthText-0;
        quantity = $('input#id_quantity')
        display = $('span#quantity-help')
            .append('&nbsp;<span id="display"/>')
            .find('span#display')
        var updateDisplay = function() {
            displayTxt = '';
            quantityInt = parseInt(quantity[0].value-0);
            if(!isNaN(quantityInt) && quantityInt>0) {
                displayTxt = display.text(' = ' + (quantityInt*meterLength) +
                    'm');
            }
            display.text(displayTxt)
        }
        updateDisplay();
        quantity.keyup(updateDisplay);
    }
    
    // Add a 'close' link to the trace window
    $('div#trace')
        .prepend('<p id="close-trace">[close]</p>').find('p#close-trace')
            .click(function() {
                $('div#trace').hide()
            });
    
    // Toggle visibility of detail on upload page
    $('div.sheet-errors')
        .addClass('sheet-errors-collapsed')
        .find('p')
            .append(' <a href="#" class="toggle">Show detail</a>')
            .find('a.toggle')
                .click(function() {
                   a = $(this)
                   div = a.parents('div.sheet-errors')
                   if(div.hasClass('sheet-errors-collapsed')) {
                       div.removeClass('sheet-errors-collapsed')
                       a.text('Hide detail.')
                   }
                   else {
                     div.addClass('sheet-errors-collapsed')  
                     a.text('Show detail.')
                   }
                   return false;
                });
    
    // Widgets that toggle visibility of elements
    function widgetToggle(widget, value, obj) {
        if(widget.length>0) {
            toggle = function(evt, duration) {
                duration = duration === undefined ? 100 : duration;
                if($(this).serializeArray()[0].value==value) {
                    obj.css('display','block')
                    //obj.show(duration);
                    return;
                }
                //obj.hide(duration)
                obj.css('display','none')
            }
            widget.click(toggle)
            toggle.apply(widget, [null, 0])
        }
    }
    widgetToggle($('input[name=moulding_required]'), 'Yes', 
        $('div#id_door_moulding').parent())
    widgetToggle($('select[name=timber]'), 'Other', 
        $('input#id_other_timber').parent())
})




/****************************************************************************/

// Globals
var slideshowInterval 	= 4000;
var slideshowPosition 	= 0;	
var slides 				= new Array();

// Preload
var images 		= new Array();
var preloader 	= new Image();
images.push("/static/furniture/double-arrow-gold.gif");
images.push("/static/furniture/double-arrow-grey.gif");
for(i in images) {
	preloader.src = images[i];		
}

$(document).ready(function() {

	// Add print page link to pages with ul#context-links
	$('ul#context-links').prepend('<li><a id="print-page" href="javascript:print()">Print page</a></li>');

	// Replace link to Google maps with iframe embedded map    
	map_html = '<iframe class="frame" width="674" height="470" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Atkey+and+Company&amp;sll=52.800651,-4.064941&amp;sspn=13.209342,39.331055&amp;ie=UTF8&amp;hq=Atkey+and+Company&amp;hnear=&amp;cid=7298160439260424237&amp;ll=51.384424,-2.727013&amp;spn=0.050352,0.115528&amp;z=13&amp;iwloc=A&amp;output=embed"></iframe>'
	$("p#googlemap>a").html(map_html)
	
	gutter();
	fnHomeLink();			
	fnFixes();		
	fnIEFixes();
	clickable();
	formoptions();
	buttons();
	if($("#wrapper-2").size()>0) {		 
		slides.push('/static/furniture/home-page-image-1.jpg');
		slides.push('/static/furniture/home-page-image-2.jpg');
		slides.push('/static/furniture/home-page-image-3.jpg');
		setTimeout("fnHomepageSlideshow()",slideshowInterval);
	}
});


// Gutter
function gutter() {
	if(!$.browser.msie) {
		$("html").css({"overflow-y":"scroll"})
	}	
}

// Add a absolutely positioned link over the logo
function fnHomeLink() {
	$("#wrapper-1 .center").prepend('<div id="homelink"></div>');
	$("#homelink").click(function(){ window.location="/" })
}

// Cross-browser enhancements
function fnFixes() {
	
	// replace spaces with &nbsp; character to make each element fall onto a whole line without widows
	$(".slashlist li a, #basket dd, #basket dt").each(function(){
		var html = $(this).html();
		$(this).html(html.replace(/\s/g,"&nbsp;"))
		
	})
}

// IE6 & 7 arrow fix
function fnIEFixes() {
	if($.browser.msie && jQuery.browser.version.substr(0,1)<8) {
		
		// Grey right-of-link arrows		
		$(".arrowlinks a").append('<img src="/static/furniture/double-arrow-grey.gif" alt="" class="iedoublearrow grey" />').hover(function(){
			$("img",this).attr("src","/static/furniture/double-arrow-blue.gif");
		},function(){
			$("img",this).attr("src","/static/furniture/double-arrow-grey.gif");
		});
		
		// Blue ight-of-link arrows
		$(".print a").append('<img src="/static/furniture/double-arrow-blue.gif" alt="" class="iedoublearrow blue" />').hover(function(){
			$("img",this).attr("src","/static/furniture/double-arrow-gold.gif");
		},function(){
			$("img",this).attr("src","/static/furniture/double-arrow-blue.gif");
		});
		
		// Wierd ie 6 double right margin on last element. Could not work out via CSS
		$(".grid-product:last").css({marginRight:"0"}) 
		
		
		// Homepage catalogue slash links
		$("#home-page-products li").append('<img src="/static/furniture/slash.gif" alt="" class="ieslash" />');
		
	} 
}


/* Make a whole box clickable */
function clickable() {
	$(".clickable:has(a)").css({"cursor":"pointer"}).live("click",function() {
		var link = $("a",this).eq(0).attr("href");
		window.location = link;
	}).hover(function(){
		$(this).addClass("hover");
	},function(){
		$(this).removeClass("hover");
	})
}

/* Make a whole box clickable */
function formoptions() {
	$(".product-option input:radio").click(function(){
		$(".product-option").removeClass("selected");
		if($(this).is(":checked")) {
			$(this).closest(".product-option").addClass("selected")
		}
	})
}

// Buttons
function buttons() {
	$("input.btn").each(function(){
		var t = $(this).attr("value");
		$(this).after('<div class="formbutton input"><div>'+t+'</div></div>').remove();
	})
	$("a.btn").each(function(){
		var t = $(this).html();
		var l = $(this).attr("href");
		$(this).after('<div class="formbutton link"><a href="'+l+'">'+t+'</a></div>').remove();
	})
	$(".formbutton").click(function(){
		if($(this).hasClass("input")) {
			$(this).closest("form").submit();	
		}		
	}).hover(function(){$(this).addClass("buttonhover")},function(){$(this).removeClass("buttonhover")})
}


// Home page slideshow
function fnHomepageSlideshow() {
	
	var speed = 2000;
	var next = slideshowPosition+1;
	slideshowPosition++;
	if(next > slides.length-1) {
		next=0;
		slideshowPosition = 0;
	}
	var nextImage = slides[next];	
	
	var img1 = $("#wrapper-2 .center img");	
	img1.css({zIndex:1}).attr("id","image1");
	$("#wrapper-2 .center").append('<img src="' + nextImage + '" id="image2" style="display:none;z-index:2" />');
	
	newImage = new Image();
	newImage.onload = function() {		
		$("#image2").fadeIn(speed,function(){
			$("#image1").remove();
			setTimeout("fnHomepageSlideshow()",slideshowInterval);
		});	
	}	
	newImage.src = nextImage;
}

/* Print */
function fnPrintLink(text) {
	var text = text || "Print this page";
	document.write('<p class="print"><img src="/static/furniture/print.gif" /><a href="javascript:window.print();">'+text+'</a></p>');
}
