/* Minification failed. Returning unminified contents.
(1,10): run-time error CSS1031: Expected selector, found '='
(1,10): run-time error CSS1025: Expected comma or open brace, found '='
(1,14): run-time error CSS1019: Unexpected token, found ';'
(3,10): run-time error CSS1031: Expected selector, found 'navOver('
(3,10): run-time error CSS1025: Expected comma or open brace, found 'navOver('
(13,1): run-time error CSS1019: Unexpected token, found '$'
(13,2): run-time error CSS1019: Unexpected token, found '('
(13,12): run-time error CSS1031: Expected selector, found '('
(13,12): run-time error CSS1025: Expected comma or open brace, found '('
(107,2): run-time error CSS1019: Unexpected token, found ')'
(107,3): run-time error CSS1019: Unexpected token, found ';'
(110,1): run-time error CSS1019: Unexpected token, found '/'
(110,2): run-time error CSS1019: Unexpected token, found '/'
(111,10): run-time error CSS1031: Expected selector, found 'setProductViewType('
(111,10): run-time error CSS1025: Expected comma or open brace, found 'setProductViewType('
(126,1): run-time error CSS1019: Unexpected token, found '/'
(126,2): run-time error CSS1019: Unexpected token, found '/'
(127,10): run-time error CSS1031: Expected selector, found 'addToCart('
(127,10): run-time error CSS1025: Expected comma or open brace, found 'addToCart('
(150,1): run-time error CSS1019: Unexpected token, found '/'
(150,2): run-time error CSS1019: Unexpected token, found '/'
(150,30): run-time error CSS1031: Expected selector, found '/'
(150,30): run-time error CSS1025: Expected comma or open brace, found '/'
(172,1): run-time error CSS1019: Unexpected token, found '/'
(172,2): run-time error CSS1019: Unexpected token, found '/'
(173,10): run-time error CSS1031: Expected selector, found 'addToWishlist('
(173,10): run-time error CSS1025: Expected comma or open brace, found 'addToWishlist('
(191,1): run-time error CSS1019: Unexpected token, found '/'
(191,2): run-time error CSS1019: Unexpected token, found '/'
(192,10): run-time error CSS1031: Expected selector, found 'lookupSuburbs('
(192,10): run-time error CSS1025: Expected comma or open brace, found 'lookupSuburbs('
(194,67): run-time error CSS1002: Unterminated string: 't lookup until postcode completed
(247,1): run-time error CSS1019: Unexpected token, found '/'
(247,2): run-time error CSS1019: Unexpected token, found '/'
(248,10): run-time error CSS1031: Expected selector, found 'checkAccount('
(248,10): run-time error CSS1025: Expected comma or open brace, found 'checkAccount('
(283,1): run-time error CSS1019: Unexpected token, found '/'
(283,2): run-time error CSS1019: Unexpected token, found '/'
(283,31): run-time error CSS1031: Expected selector, found '('
(283,31): run-time error CSS1025: Expected comma or open brace, found '('
(323,10): run-time error CSS1031: Expected selector, found 'loginPopup('
(323,10): run-time error CSS1025: Expected comma or open brace, found 'loginPopup('
(340,10): run-time error CSS1031: Expected selector, found 'getPageScroll('
(340,10): run-time error CSS1025: Expected comma or open brace, found 'getPageScroll('
(354,10): run-time error CSS1031: Expected selector, found 'getPageSize('
(354,10): run-time error CSS1025: Expected comma or open brace, found 'getPageSize('
(399,10): run-time error CSS1031: Expected selector, found 'removePopup('
(399,10): run-time error CSS1025: Expected comma or open brace, found 'removePopup('
(403,1): run-time error CSS1019: Unexpected token, found '$'
(403,2): run-time error CSS1019: Unexpected token, found '('
(403,12): run-time error CSS1031: Expected selector, found '('
(403,12): run-time error CSS1025: Expected comma or open brace, found '('
(408,2): run-time error CSS1019: Unexpected token, found ')'
(408,3): run-time error CSS1019: Unexpected token, found ';'
(410,10): run-time error CSS1031: Expected selector, found 'lineUpShopButtons('
(410,10): run-time error CSS1025: Expected comma or open brace, found 'lineUpShopButtons('
(431,1): run-time error CSS1019: Unexpected token, found '('
(431,11): run-time error CSS1031: Expected selector, found '('
(431,11): run-time error CSS1025: Expected comma or open brace, found '('
(501,13): run-time error CSS1019: Unexpected token, found ')'
(501,14): run-time error CSS1019: Unexpected token, found '('
(501,21): run-time error CSS1031: Expected selector, found ')'
(501,21): run-time error CSS1025: Expected comma or open brace, found ')'
(505,4): run-time error CSS1031: Expected selector, found '('
(505,4): run-time error CSS1025: Expected comma or open brace, found '('
(507,1): run-time error CSS1019: Unexpected token, found '/'
(837): run-time error CSS1001: Unterminated comment.
 */
var Cart = {};

function navOver(imgTag) {
    var theImage = imgTag;
    if (theImage.src.indexOf("_off.") != -1) {
        theImage.src = theImage.src.replace("_off.", "_on.");
    }
    else {
        theImage.src = theImage.src.replace("_on.", "_off.");
    }
}

$(function () {
	//replace dropdowns
	$(".selectBox:visible").selectBox();
	//show forgot password
	$(".forgotPopup").click(function () {
		$(".showForgotten").toggle();
		return false;
	});
	$(".hideForgotten").click(function () {
		$(".showForgotten").hide();
		return false;
	});
	//temporary, for dislpaying login/logout in shopping cart.
	//$(".ifAccount").hide();
	$(".tempLogIn").click(function () {
		$(".ifAccount").show();
		$(".ifNoAccount").hide();
		return false;
	});
	//    $(".tempLogout").click(function () {
	//        $(".ifNoAccount").show();
	//        $(".ifAccount").hide();
	//        return false;
	//    });
	//toggle between list and grid view
	$(".viewList").click(function () {

		$(this).addClass("viewListOn");
		$(".viewGrid").removeClass("viewGridOn");
		$("#gridView").hide();
		$("#listView").fadeIn("slow");

		setProductViewType("List");
		return false;

	});
	$(".viewGrid").click(function () {

		$(this).addClass("viewGridOn");
		$(".viewList").removeClass("viewListOn");
		$("#listView").hide();
		$("#gridView").fadeIn("slow", lineUpShopButtons);

		setProductViewType("Grid");
		return false;

	});

	Cart.DOM = {
		wrapper: $(".cartStatus"),
		items: {
			wrapper: $(".cart-items-wrapper"),
			count: $(".cart-items .items"),
			cost: $(".cart-total .total")
		},
		empty: $(".cart-empty")
	};

	Cart.updateValues = function (items, total, callback) {

		total = '$' + total.toFixed(2);

		// Fadeout the current cart display
		Cart.DOM.wrapper.fadeOut(function () {

			// Update the item count/cost
			Cart.DOM.items.count.text(items);
			Cart.DOM.items.cost.text(total);

			// Hide the empty cart display
			Cart.DOM.empty.hide();
			Cart.DOM.items.wrapper.show();

			// Fade in the new cart display
			Cart.DOM.wrapper.fadeIn(1200);
		});

		if (callback)
			callback.call(this);
	};

	// setup the blur action on the email field in account details
	$('.txtEmailBlur').live('focusout', function () {
		checkAccount($(this).val());
	});

	lineUpShopButtons();

	// Listen for 'tab' button on the postcode shipping fields (not blurring correctly in some browsers)
	$('#txtPostcode, #postcode').keyup(function (event) {
		if (event.which == 9) {
			$(this).blur();
		}
    });
});


