var bulbFinderAjax = null;
var bulbFinderButton = null;
var root = "";
var tb_pathToImage = "";

jQuery.fn.equalHeight = function() {
	var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        $(this).height(maxHeight + "px");
        if (this.offsetHeight>maxHeight) {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
        }
    });
};

// functions used throughout the site
// moved outside of document.ready for Safari 2.0.4. D'oh!
function updateAddressSession(id, type) {
    var ajax = $.ajax({type: "GET", url: root + "checkout/ajax_address.ashx", dataType: "text", data: "id=" + id + "&type=" + type, success: function(response){
        if (type == "Billing") {
            $("div.billing div.address-summary div.address").html(response);
        } else {
            $("div.delivery div.address-summary div.address").html(response);
        }
    }});
}
function copyInputValues(selector) {
    $(selector).each(function() {
        var delivery = $("#" + $(this).attr("id").replace(/_billing_/,"_delivery_")).attr("id");
        $("#" + delivery).val($(this).val());
    });
}
function copySelectValue(copyBilling) {
    if (copyBilling) {
        document.getElementById("ctl00_c_delivery_ddlTitle").selectedIndex = document.getElementById("ctl00_c_billing_ddlTitle").selectedIndex;
    }
}

function howFindMoreInfo(selector, stealfocus) {
    $("input#ctl00_c_txtHowFindOther").val("");
    if ($("option:selected", selector).hasClass("more-info")) {
        $("div.more-info").show();
        if (stealfocus) {
            $("input#ctl00_c_txtHowFindOther").focus();
        }
    } else {
        $("div.more-info").hide();		            
    }
}
		    
function parseAddressFromPostcodeLookup(address_json) {
    var address = eval("(" + address_json + ")");
    $("input#" + address.prefix + "txtAddress1").val(address.address1);
    $("input#" + address.prefix + "txtAddress2").val(address.address2);
    $("input#" + address.prefix + "txtAddress3").val(address.address3);
    $("input#" + address.prefix + "txtTown").val(address.town);
    $("input#" + address.prefix + "txtCounty").val(address.county);
    $("input#" + address.prefix + "txtCompanyName").val(address.company);
    $("input#" + address.prefix + "txtPostcode").val(address.postcode);    
    if ($("#ctl00_c_cbDeliverySameAsBilling").is(":checked")) {
        copyBillingToDelivery();
    }    
}

function highlightSelectedCategory() {
    var bodyClass = $("body").attr("class");
    catClass = bodyClass.replace(/[a-z]+/,"").replace(/\s/,"");
    $("#browse-products ul li." + catClass).addClass("selected");
}

function enhanceBulbFinderResults() {
    $("table.products tbody tr")
        .mouseover(function() { $(this).addClass("selected"); })
        .mouseout(function() { $(this).removeClass("selected"); })
        .click(function() { window.location = $("a", this).attr("href") });
    
    $("table.products tbody td").each(function() {
        if ($(this).html() == "") {
            $(this).html("&nbsp;");
        }
    });
        
    $("table.products tbody tr:odd").addClass("alt");
    
	$("div.paging a.disabled").each(function() {
	    $(this).after("<span class=\"disabled\">" + $(this).html() + "</span>").remove();
	});
	
	$("div.paging a").each(function() {
	    var text = $(this).text().toLowerCase();
	    if (text.indexOf("previous") == -1 && text.indexOf("next") == -1) {
	        $(this).addClass("page");
	    }
	});
	
	$("div#narrow-category div.subcats ul li:not(:last)").append(", ");
	$("div#narrow-category div.history ul li:not(:last):not(:first)").after("<li>&raquo;</li>");
	var lastLinkText = $("div#narrow-category div.history ul li:last a").text();
	$("div#narrow-category div.history ul li:last").html(lastLinkText);		
	$("div#narrow-category form input.button").attr("value", "Filter");
}

function paymentButtonLabels(e) {
    $("input.pay-button").val($(e).parent().find("label").attr("title"));
}
function setupPaymentTypes() {        
	    // add click/change events to inputs
	    $(".payment-types input").change(function() {
	        paymentButtonLabels(this);
	    });
	    if ($.browser.msie) {
	        $(".payment-types input").click(function() {
	        paymentButtonLabels(this);
	    });
	    }
	    // pre-select first payment option
	    $("form#aspnetForm:not(.postback) .payment-types input:first").attr("checked", "checked");	    
	    // persist selection on postback
	    var formClass = $("form#aspnetForm").attr("class") + "";
	    if (formClass.indexOf("payment") != -1) {
	        paymentType = $("form#aspnetForm").attr("class").replace(/postback payment-/,"");
	        $("form#aspnetForm input#pay_" + paymentType).attr("checked", "checked");
	    }		    
	    $("li.disabled input").attr("disabled", "disabled");
	    // persist button label on postback
	    paymentButtonLabels($(".payment-types input:checked"));
	    $(".payment-types li.disabled input").attr("disabled", "disabled");
}
    
function recalculateSaver(quantity) {
    var cost = $("span.calc_cost").html();
    var carbon = $("span.calc_carbon").html();
    $("div.saver ul.result li:first strong").html("&pound;" + (cost * quantity));
    $("div.saver ul.result li:last strong").html((carbon * quantity) + "kg");
}

$(document).ready(function() {
    $("html").addClass("hasJs");

    root = $("a#logo").attr("href");
    tb_pathToImage = root + "images/loadingAnimation.gif";
    
    var header = $("div#header");
    var nav = $("div#nav");
    header.height((nav.height() + 100) + "px");
    
	if (countBulbFinderSelections("#bulb-finder") == 4) {
		$("#bulb-finder input[@type='submit']").hide();
	}
	$("div#bulb-finder select, div#bulb-finder fieldset.search-in input").change(function(e) { bulbFinder(e); });
	
	if ($.browser.msie) {
	    $("div#bulb-finder fieldset.search-in input").click(function(e) { bulbFinder(e); });
	}
	
	var s = $("input#s");
    if(s.value == '') { s.value = s.title; }
    s.focus(function() { if(this.value == this.title) { this.value = ''; } });
    s.blur(function(){ if(this.value == '') { this.value = this.title; } });
    s.click(function(){ if(this.value == this.title && this.title != ''){ this.value=''; } });
	
	$("form label").each(function() {
	    var text = $(this).text();
	    $(this).html(text.replace(/\*/,"<span class=\"req\">*</span>"));
	});
	
	if (!$("body").hasClass("checkout")) {
	    $("div#show-vat").show();
        $("div#show-vat input").click(function() {
            var url = root + "product.aspx?mode=show-vat&show-vat=" + $(this).is(":checked") + "&url=" + encodeURIComponent(window.location.href);
            window.location.replace(url);
        });        
    } else {
        $("a#logo, p.copyright a").click(function() {
            if ($("body").attr("id") != "p-thankyou") {
                return confirm("You have not yet placed your order. Are you sure you want to leave the Checkout?");
            }
        });
    }	
	
	/*  If secondary is taller than primary, shift promotions area up so that its bottom 
	    edge aligns with bottom of secondary */
	var secondary_height = $("div#secondary").height();
	var breadcrumb_height = $("ul#breadcrumb").height() + parseInt($("div#primary").css("margin-top")) + parseInt($("div#primary").css("margin-bottom"));
	var primary_height = $("div#primary").height() + parseInt($("div#primary").css("margin-top")) + parseInt($("div#primary").css("margin-bottom"));
	var promotions_height = $("div#promotions").height() - 20;
	var diff = secondary_height - (primary_height + promotions_height + breadcrumb_height) + 8;
	if (diff > 0) {
	    $("div#promotions").css("margin-top", diff + "px");
	}
        
	$(".button").mouseover(function() { $(this).toggleClass("focus") }).mouseout(function() { $(this).toggleClass("focus") });

	$("a[@rel='external']").click(function() {	    
	    window.open($(this).attr("href"));
	    return false;
	});
	
	// give form fields focus from validation summary links
    $(".validationsummary li a").each(function() {
        $(this).click(function() {
            $($(this).attr("href")).focus();
            return false;
        });
    });
    
    // if validation summary is inline, add commas to each list item
    $("validationsummary-inline li:not(:last)").each(function() {
        var html = $(this).html();
        $(this).html(html + ", ");
    });
    
    $(".field span.extra-info").each(function() {
        $(this).prev().append($(this));
    });

	switch ($("body").attr("id")) {
	
	    case "p-home":
	        $("ul#categories li").equalHeight();
	        $("div#primary p:first").addClass("intro");
	        $("#quick-start li a[@href*='bulbfinder']").click(function(e) {
	            e.preventDefault();
	            window.location.hash = "#bulb-finder";
	            $("#bulb-finder form").highlightFadeBasket();
	            $("#bulb-finder form select:first").focus();
	        });	        
	        break;
	        
		case "p-category":
			wrapCategoryListing();
			enhanceBulbFinderResults();
			highlightSelectedCategory();
			break;
		
		case "p-product":
		
		    $("div.hproduct table tbody tr:odd").addClass("alt");
		    
		    $("div#addtobasket form").submit(function() {
		        $("div#addtobasket input.button")
		        .unbind("click")
		        .val("Please wait...")
		        .removeClass("green")
		        .addClass("grey");
		        var ajax = $.ajax({type: "GET", url: $("div#addtobasket form").attr("action").replace(/basket.aspx/, "ajax_basket_update.ashx"), dataType: "text", data: $(this).serialize(), success: function(response){
		            eval(response);
		            $("div#addtobasket h2").css("margin-top", "0")
		            $("div#addtobasket")
		            .css("margin-top", "20px")
		            .css("padding", "10px")
		            .css("width", "180px")
		            .highlightFade();	            
	            }});
		        return false;
		    });
		    
		    $("#calc_q").change(function() {
		        recalculateSaver($(this).val());
		    });
		    $("input[@name='quantity']").change(function() {
		        $("#calc_q").val($(this).val());
		        recalculateSaver($(this).val());
		    });
		    
		    var img = $("div.img");
		    $("img", img).get(0).onload = function() {
		        var h = $("img", img).height();
		        $("span.mask").height(h + "px");
		    }
		   
			break;
		case "p-basket":
		    $("table.basket tbody tr.product:odd").addClass("alt");
		    $("table.basket td.quantity input[@type='checkbox']").change(function() {
		        if (this.checked) {
		            $(this).parent().parent().css({opacity: "0.3"});
		        } else {
		            $(this).parent().parent().css({opacity: "1"});
		        }
		    });
		    var refer = unescape($("input#ctl00_c_ctl00_referal").val());
		    if (refer == "") {
		        refer = root;
		    }
		    $("td.continue-shopping a.secondary").attr("href", refer);
		    
		    $.ajax({type: "GET", url: root + "ajax_session.aspx?step=0", dataType: "text"});
		    
		    break;
			
		case "p-bulbfinder":
	        enhanceBulbFinderResults();
	        highlightSelectedCategory();
		    break;
		    		   
		case "p-search":
		    $("#s").val($("#s_value").html());
		    $("div.enquiryThanks").highlightFade();
		    enhanceBulbFinderResults();
		    $("table.products thead a").click(function() { return false; });
		    break;
		
		case "p-contact":
		    $("div.enquiryThanks").highlightFade();
		    break;
		
		case "p-sitemap":
		    $("ul.column").equalHeight();
		break;
	
	    case "p-articles":
	        var lastRow = $("div#primary div.row:last");
	        if ($("div.category", lastRow).length == 1) {
	            lastRow.addClass("wide");
	        }
	        $("div#primary div.row").each(function() {
	            $("div.category", this).equalHeight();
	        });
	    break;
	    
	    case "p-article":
	        if ($("body").hasClass("article-19")) {
	            var indices = [];
                var elems = jQuery("#primary").children();
                elems.each( function(i) {
                    if (jQuery(this).is("h2")) {
                        indices.push(i);
                    };
                });
                indices.push(elems.length);
                for (i=1; i < indices.length; i++) {
                    if (indices[i] - indices[i-1] != 1) {
                        elems.slice((indices[i-1]), indices[i]).wrapAll("<div class='term clearfix'></div>");
                    };
                };
	        }
	        if ($("body").hasClass("article-14")) {
	            var indices = [];
                var elems = jQuery("#primary").children();
                elems.each( function(i) {
                    if (jQuery(this).is("h2")) {
                        indices.push(i);
                    };
                });
                indices.push(elems.length);
                for (i=1; i < indices.length; i++) {
                    if (indices[i] - indices[i-1] != 1) {
                        elems.slice((indices[i-1]), indices[i]).wrapAll("<div class='bulb clearfix'></div>");
                    };
                };
                $("#primary div.bulb:last").removeClass("bulb").css("padding-top", "20px").css("clear", "both");
	        }
	    break;
	
	    case "p-custom":
		    $("div#footer a[@href$='"+$("body").attr("class")+"/']").addClass("selected");
		    
		    switch($("div#wrapper").attr("class")) {
		        case "p-how-to-enable-cookies":
		        
		            var browserFound = false;
	
	                $("div.browser-safari").hide();
	                $("div.browser-firefox").hide();
	                $("div.browser-ie6").hide();
	                $("div.browser-ie7").hide();
                	
	                if ($.browser.safari) {
		                $("browser-safari").show();
		                browserFound = true;
	                }

	                if ($.browser.mozilla) {
		                $("div.browser-firefox").show();
		                browserFound = true;
	                }

	                if ($.browser.msie) {
		                var version = parseInt($.browser.version);
		                if (version == 6) {
			                $("div.browser-ie6").show();
			                browserFound = true;
		                } else if (version == 7) {
			                $("div.browser-ie7").show();
			                browserFound = true;
		                }		
	                }
                	
	                if (!browserFound) {
		                $("div.browser-ie6").show();
	                }
		        break;
		    }
		    
		    break;
		    
		case "p-testimonials":
		    $("div#primary div.all div.row:odd").addClass("odd");
		    var curPage = 1;
            var loading = false;

            $("body").prepend("<div class=\"testimonials-loading\">Loading more comments...</div>");

            window.onscroll = function(){
                if ( curPage >= 1 && !loading && pageHeight() - scrollY() - windowHeight() < windowHeight() ) {
                    loading = true;
                    
                    $("div.testimonials-loading").fadeIn("slow");
                    
                    var ajax = $.ajax({
                        type: "GET",
                        url: root + "ajax_testimonials.ashx?page=" + (++curPage),
                        dataType: "text",
                        success: function(response){
                            if (response == "end") {
                                curPage = 0;
                            } else {
                                $("div.all").append(response)
                                $("div#primary div.all div.row").each(function() {
                                    if ($("div.comment", this).length == 0) {
                                        $(this).remove();
                                    }
                                });
                                $("div#primary div.all div.odd").removeClass("odd");
                                $("div#primary div.all div.row:odd").addClass("odd"); 
                            }                     
                        },
                        complete: function() {
                            loading = false;
                            $("div.testimonials-loading").fadeOut("slow");
                        }
                    });
                }
            };
		break;
	}

});