// Set product page view type
function setProductViewType(viewType) {

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/api/product-view-settings.asmx/SetViewType?view=' + viewType,
        dataType: 'json',
        success: function (response) {
            if ("console" in window)
                console.log(response);
        }
    });

}

// Add product to cart
function addToCart(id, qty, btn) {

	$.ajax({
		type: 'POST',
		url: '/api/shopping-cart.asmx/AddProduct',
		data: "productID=" + id + "&quantity=" + qty,
		success: function (response) {

			if (btn != null)
				addedPopup(btn, 'cart');

			var content = response.documentElement.textContent || response.documentElement.text;
			var responseData = $.parseJSON(content);

			Cart.updateValues(responseData.NumberOfItems, responseData.TotalCost);

			if ("console" in window)
				console.log(responseData);
		}
	});

}

// Display the added to cart / wishlist animation
function addedPopup(btn, type) {
    // insert the 'added to cart' balloon
    if (type == "cart")
        $(btn).before("<span class=\"popupAddToCart\">Added to cart</span");
    else if (isLoggedIn)
        $(btn).before("<span class=\"popupAddToWishlist\">Added to wishlist</span");
    else
        $(btn).before("<span class=\"popupAddToWishlistLoggedOut\">Added to wishlist � you need to be logged in to access your wishlist</span>");
    var popup = $(btn).prev();
    // Fade in, wait, then fade out and remove the balloon
    popup.animate({
        opacity: 1
    }, 500, function () {
        $(this).delay(2000).animate({
            opacity: 0
        }, 1000, function () {
            $(this).remove();
        });
    });
}

// Add product to wishlist
function addToWishlist(id,btn) {
    
    $.ajax({
        type: 'POST',
        url: '/api/shopping-cart.asmx/AddToWishlist',
        data: "productID=" + id,
        success: function (response) {

            if (btn != null)
                addedPopup(btn, 'wishlist');

            if ("console" in window)
                console.log(response);
        }
    });

}

// Suburb-postcode ajax lookup
function lookupSuburbs(postcode, callback) {

	if (postcode.length != 4) // don't lookup until postcode completed
		return;

	$.ajax({
		type: 'POST',
		url: '/api/shopping-cart.asmx/LookupSuburbs',
		data: { postcode: postcode },
		success: function (response) {

			var content = response.documentElement.textContent || response.documentElement.text;
			var responseObj = $.parseJSON(content);

			if ("console" in window)
				console.log(responseObj);

			var suburbSelect = $("#select-suburb");
			var suburbError = $("#select-suburb-error");
			var suburbList = document.getElementById("ddlSuburbs");

			suburbSelect.hide();
			suburbError.hide();

			// Build the list of suburbs
			suburbList.options.length = 0; // clear existing first
			for (var i = 0, len = responseObj.length; i < len; i++) {
				var newOption = document.createElement("option");
				newOption.value = responseObj[i].Id;
				if (navigator.appName == 'Microsoft Internet Explorer')
					newOption.innerText = responseObj[i].Name + ", " + responseObj[i].State + " " + responseObj[i].Postcode;
				else
					newOption.text = responseObj[i].Name + ", " + responseObj[i].State + " " + responseObj[i].Postcode;
				suburbList.appendChild(newOption);
			}

			if (responseObj != null && responseObj.length > 0) {
				suburbSelect.show();
				$('#ddlSuburbs').selectBox();
				$('#ddlSuburbs').selectBox('refresh');
				$('#select-suburb .selectBox').focus();
				if (typeof callback == "function")
					callback();
			}
			else {
				$("#txtPostcode").parent().addClass("inputCError");
				suburbError.fadeIn("slow");
				suburbError.selectBox();
			}
			$('#ddlSuburbs').focus();
		}
	});

}

// Check for existance of customer account by email
function checkAccount(email) {
    
	if (!email || email.replace(/\s/g, "") === "")
		return;

	$.ajax({
		type: 'POST',
		url: '/api/customers.asmx/CheckAccount',
		data: "email=" + email,
		success: function (response) {

			var content = response.documentElement.textContent || response.documentElement.text;

			if ("console" in window)
				console.log(content);

			if (content == "true") {
				// Populate email field and focus password
				$("#divLoginEmail #txtLoginEmail").val(email);
				$("#txtLoginPass").focus();
				$("#btnPayNow").attr("disabled", "disabled");

				// Panel fadey slidey
				$("#account-details").fadeOut(250, function () {
					$("#login-panel").animate({ width: "100%" }, function () {
						$("#login-panel .loginMessage").fadeIn(600);
					});
				});

			}

		}
	});
}

// Retrieve password function (ajax)
function retrievePassword() {

	var email = $("#txtFpEmail").val();

	$.ajax({
		type: 'POST',
		url: '/api/customers.asmx/RetrievePassword',
		data: "email=" + email,
		success: function (response) {

			var content = response.documentElement.textContent || response.documentElement.text;

			if ("console" in window)
				console.log(content);

			var message = $("#fpMsg");
			message.hide();

            if (content == "true") { // success
                var messageHtml = "Your password has been reset and sent to your email address.";
                messageHtml += "<br /><span class='importantNote'><strong>Please note:</strong> Check the spam folder of your inbox</span>";

				$("#fpMsg").html(messageHtml);
				message.fadeIn("slow");
			}
			else { // failure
				$("#fpMsg").html("Password retrieval failed.");
				message.fadeIn("slow");
				setTimeout(function () {
					message.fadeOut("slow", function () {
						message.html("Enter the email address associated with your account to retrieve your password.");
						message.fadeIn("slow");
					});
				}, 1500);
			}
		}
	});
}

function loginPopup() {

    var sizeatt = getPageSize();
    var scrollatt = getPageScroll();
    var fullHeight = "";

    overlayObj = document.getElementById("overlay2");
    overlayBoxObj = document.getElementById("overlayCLogin");

    overlayObj.style.display = "block";
    fullHeight = sizeatt[1];

    overlayObj.style.height = fullHeight + "px";
    overlayBoxObj.style.display = "block";
    overlayBoxObj.style.top = scrollatt[1] + 100 + "px";
}

function getPageScroll() {
    var yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {
        yScroll = document.body.scrollTop;
    }

    arrayPageScroll = new Array('', yScroll)
    return arrayPageScroll;
}

function getPageSize() {

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.scrollHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }

    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
    return arrayPageSize;
}

function removePopup() {
    $("#overlay2, #overlayCLogin").hide();
}

$(function () {
    $("#overlay2").click(function () {
        removePopup();
        return false;
    });
});

function lineUpShopButtons() {
    // Equalises the height of the text areas on the shop pages so that all 'Buy' and 'More' buttons horizontally align.
    var maxHeight = 0;
    $('.p-text').each(function () {
    	$(this).css('height', 'auto');
    	if (parseInt($(this).css('height')) > maxHeight)
    		maxHeight = parseInt($(this).css('height'));
    });
	if (maxHeight != 0)
		$('.p-text').css('height', maxHeight + "px");
}

/* PLUGINS!! */