// Category - convert block elements to inline and wrap <a> around (maintains headings for SEO)
function wrapCategoryListing() {
	$("div.category").each(function() {
		$(this).html("<a href=\"" + $("h3.name a", this).attr("href") + "\"><img src=\"" + $("img", this).attr("src") + "\" alt=\"\" /><span class=\"name\">" + $(".name a", this).html() + "</span><span class=\"desc\"><span class=\"count\">" + $(".count a", this).html() + "</span></span></a>");
	});
	$("div.category").equalHeight();
}

function countBulbFinderSelections(selector) {
    var numAny = 0;
	$("select", $(selector)).each(function(i) {
	    if($(this).val() == "Any") {
	        numAny++;
	    }
	});
    if (numAny == 4 && typeof($("#ctl00_ucBulbFinderControls_search_in input").val()) != "undefined") {
        numAny = numAny - 1;
    }
	return numAny;
}

// Executed on change of 4 select boxes
function bulbFinder(e) {

    var form = $(e.target.form);
    
    var isBulbFinderSidebar = false;
    if ($(form).parent().attr("id") == "bulb-finder") {
        isBulbFinderSidebar = true;
    }
    
	// cancel any running bulb finder calls
	if (bulbFinderAjax) {
		bulbFinderAjax.abort();
	}
	
	// show "searching" label and animation
	var searchingText = "";
	if (isBulbFinderSidebar) {
	    searchingText = "Searching, <br />please wait...";
	} else {
	    searchingText = "Searching, please wait...";
	}
	$("div.searching", form)
	    .removeClass("result-false")
		.removeClass("result-true")
	    .html(searchingText)
		.show();
		
    

	if (isBulbFinderSidebar && countBulbFinderSelections("div#bulb-finder form") == 4) {
	    $("div.searching", form)
	        .text("")
	        .hide()
	        .removeClass("result-true")
			.addClass("result-false")
			.text("Please choose at least one option to search by.")
			.show();
		$("input[type='submit']", form).hide();
	    return false;
	}
	
	// perform AJAX request and load XML response	
	bulbFinderAjax = $.ajax({type: "GET", url: $("div#bulb-finder form").attr("action").replace("bulbfinder/","") + "ajax_bulbfinder.ashx", dataType: "xml", data: $(form).serialize(), success: function(response){
		$("div.searching", form).hide();
		var num_matches = $("matches", response).attr("count");
		if (num_matches == "0") {
			$("div.searching", form)
				.removeClass("result-true")
				.addClass("result-false")
				.text("Sorry, but we don't have any bulbs matching this specification.")
				.show();
			if (isBulbFinderSidebar) {
			    $("input[type='submit']", form).hide();
			}
		} else {
		    var label = "bulbs";
		    if (num_matches == 1) { label = "bulb"; } 
			$("div.searching", form)
				.removeClass("result-false")
				.addClass("result-true")
				.html("<strong>" + num_matches + "</strong> " + label + " found")
				.show();
			if (isBulbFinderSidebar) {
			    $("input[type='submit']", form)
				    .val("View matching bulbs")
				    .addClass("result-true")
				    .show();
			}
		}
	} });
	return false;
}

function scrollY() {
    var de = document.documentElement;
    return self.pageYOffset ||
        ( de && de.scrollTop ) ||
        document.body.scrollTop;
}
function windowHeight() {
    var de = document.documentElement;
    return self.innerHeight ||
        ( de && de.clientHeight ) ||
        document.body.clientHeight;
}
function pageHeight() {
    return document.body.scrollHeight;
}