/*
* SimpleModal 1.4.1 - jQuery Plugin
* http://www.ericmmartin.com/projects/simplemodal/
* Copyright (c) 2010 Eric Martin (http://twitter.com/ericmmartin)
* Dual licensed under the MIT and GPL licenses
* Revision: $Id: jquery.simplemodal.js 261 2010-11-05 21:16:20Z emartin24 $
*/
(function (d) {
    var k = d.browser.msie && parseInt(d.browser.version) === 6 && typeof window.XMLHttpRequest !== "object", m = d.browser.msie && parseInt(d.browser.version) === 7, l = null, f = []; d.modal = function (a, b) { return d.modal.impl.init(a, b) }; d.modal.close = function () { d.modal.impl.close() }; d.modal.focus = function (a) { d.modal.impl.focus(a) }; d.modal.setContainerDimensions = function () { d.modal.impl.setContainerDimensions() }; d.modal.setPosition = function () { d.modal.impl.setPosition() }; d.modal.update = function (a, b) {
        d.modal.impl.update(a,
b)
    }; d.fn.modal = function (a) { return d.modal.impl.init(this, a) }; d.modal.defaults = { appendTo: "form", focus: true, opacity: 50, overlayId: "simplemodal-overlay", overlayCss: {}, containerId: "simplemodal-container", containerCss: {}, dataId: "simplemodal-data", dataCss: {}, minHeight: null, minWidth: null, maxHeight: null, maxWidth: null, autoResize: false, autoPosition: true, zIndex: 1E3, close: true, closeHTML: '<a class="modalCloseImg" title="Close"></a>', closeClass: "simplemodal-close", escClose: true, overlayClose: false, position: null,
        persist: false, modal: true, onOpen: null, onShow: null, onClose: null
    }; d.modal.impl = { d: {}, init: function (a, b) {
        var c = this; if (c.d.data) return false; l = d.browser.msie && !d.boxModel; c.o = d.extend({}, d.modal.defaults, b); c.zIndex = c.o.zIndex; c.occb = false; if (typeof a === "object") {
            a = a instanceof jQuery ? a : d(a); c.d.placeholder = false; if (a.parent().parent().size() > 0) {
                a.before(d("<span></span>").attr("id", "simplemodal-placeholder").css({ display: "none" })); c.d.placeholder = true; c.display = a.css("display"); if (!c.o.persist) c.d.orig =
a.clone(true)
            } 
        } else if (typeof a === "string" || typeof a === "number") a = d("<div></div>").html(a); else { alert("SimpleModal Error: Unsupported data type: " + typeof a); return c } c.create(a); c.open(); d.isFunction(c.o.onShow) && c.o.onShow.apply(c, [c.d]); return c
    }, create: function (a) {
        var b = this; f = b.getDimensions(); if (b.o.modal && k) b.d.iframe = d('<iframe src="javascript:false;"></iframe>').css(d.extend(b.o.iframeCss, { display: "none", opacity: 0, position: "fixed", height: f[0], width: f[1], zIndex: b.o.zIndex, top: 0, left: 0 })).appendTo(b.o.appendTo);
        b.d.overlay = d("<div></div>").attr("id", b.o.overlayId).addClass("simplemodal-overlay").css(d.extend(b.o.overlayCss, { display: "none", opacity: b.o.opacity / 100, height: b.o.modal ? f[0] : 0, width: b.o.modal ? f[1] : 0, position: "fixed", left: 0, top: 0, zIndex: b.o.zIndex + 1 })).appendTo(b.o.appendTo); b.d.container = d("<div></div>").attr("id", b.o.containerId).addClass("simplemodal-container").css(d.extend(b.o.containerCss, { display: "none", position: "fixed", zIndex: b.o.zIndex + 2 })).append(b.o.close && b.o.closeHTML ? d(b.o.closeHTML).addClass(b.o.closeClass) :
"").appendTo(b.o.appendTo); b.d.wrap = d("<div></div>").attr("tabIndex", -1).addClass("simplemodal-wrap").css({ height: "100%", outline: 0, width: "100%" }).appendTo(b.d.container); b.d.data = a.attr("id", a.attr("id") || b.o.dataId).addClass("simplemodal-data").css(d.extend(b.o.dataCss, { display: "none" })).appendTo("body"); b.setContainerDimensions(); b.d.data.appendTo(b.d.wrap); if (k || l) b.fixIE()
    }, bindEvents: function () {
        var a = this; d("." + a.o.closeClass).bind("click.simplemodal", function (b) { b.preventDefault(); a.close() });
        a.o.modal && a.o.close && a.o.overlayClose && a.d.overlay.bind("click.simplemodal", function (b) { b.preventDefault(); a.close() }); d(document).bind("keydown.simplemodal", function (b) { if (a.o.modal && b.keyCode === 9) a.watchTab(b); else if (a.o.close && a.o.escClose && b.keyCode === 27) { b.preventDefault(); a.close() } }); d(window).bind("resize.simplemodal", function () {
            f = a.getDimensions(); a.o.autoResize ? a.setContainerDimensions() : a.o.autoPosition && a.setPosition(); if (k || l) a.fixIE(); else if (a.o.modal) {
                a.d.iframe && a.d.iframe.css({ height: f[0],
                    width: f[1]
                }); a.d.overlay.css({ height: f[0], width: f[1] })
            } 
        })
    }, unbindEvents: function () { d("." + this.o.closeClass).unbind("click.simplemodal"); d(document).unbind("keydown.simplemodal"); d(window).unbind("resize.simplemodal"); this.d.overlay.unbind("click.simplemodal") }, fixIE: function () {
        var a = this, b = a.o.position; d.each([a.d.iframe || null, !a.o.modal ? null : a.d.overlay, a.d.container], function (c, h) {
            if (h) {
                var g = h[0].style; g.position = "absolute"; if (c < 2) {
                    g.removeExpression("height"); g.removeExpression("width"); g.setExpression("height",
'document.body.scrollHeight > document.body.clientHeight ? document.body.scrollHeight : document.body.clientHeight + "px"'); g.setExpression("width", 'document.body.scrollWidth > document.body.clientWidth ? document.body.scrollWidth : document.body.clientWidth + "px"')
                } else {
                    var e; if (b && b.constructor === Array) {
                        c = b[0] ? typeof b[0] === "number" ? b[0].toString() : b[0].replace(/px/, "") : h.css("top").replace(/px/, ""); c = c.indexOf("%") === -1 ? c + ' + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"' :
parseInt(c.replace(/%/, "")) + ' * ((document.documentElement.clientHeight || document.body.clientHeight) / 100) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'; if (b[1]) { e = typeof b[1] === "number" ? b[1].toString() : b[1].replace(/px/, ""); e = e.indexOf("%") === -1 ? e + ' + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"' : parseInt(e.replace(/%/, "")) + ' * ((document.documentElement.clientWidth || document.body.clientWidth) / 100) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"' } 
                    } else {
                        c =
'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'; e = '(document.documentElement.clientWidth || document.body.clientWidth) / 2 - (this.offsetWidth / 2) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"'
                    } g.removeExpression("top"); g.removeExpression("left"); g.setExpression("top",
c); g.setExpression("left", e)
                } 
            } 
        })
    }, focus: function (a) { var b = this; a = a && d.inArray(a, ["first", "last"]) !== -1 ? a : "first"; var c = d(":input:enabled:visible:" + a, b.d.wrap); setTimeout(function () { c.length > 0 ? c.focus() : b.d.wrap.focus() }, 10) }, getDimensions: function () { var a = d(window); return [d.browser.opera && d.browser.version > "9.5" && d.fn.jquery < "1.3" || d.browser.opera && d.browser.version < "9.5" && d.fn.jquery > "1.2.6" ? a[0].innerHeight : a.height(), a.width()] }, getVal: function (a, b) {
        return a ? typeof a === "number" ? a : a === "auto" ? 0 :
a.indexOf("%") > 0 ? parseInt(a.replace(/%/, "")) / 100 * (b === "h" ? f[0] : f[1]) : parseInt(a.replace(/px/, "")) : null
    }, update: function (a, b) { var c = this; if (!c.d.data) return false; c.d.origHeight = c.getVal(a, "h"); c.d.origWidth = c.getVal(b, "w"); c.d.data.hide(); a && c.d.container.css("height", a); b && c.d.container.css("width", b); c.setContainerDimensions(); c.d.data.show(); c.o.focus && c.focus(); c.unbindEvents(); c.bindEvents() }, setContainerDimensions: function () {
        var a = this, b = k || m, c = a.d.origHeight ? a.d.origHeight : d.browser.opera ?
a.d.container.height() : a.getVal(b ? a.d.container[0].currentStyle.height : a.d.container.css("height"), "h"); b = a.d.origWidth ? a.d.origWidth : d.browser.opera ? a.d.container.width() : a.getVal(b ? a.d.container[0].currentStyle.width : a.d.container.css("width"), "w"); var h = a.d.data.outerHeight(true), g = a.d.data.outerWidth(true); a.d.origHeight = a.d.origHeight || c; a.d.origWidth = a.d.origWidth || b; var e = a.o.maxHeight ? a.getVal(a.o.maxHeight, "h") : null, i = a.o.maxWidth ? a.getVal(a.o.maxWidth, "w") : null; e = e && e < f[0] ? e : f[0]; i = i && i <
f[1] ? i : f[1]; var j = a.o.minHeight ? a.getVal(a.o.minHeight, "h") : "auto"; c = c ? a.o.autoResize && c > e ? e : c < j ? j : c : h ? h > e ? e : a.o.minHeight && j !== "auto" && h < j ? j : h : j; e = a.o.minWidth ? a.getVal(a.o.minWidth, "w") : "auto"; b = b ? a.o.autoResize && b > i ? i : b < e ? e : b : g ? g > i ? i : a.o.minWidth && e !== "auto" && g < e ? e : g : e; a.d.container.css({ height: c, width: b }); a.d.wrap.css({ overflow: h > c || g > b ? "auto" : "visible" }); a.o.autoPosition && a.setPosition()
    }, setPosition: function () {
        var a = this, b, c; b = f[0] / 2 - a.d.container.outerHeight(true) / 2; c = f[1] / 2 - a.d.container.outerWidth(true) /
2; if (a.o.position && Object.prototype.toString.call(a.o.position) === "[object Array]") { b = a.o.position[0] || b; c = a.o.position[1] || c } else { b = b; c = c } a.d.container.css({ left: c, top: b })
    }, watchTab: function (a) {
        var b = this; if (d(a.target).parents(".simplemodal-container").length > 0) {
            b.inputs = d(":input:enabled:visible:first, :input:enabled:visible:last", b.d.data[0]); if (!a.shiftKey && a.target === b.inputs[b.inputs.length - 1] || a.shiftKey && a.target === b.inputs[0] || b.inputs.length === 0) {
                a.preventDefault(); b.focus(a.shiftKey ? "last" :
"first")
            } 
        } else { a.preventDefault(); b.focus() } 
    }, open: function () { var a = this; a.d.iframe && a.d.iframe.show(); if (d.isFunction(a.o.onOpen)) a.o.onOpen.apply(a, [a.d]); else { a.d.overlay.show(); a.d.container.show(); a.d.data.show() } a.o.focus && a.focus(); a.bindEvents() }, close: function () {
        var a = this; if (!a.d.data) return false; a.unbindEvents(); if (d.isFunction(a.o.onClose) && !a.occb) { a.occb = true; a.o.onClose.apply(a, [a.d]) } else {
            if (a.d.placeholder) {
                var b = d("#simplemodal-placeholder"); if (a.o.persist) b.replaceWith(a.d.data.removeClass("simplemodal-data").css("display",
a.display)); else { a.d.data.hide().remove(); b.replaceWith(a.d.orig) } 
            } else a.d.data.hide().remove(); a.d.container.hide().remove(); a.d.overlay.hide(); a.d.iframe && a.d.iframe.hide().remove(); setTimeout(function () { a.d.overlay.remove(); a.d = {} }, 10)
        } 
    } 
    }
           })(jQuery);


/* jQuery SelectBox - https://github.com/claviska/jquery-selectBox */
if (jQuery) (function ($) { $.extend($.fn, { selectBox: function (method, data) { var typeTimer, typeSearch = '', isMac = navigator.platform.match(/mac/i); var init = function (select, data) { var options; if (navigator.userAgent.match(/iPad|iPhone|Android|IEMobile|BlackBerry/i)) return false; if (select.tagName.toLowerCase() !== 'select') return false; select = $(select); if (select.data('selectBox-control')) return false; var control = $('<a class="selectBox" />'), inline = select.attr('multiple') || parseInt(select.attr('size')) > 1; var settings = data || {}; control.width(select.outerWidth()).addClass(select.attr('class')).attr('title', select.attr('title') || '').attr('tabindex', parseInt(select.attr('tabindex'))).css('display', 'inline-block').bind('focus.selectBox', function () { if (this !== document.activeElement && document.body !== document.activeElement) $(document.activeElement).blur(); if (control.hasClass('selectBox-active')) return; control.addClass('selectBox-active'); select.trigger('focus') }).bind('blur.selectBox', function () { if (!control.hasClass('selectBox-active')) return; control.removeClass('selectBox-active'); select.trigger('blur') }); if (!$(window).data('selectBox-bindings')) { $(window).data('selectBox-bindings', true).bind('scroll.selectBox', hideMenus).bind('resize.selectBox', hideMenus) } if (select.attr('disabled')) control.addClass('selectBox-disabled'); select.bind('click.selectBox', function (event) { control.focus(); event.preventDefault() }); if (inline) { options = getOptions(select, 'inline'); control.append(options).data('selectBox-options', options).addClass('selectBox-inline selectBox-menuShowing').bind('keydown.selectBox', function (event) { handleKeyDown(select, event) }).bind('keypress.selectBox', function (event) { handleKeyPress(select, event) }).bind('mousedown.selectBox', function (event) { if ($(event.target).is('A.selectBox-inline')) event.preventDefault(); if (!control.hasClass('selectBox-focus')) control.focus() }).insertAfter(select); if (!select[0].style.height) { var size = select.attr('size') ? parseInt(select.attr('size')) : 5; var tmp = control.clone().removeAttr('id').css({ position: 'absolute', top: '-9999em' }).show().appendTo('body'); tmp.find('.selectBox-options').html('<li><a>\u00A0</a></li>'); var optionHeight = parseInt(tmp.find('.selectBox-options A:first').html('&nbsp;').outerHeight()); tmp.remove(); control.height(optionHeight * size) } disableSelection(control) } else { var label = $('<span class="selectBox-label" />'), arrow = $('<span class="selectBox-arrow" />'); label.attr('class', getLabelClass(select)).text(getLabelText(select)); options = getOptions(select, 'dropdown'); options.appendTo('BODY'); control.data('selectBox-options', options).addClass('selectBox-dropdown').append(label).append(arrow).bind('mousedown.selectBox', function (event) { if (control.hasClass('selectBox-menuShowing')) { hideMenus() } else { event.stopPropagation(); options.data('selectBox-down-at-x', event.screenX).data('selectBox-down-at-y', event.screenY); showMenu(select) } }).bind('keydown.selectBox', function (event) { handleKeyDown(select, event) }).bind('keypress.selectBox', function (event) { handleKeyPress(select, event) }).bind('open.selectBox', function (event, triggerData) { if (triggerData && triggerData._selectBox === true) return; showMenu(select) }).bind('close.selectBox', function (event, triggerData) { if (triggerData && triggerData._selectBox === true) return; hideMenus() }).insertAfter(select); var labelWidth = control.width() - arrow.outerWidth() - parseInt(label.css('paddingLeft')) - parseInt(label.css('paddingLeft')); disableSelection(control) } select.addClass('selectBox').data('selectBox-control', control).data('selectBox-settings', settings).hide() }; var getOptions = function (select, type) { var options; var _getOptions = function (select, options) { select.children('OPTION, OPTGROUP').each(function () { if ($(this).is('OPTION')) { if ($(this).length > 0) { generateOptions($(this), options) } else { options.append('<li>\u00A0</li>') } } else { var optgroup = $('<li class="selectBox-optgroup" />'); optgroup.text($(this).attr('label')); options.append(optgroup); options = _getOptions($(this), options) } }); return options }; switch (type) { case 'inline': options = $('<ul class="selectBox-options" />'); options = _getOptions(select, options); options.find('A').bind('mouseover.selectBox', function (event) { addHover(select, $(this).parent()) }).bind('mouseout.selectBox', function (event) { removeHover(select, $(this).parent()) }).bind('mousedown.selectBox', function (event) { event.preventDefault(); if (!select.selectBox('control').hasClass('selectBox-active')) select.selectBox('control').focus() }).bind('mouseup.selectBox', function (event) { hideMenus(); selectOption(select, $(this).parent(), event) }); disableSelection(options); return options; case 'dropdown': options = $('<ul class="selectBox-dropdown-menu selectBox-options" />'); options = _getOptions(select, options); options.data('selectBox-select', select).css('display', 'none').appendTo('BODY').find('A').bind('mousedown.selectBox', function (event) { event.preventDefault(); if (event.screenX === options.data('selectBox-down-at-x') && event.screenY === options.data('selectBox-down-at-y')) { options.removeData('selectBox-down-at-x').removeData('selectBox-down-at-y'); hideMenus() } }).bind('mouseup.selectBox', function (event) { if (event.screenX === options.data('selectBox-down-at-x') && event.screenY === options.data('selectBox-down-at-y')) { return } else { options.removeData('selectBox-down-at-x').removeData('selectBox-down-at-y') } selectOption(select, $(this).parent()); hideMenus() }).bind('mouseover.selectBox', function (event) { addHover(select, $(this).parent()) }).bind('mouseout.selectBox', function (event) { removeHover(select, $(this).parent()) }); var classes = select.attr('class') || ''; if (classes !== '') { classes = classes.split(' '); for (var i in classes) options.addClass(classes[i] + '-selectBox-dropdown-menu') } disableSelection(options); return options } }; var getLabelClass = function (select) { var selected = $(select).find('OPTION:selected'); return ('selectBox-label ' + (selected.attr('class') || '')).replace(/\s+$/, '') }; var getLabelText = function (select) { var selected = $(select).find('OPTION:selected'); return selected.text() || '\u00A0' }; var setLabel = function (select) { select = $(select); var control = select.data('selectBox-control'); if (!control) return; control.find('.selectBox-label').attr('class', getLabelClass(select)).text(getLabelText(select)) }; var destroy = function (select) { select = $(select); var control = select.data('selectBox-control'); if (!control) return; var options = control.data('selectBox-options'); options.remove(); control.remove(); select.removeClass('selectBox').removeData('selectBox-control').data('selectBox-control', null).removeData('selectBox-settings').data('selectBox-settings', null).show() }; var refresh = function (select) { select = $(select); select.selectBox('options', select.html()) }; var showMenu = function (select) { select = $(select); var control = select.data('selectBox-control'), settings = select.data('selectBox-settings'), options = control.data('selectBox-options'); if (control.hasClass('selectBox-disabled')) return false; hideMenus(); var borderBottomWidth = isNaN(control.css('borderBottomWidth')) ? 0 : parseInt(control.css('borderBottomWidth')); options.width(control.innerWidth()).css({ top: control.offset().top + control.outerHeight() - borderBottomWidth, left: control.offset().left }); if (select.triggerHandler('beforeopen')) return false; var dispatchOpenEvent = function () { select.triggerHandler('open', { _selectBox: true }) }; switch (settings.menuTransition) { case 'fade': options.fadeIn(settings.menuSpeed, dispatchOpenEvent); break; case 'slide': options.slideDown(settings.menuSpeed, dispatchOpenEvent); break; default: options.show(settings.menuSpeed, dispatchOpenEvent); break } if (!settings.menuSpeed) dispatchOpenEvent(); var li = options.find('.selectBox-selected:first'); keepOptionInView(select, li, true); addHover(select, li); control.addClass('selectBox-menuShowing'); $(document).bind('mousedown.selectBox', function (event) { if ($(event.target).parents().andSelf().hasClass('selectBox-options')) return; hideMenus() }) }; var hideMenus = function () { if ($(".selectBox-dropdown-menu:visible").length === 0) return; $(document).unbind('mousedown.selectBox'); $(".selectBox-dropdown-menu").each(function () { var options = $(this), select = options.data('selectBox-select'), control = select.data('selectBox-control'), settings = select.data('selectBox-settings'); if (select.triggerHandler('beforeclose')) return false; var dispatchCloseEvent = function () { select.triggerHandler('close', { _selectBox: true }) }; if (settings) { switch (settings.menuTransition) { case 'fade': options.fadeOut(settings.menuSpeed, dispatchCloseEvent); break; case 'slide': options.slideUp(settings.menuSpeed, dispatchCloseEvent); break; default: options.hide(settings.menuSpeed, dispatchCloseEvent); break } if (!settings.menuSpeed) dispatchCloseEvent(); control.removeClass('selectBox-menuShowing') } else { $(this).hide(); $(this).triggerHandler('close', { _selectBox: true }); $(this).removeClass('selectBox-menuShowing') } }) }; var selectOption = function (select, li, event) { select = $(select); li = $(li); var control = select.data('selectBox-control'), settings = select.data('selectBox-settings'); if (control.hasClass('selectBox-disabled')) return false; if (li.length === 0 || li.hasClass('selectBox-disabled')) return false; if (select.attr('multiple')) { if (event.shiftKey && control.data('selectBox-last-selected')) { li.toggleClass('selectBox-selected'); var affectedOptions; if (li.index() > control.data('selectBox-last-selected').index()) { affectedOptions = li.siblings().slice(control.data('selectBox-last-selected').index(), li.index()) } else { affectedOptions = li.siblings().slice(li.index(), control.data('selectBox-last-selected').index()) } affectedOptions = affectedOptions.not('.selectBox-optgroup, .selectBox-disabled'); if (li.hasClass('selectBox-selected')) { affectedOptions.addClass('selectBox-selected') } else { affectedOptions.removeClass('selectBox-selected') } } else if ((isMac && event.metaKey) || (!isMac && event.ctrlKey)) { li.toggleClass('selectBox-selected') } else { li.siblings().removeClass('selectBox-selected'); li.addClass('selectBox-selected') } } else { li.siblings().removeClass('selectBox-selected'); li.addClass('selectBox-selected') } if (control.hasClass('selectBox-dropdown')) { control.find('.selectBox-label').text(li.text()) } var i = 0, selection = []; if (select.attr('multiple')) { control.find('.selectBox-selected A').each(function () { selection[i++] = $(this).attr('rel') }) } else { selection = li.find('A').attr('rel') } control.data('selectBox-last-selected', li); if (select.val() !== selection) { select.val(selection); setLabel(select); select.trigger('change') } return true }; var addHover = function (select, li) { select = $(select); li = $(li); var control = select.data('selectBox-control'), options = control.data('selectBox-options'); options.find('.selectBox-hover').removeClass('selectBox-hover'); li.addClass('selectBox-hover') }; var removeHover = function (select, li) { select = $(select); li = $(li); var control = select.data('selectBox-control'), options = control.data('selectBox-options'); options.find('.selectBox-hover').removeClass('selectBox-hover') }; var keepOptionInView = function (select, li, center) { if (!li || li.length === 0) return; select = $(select); var control = select.data('selectBox-control'), options = control.data('selectBox-options'), scrollBox = control.hasClass('selectBox-dropdown') ? options : options.parent(), top = parseInt(li.offset().top - scrollBox.position().top), bottom = parseInt(top + li.outerHeight()); if (center) { scrollBox.scrollTop(li.offset().top - scrollBox.offset().top + scrollBox.scrollTop() - (scrollBox.height() / 2)) } else { if (top < 0) { scrollBox.scrollTop(li.offset().top - scrollBox.offset().top + scrollBox.scrollTop()) } if (bottom > scrollBox.height()) { scrollBox.scrollTop((li.offset().top + li.outerHeight()) - scrollBox.offset().top + scrollBox.scrollTop() - scrollBox.height()) } } }; var handleKeyDown = function (select, event) { select = $(select); var control = select.data('selectBox-control'), options = control.data('selectBox-options'), settings = select.data('selectBox-settings'), totalOptions = 0, i = 0; if (control.hasClass('selectBox-disabled')) return; switch (event.keyCode) { case 8: event.preventDefault(); typeSearch = ''; break; case 9: case 27: hideMenus(); removeHover(select); break; case 13: if (control.hasClass('selectBox-menuShowing')) { selectOption(select, options.find('LI.selectBox-hover:first'), event); if (control.hasClass('selectBox-dropdown')) hideMenus() } else { showMenu(select) } break; case 38: case 37: event.preventDefault(); if (control.hasClass('selectBox-menuShowing')) { var prev = options.find('.selectBox-hover').prev('LI'); totalOptions = options.find('LI:not(.selectBox-optgroup)').length; i = 0; while (prev.length === 0 || prev.hasClass('selectBox-disabled') || prev.hasClass('selectBox-optgroup')) { prev = prev.prev('LI'); if (prev.length === 0) { if (settings.loopOptions) { prev = options.find('LI:last') } else { prev = options.find('LI:first') } } if (++i >= totalOptions) break } addHover(select, prev); selectOption(select, prev, event); keepOptionInView(select, prev) } else { showMenu(select) } break; case 40: case 39: event.preventDefault(); if (control.hasClass('selectBox-menuShowing')) { var next = options.find('.selectBox-hover').next('LI'); totalOptions = options.find('LI:not(.selectBox-optgroup)').length; i = 0; while (next.length === 0 || next.hasClass('selectBox-disabled') || next.hasClass('selectBox-optgroup')) { next = next.next('LI'); if (next.length === 0) { if (settings.loopOptions) { next = options.find('LI:first') } else { next = options.find('LI:last') } } if (++i >= totalOptions) break } addHover(select, next); selectOption(select, next, event); keepOptionInView(select, next) } else { showMenu(select) } break } }; var handleKeyPress = function (select, event) { select = $(select); var control = select.data('selectBox-control'), options = control.data('selectBox-options'); if (control.hasClass('selectBox-disabled')) return; switch (event.keyCode) { case 9: case 27: case 13: case 38: case 37: case 40: case 39: break; default: if (!control.hasClass('selectBox-menuShowing')) showMenu(select); event.preventDefault(); clearTimeout(typeTimer); typeSearch += String.fromCharCode(event.charCode || event.keyCode); options.find('A').each(function () { if ($(this).text().substr(0, typeSearch.length).toLowerCase() === typeSearch.toLowerCase()) { addHover(select, $(this).parent()); keepOptionInView(select, $(this).parent()); return false } }); typeTimer = setTimeout(function () { typeSearch = '' }, 1000); break } }; var enable = function (select) { select = $(select); select.attr('disabled', false); var control = select.data('selectBox-control'); if (!control) return; control.removeClass('selectBox-disabled') }; var disable = function (select) { select = $(select); select.attr('disabled', true); var control = select.data('selectBox-control'); if (!control) return; control.addClass('selectBox-disabled') }; var setValue = function (select, value) { select = $(select); select.val(value); value = select.val(); if (value === null) { value = select.children().first().val(); select.val(value) } var control = select.data('selectBox-control'); if (!control) return; var settings = select.data('selectBox-settings'), options = control.data('selectBox-options'); setLabel(select); options.find('.selectBox-selected').removeClass('selectBox-selected'); options.find('A').each(function () { if (typeof (value) === 'object') { for (var i = 0; i < value.length; i++) { if ($(this).attr('rel') == value[i]) { $(this).parent().addClass('selectBox-selected') } } } else { if ($(this).attr('rel') == value) { $(this).parent().addClass('selectBox-selected') } } }); if (settings.change) settings.change.call(select) }; var setOptions = function (select, options) { select = $(select); var control = select.data('selectBox-control'), settings = select.data('selectBox-settings'); switch (typeof (data)) { case 'string': select.html(data); break; case 'object': select.html(''); for (var i in data) { if (data[i] === null) continue; if (typeof (data[i]) === 'object') { var optgroup = $('<optgroup label="' + i + '" />'); for (var j in data[i]) { optgroup.append('<option value="' + j + '">' + data[i][j] + '</option>') } select.append(optgroup) } else { var option = $('<option value="' + i + '">' + data[i] + '</option>'); select.append(option) } } break } if (!control) return; control.data('selectBox-options').remove(); var type = control.hasClass('selectBox-dropdown') ? 'dropdown' : 'inline'; options = getOptions(select, type); control.data('selectBox-options', options); switch (type) { case 'inline': control.append(options); break; case 'dropdown': setLabel(select); $("BODY").append(options); break } }; var disableSelection = function (selector) { $(selector).css('MozUserSelect', 'none').bind('selectstart', function (event) { event.preventDefault() }) }; var generateOptions = function (self, options) { var li = $('<li />'), a = $('<a />'); li.addClass(self.attr('class')); li.data(self.data()); a.attr('rel', self.val()).text(self.text()); li.append(a); if (self.attr('disabled')) li.addClass('selectBox-disabled'); if (self.attr('selected')) li.addClass('selectBox-selected'); options.append(li) }; switch (method) { case 'control': return $(this).data('selectBox-control'); case 'settings': if (!data) return $(this).data('selectBox-settings'); $(this).each(function () { $(this).data('selectBox-settings', $.extend(true, $(this).data('selectBox-settings'), data)) }); break; case 'options': if (data === undefined) return $(this).data('selectBox-control').data('selectBox-options'); $(this).each(function () { setOptions(this, data) }); break; case 'value': if (data === undefined) return $(this).val(); $(this).each(function () { setValue(this, data) }); break; case 'refresh': $(this).each(function () { refresh(this) }); break; case 'enable': $(this).each(function () { enable(this) }); break; case 'disable': $(this).each(function () { disable(this) }); break; case 'destroy': $(this).each(function () { destroy(this) }); break; default: $(this).each(function () { init(this, method) }); break } return $(this) } }) })(jQuery);

//** Accordion Content script: By Dynamic Drive, at http://www.dynamicdrive.com
//** Created: Jan 7th, 08'. Last updated: June 7th, 2010 to v1.9

//Version 1.9: June 7th, 2010':
//**1) Ajax content support added, so a given header's content can be dynamically fetched from an external file and on demand.
//**2) Optimized script performance by caching header and content container references


var ddaccordion = {
    ajaxloadingmsg: 'Loading Content...', //customize HTML to output while Ajax content is being fetched (if applicable)

    headergroup: {}, //object to store corresponding header group based on headerclass value
    contentgroup: {}, //object to store corresponding content group based on headerclass value

    preloadimages: function ($images) {
        $images.each(function () {
            var preloadimage = new Image()
            preloadimage.src = this.src
        })
    },

    expandone: function (headerclass, selected) { //PUBLIC function to expand a particular header
        this.toggleone(headerclass, selected, "expand")
    },

    collapseone: function (headerclass, selected) { //PUBLIC function to collapse a particular header
        this.toggleone(headerclass, selected, "collapse")
    },

    expandall: function (headerclass) { //PUBLIC function to expand all headers based on their shared CSS classname
        var $headers = this.headergroup[headerclass]
        this.contentgroup[headerclass].filter(':hidden').each(function () {
            $headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
        })
    },

    collapseall: function (headerclass) { //PUBLIC function to collapse all headers based on their shared CSS classname
        var $headers = this.headergroup[headerclass]
        this.contentgroup[headerclass].filter(':visible').each(function () {
            $headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
        })
    },

    toggleone: function (headerclass, selected, optstate) { //PUBLIC function to expand/ collapse a particular header
        var $targetHeader = this.headergroup[headerclass].eq(selected)
        var $subcontent = this.contentgroup[headerclass].eq(selected)
        if (typeof optstate == "undefined" || optstate == "expand" && $subcontent.is(":hidden") || optstate == "collapse" && $subcontent.is(":visible"))
            $targetHeader.trigger("evt_accordion")
    },

    ajaxloadcontent: function ($targetHeader, $targetContent, config, callback) {
        var ajaxinfo = $targetHeader.data('ajaxinfo')

        function handlecontent(content) { //nested function
            if (content) { //if ajax content has loaded
                ajaxinfo.cacheddata = content //remember ajax content 
                ajaxinfo.status = "cached" //set ajax status to cached
                if ($targetContent.queue("fx").length == 0) { //if this content isn't currently expanding or collapsing
                    $targetContent.hide().html(content) //hide loading message, then set sub content's HTML to ajax content
                    ajaxinfo.status = "complete" //set ajax status to complete
                    callback() //execute callback function- expand this sub content
                }
            }
            if (ajaxinfo.status != "complete") {
                setTimeout(function () { handlecontent(ajaxinfo.cacheddata) }, 100) //call handlecontent() again until ajax content has loaded (ajaxinfo.cacheddata contains data)
            }
        } //end nested function

        if (ajaxinfo.status == "none") { //ajax data hasn't been fetched yet
            $targetContent.html(this.ajaxloadingmsg)
            $targetContent.slideDown(config.animatespeed)
            ajaxinfo.status = "loading" //set ajax status to "loading"
            $.ajax({
                url: ajaxinfo.url, //path to external menu file
                error: function (ajaxrequest) {
                    handlecontent('Error fetching content. Server Response: ' + ajaxrequest.responseText)
                },
                success: function (content) {
                    content = (content == "") ? " " : content //if returned content is empty, set it to "space" is content no longer returns false/empty (hasn't loaded yet)
                    handlecontent(content)
                }
            })
        }
        else if (ajaxinfo.status == "loading")
            handlecontent(ajaxinfo.cacheddata)
    },

    expandit: function ($targetHeader, $targetContent, config, useractivated, directclick, skipanimation) {
        var ajaxinfo = $targetHeader.data('ajaxinfo')
        if (ajaxinfo) { //if this content should be fetched via Ajax
            if (ajaxinfo.status == "none" || ajaxinfo.status == "loading")
                this.ajaxloadcontent($targetHeader, $targetContent, config, function () { ddaccordion.expandit($targetHeader, $targetContent, config, useractivated, directclick) })
            else if (ajaxinfo.status == "cached") {
                $targetContent.html(ajaxinfo.cacheddata)
                ajaxinfo.cacheddata = null
                ajaxinfo.status = "complete"
            }
        }
        this.transformHeader($targetHeader, config, "expand")
        $targetContent.slideDown(skipanimation ? 0 : config.animatespeed, function () {
            config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)
            if (config.postreveal == "gotourl" && directclick) { //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
                var targetLink = ($targetHeader.is("a")) ? $targetHeader.get(0) : $targetHeader.find('a:eq(0)').get(0)
                if (targetLink) //if this header is a link
                    setTimeout(function () { location = targetLink.href }, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
            }
        })
    },

    collapseit: function ($targetHeader, $targetContent, config, isuseractivated) {
        this.transformHeader($targetHeader, config, "collapse")
        $targetContent.slideUp(config.animatespeed, function () { config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated) })
    },

    transformHeader: function ($targetHeader, config, state) {
        $targetHeader.addClass((state == "expand") ? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state == "expand") ? config.cssclass.collapse : config.cssclass.expand)
        if (config.htmlsetting.location == 'src') { //Change header image (assuming header is an image)?
            $targetHeader = ($targetHeader.is("img")) ? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
            $targetHeader.attr('src', (state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
        }
        else if (config.htmlsetting.location == "prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
            $targetHeader.find('.accordprefix').html((state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse)
        else if (config.htmlsetting.location == "suffix")
            $targetHeader.find('.accordsuffix').html((state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse)
    },

    urlparamselect: function (headerclass) {
        var result = window.location.search.match(new RegExp(headerclass + "=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
        if (result != null)
            result = RegExp.$1.split(',')
        return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
    },

    getCookie: function (Name) {
        var re = new RegExp(Name + "=[^;]+", "i") //construct RE to search for target name/value pair
        if (document.cookie.match(re)) //if cookie found
            return document.cookie.match(re)[0].split("=")[1] //return its value
        return null
    },

    setCookie: function (name, value) {
        document.cookie = name + "=" + value + "; path=/"
    },

    init: function (config) {
        document.write('<style type="text/css">\n')
        document.write('.' + config.contentclass + '{display: none}\n') //generate CSS to hide contents
        document.write('a.hiddenajaxlink{display: none}\n') //CSS class to hide ajax link
        document.write('<\/style>')
        jQuery(document).ready(function ($) {
            ddaccordion.urlparamselect(config.headerclass)
            var persistedheaders = ddaccordion.getCookie(config.headerclass)
            ddaccordion.headergroup[config.headerclass] = $('.' + config.headerclass) //remember header group for this accordion
            ddaccordion.contentgroup[config.headerclass] = $('.' + config.contentclass) //remember content group for this accordion
            var $headers = ddaccordion.headergroup[config.headerclass]
            var $subcontents = ddaccordion.contentgroup[config.headerclass]
            config.cssclass = { collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
            config.revealtype = config.revealtype || "click"
            config.revealtype = config.revealtype.replace(/mouseover/i, "mouseenter")
            if (config.revealtype == "clickgo") {
                config.postreveal = "gotourl" //remember added action
                config.revealtype = "click" //overwrite revealtype to "click" keyword
            }
            if (typeof config.togglehtml == "undefined")
                config.htmlsetting = { location: "none" }
            else
                config.htmlsetting = { location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
            config.oninit = (typeof config.oninit == "undefined") ? function () { } : config.oninit //attach custom "oninit" event handler
            config.onopenclose = (typeof config.onopenclose == "undefined") ? function () { } : config.onopenclose //attach custom "onopenclose" event handler
            var lastexpanded = {} //object to hold reference to last expanded header and content (jquery objects)
            var expandedindices = ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders != null) ? persistedheaders : config.defaultexpanded)
            if (typeof expandedindices == 'string') //test for string value (exception is config.defaultexpanded, which is an array)
                expandedindices = expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
            if (expandedindices.length == 1 && expandedindices[0] == "-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
                expandedindices = []
            if (config["collapseprev"] && expandedindices.length > 1) //only allow one content open?
                expandedindices = [expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
            if (config["onemustopen"] && expandedindices.length == 0) //if at least one content should be open at all times and none are, open 1st header
                expandedindices = [0]
            $headers.each(function (index) { //loop through all headers
                var $header = $(this)
                if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $header.html() != "") { //add a SPAN element to header depending on user setting and if header is a container tag
                    $('<span class="accordprefix"></span>').prependTo(this)
                    $('<span class="accordsuffix"></span>').appendTo(this)
                }
                $header.attr('headerindex', index + 'h') //store position of this header relative to its peers
                $subcontents.eq(index).attr('contentindex', index + 'c') //store position of this content relative to its peers
                var $subcontent = $subcontents.eq(index)
                var $hiddenajaxlink = $subcontent.find('a.hiddenajaxlink:eq(0)') //see if this content should be loaded via ajax
                if ($hiddenajaxlink.length == 1) {
                    $header.data('ajaxinfo', { url: $hiddenajaxlink.attr('href'), cacheddata: null, status: 'none' }) //store info about this ajax content inside header
                }
                var needle = (typeof expandedindices[0] == "number") ? index : index + '' //check for data type within expandedindices array- index should match that type
                if (jQuery.inArray(needle, expandedindices) != -1) { //check for headers that should be expanded automatically (convert index to string first)
                    ddaccordion.expandit($header, $subcontent, config, false, false, !config.animatedefault) //3rd last param sets 'isuseractivated' parameter, 2nd last sets isdirectclick, last sets skipanimation param
                    lastexpanded = { $header: $header, $content: $subcontent }
                }  //end check
                else {
                    $subcontent.hide()
                    config.onopenclose($header.get(0), parseInt($header.attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
                    ddaccordion.transformHeader($header, config, "collapse")
                }
            })
            $headers.bind("evt_accordion", function (e, isdirectclick) { //assign CUSTOM event handler that expands/ contacts a header
                var $subcontent = $subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
                if ($subcontent.css('display') == "none") {
                    ddaccordion.expandit($(this), $subcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
                    if (config["collapseprev"] && lastexpanded.$header && $(this).get(0) != lastexpanded.$header.get(0)) { //collapse previous content?
                        ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
                    }
                    lastexpanded = { $header: $(this), $content: $subcontent }
                }
                else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0) != lastexpanded.$header.get(0)) {
                    ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
                }
            })
            $headers.bind(config.revealtype, function () {
                if (config.revealtype == "mouseenter") {
                    clearTimeout(config.revealdelay)
                    var headerindex = parseInt($(this).attr("headerindex"))
                    config.revealdelay = setTimeout(function () { ddaccordion.expandone(config["headerclass"], headerindex) }, config.mouseoverdelay || 0)
                }
                else {
                    $(this).trigger("evt_accordion", [true]) //last parameter indicates this is a direct click on the header
                    return false //cancel default click behavior
                }
            })
            $headers.bind("mouseleave", function () {
                clearTimeout(config.revealdelay)
            })
            config.oninit($headers.get(), expandedindices)
            $(window).bind('unload', function () { //clean up and persist on page unload
                $headers.unbind()
                var expandedindices = []
                $subcontents.filter(':visible').each(function (index) { //get indices of expanded headers
                    expandedindices.push($(this).attr('contentindex'))
                })
                if (config.persiststate == true && $headers.length > 0) { //persist state?
                    expandedindices = (expandedindices.length == 0) ? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
                    ddaccordion.setCookie(config.headerclass, expandedindices)
                }
            })
        })
    }
}

//preload any images defined inside ajaxloadingmsg variable
ddaccordion.preloadimages(jQuery(ddaccordion.ajaxloadingmsg).filter('img'))

ddaccordion.init({
    headerclass: "handy", //Shared CSS class name of headers group that are expandable
    contentclass: "faqInfo", //Shared CSS class name of contents group
    revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
    mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
    collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
    defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
    onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
    animatedefault: false, //Should contents open by default be animated into view?
    persiststate: true, //persist state of opened contents within browser session?
    toggleclass: ["open", "close"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
    togglehtml: ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
    animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
    oninit: function (headers, expandedindices) { //custom code to run when headers have initalized
        //do nothing
    },
    onopenclose: function (header, index, state, isuseractivated) { //custom code to run whenever a header is opened or closed
        //do nothing
    }
})


function newsletterSignup() {
    // Test fields
    var strRegex = "/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

    valid = true;

    if ($('#txtNewsName').val() == "") {
        $('#txtNewsName').parent(".newsName").addClass("newsError");
        valid = false;
    }
    else {
        $('#txtNewsName').parent(".newsName").removeClass("newsError");
        valid = true;
    }

    if ($('#txtNewsEmail').val() == "") {
        valid = false;
        $('#txtNewsEmail').parent(".newsEmail").addClass("newsError");
    }
    else if (($('#txtNewsEmail').val() == "") || !(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test($('#txtNewsEmail').val()))) {
        valid = false;
        $('#txtNewsEmail').parent(".newsEmail").addClass("newsError");
    }
    else {
        $('#txtNewsEmail').parent(".newsEmail").removeClass("newsError");
        valid = true;
    }
    if (valid) {
        jQuery.post("/base/newsletterSignup/signup.aspx", {
            txtNewsName: $('#txtNewsName').val(),
            txtNewsEmail: $('#txtNewsEmail').val()
        },
        function (data) {
            if (data != "False") {
                $('#signupNewsletterError').html("<p class='error'>Thank you for signing up to the Caravan Pro newsletter.</p>");
                $('#nlSignUpForm').hide();
            }
            else {
                $('#signupNewsletterError').html("<p class='error'>Sorry, an error has occurred. Please try again later.</p>");
            }
        });
    }
    else {
    	$('#signupNewsletterError').html("<p class='error'>Please fill in the required fields highlighted below.</p>");
    }
}

$(function () {
    $('.btnFreightCalculator').click(function () {
        $('#overlayFreightCalculator').modal({
            overlayClose: true,
            minHeight: 410
        });
        $('.selectBox').selectBox();
        return false;
    });
});

