var loading = "n";
jQuery(document).ready(function() {
	if($("#printMe").get(0)) {
		window.print();
		return false;
 	};
	$("#strapline").click(function(){window.location = "index.php"});
	$().preparePrompts();
	if($("#searchDropDownSource").get(0)) {
		$().createDropDown("#searchDropDownSource", "#searchFieldSet", "searchTarget");
	};
	if($("#latestImagesList").get(0)) {
		$().loadLatest("0");
		$("#latestImages .scrollable").scrollable({
			size: 5, 
			loop: true
		});
		if($("#latestDropDownSource").get(0)) {
			$().createDropDown("#latestDropDownSource", "#latestFieldSet", "latestTarget");
			$().loadPressReleases("0");
			$().createDropDown("#releasesDropDownSource", "#releasesFieldSet", "releasesTarget");
		}
	};
	if($("#serviceDescription").get(0)) {
		$("#serviceDescription .scrollable").scrollable({
			size: 1, 
			loop: true
		}).navigator();
	};
	$(".button").button();
	$(".registerHover").hoverIntent({    
		sensitivity: 1, 
		interval: 100, 
		over: function() {$("#registerSelect").show();}, 
		out: function() {}
	});
	$("#categoryMenuHome").hoverIntent({    
		sensitivity: 1, 
		interval: 300, 
		over: function() {$("#subMenu").show()}, 
		out: function() {}
	});
	$("#jornoPromo").hoverIntent({    
		sensitivity: 1, 
		over: function() {$("#companyPromoDetails").hide(); $("#jornoPromoDetails").show(); $("#jornoPromo h5 a").addClass("stackTop"); $("#jornoPromo .promoBlurb").addClass("stackTop");}, 
		out: function() {}
	});
	$("#companyPromo").hoverIntent({    
		sensitivity: 1, 
		over: function() {$("#jornoPromoDetails").hide(); $("#companyPromoDetails").show(); $("#companyPromo h5 a").addClass("stackTop"); $("#companyPromo .promoBlurb").addClass("stackTop");}, 
		out: function() {}
	});
//	$("li.fader").hoverIntent(function() {
//		$("#jornoPromoDetails").hide();
//		$("#jornoPromo h1 a").removeClass("stackTop");
//		$("#jornoPromo .promoBlurb").removeClass("stackTop");
//		$("#companyPromoDetails").hide();
//		$("#companyPromo h1 a").removeClass("stackTop");
//		$("#companyPromo .promoBlurb").removeClass("stackTop");
//		$("#subMenu").hide();
//		$("#subMenu").attr("class", "");
//		$("#subMenu").empty();
//		$("#subMenu").attr("class", $(this).attr("id") + " borderBottom");
//		$("#subMenu").show();
//		$("#subMenu").load("../ajax/aj_submenu.php", {menu: $(this).attr("id")}, function() {
//			$().preparePrompts();
//			$().makeDraggable("#header");
//		});
//	}, function(){});
	$("#closerTop, #closerLeft, #closerRight, #closerBottom").mouseover(function() {
		$("#subMenu").hide();
		$("#registerSelect").hide();
	});
	$("#subMenu").mouseout(function(i) {
		if(i.pageY > 415)
			$("#subMenu").hide();
	});
	$("#closerLeft, #closerRight, #closerPromos").mouseover(function() {
		$("#jornoPromoDetails").hide();
		$("#jornoPromo h5 a").removeClass("stackTop");
		$("#jornoPromo .promoBlurb").removeClass("stackTop");
		$("#companyPromoDetails").hide();
		$("#companyPromo h5 a").removeClass("stackTop");
		$("#companyPromo .promoBlurb").removeClass("stackTop");
	});
	$("#closerJourno").mouseover(function() {
		$("#jornoPromoDetails").hide();
		$("#jornoPromo h5 a").removeClass("stackTop");
		$("#jornoPromo .promoBlurb").removeClass("stackTop");
	});
	$("#closerCompany").mouseover(function() {
		$("#companyPromoDetails").hide();
		$("#companyPromo h5 a").removeClass("stackTop");
		$("#companyPromo .promoBlurb").removeClass("stackTop");
	});
	$("#categoryMenu .level1").click(function() {
		if(location.pathname != "/browser.php" || $("#industry_0").get(0)) {
			path = window.location.protocol + "//" + window.location.host + "/browser.php?cid=" + $(this).attr("id");
			if($("#clientMenu").get(0))
				path = path + "&ccid=" + $("#clientMenu").html();
			window.location.replace(path);
		}
		else {
			$("#searchWithin").show();
			$("#searchWithinSubmit").show();
			$("#searchString").val($("#searchString").attr("title"));
			$("#searchWithin").val($("#searchWithin").attr("title"));
			$("#mainSearch").val($("#mainSearch").attr("title"));
			$("#categoryMenu .subon").removeClass("subon");
			$("#categoryMenu .show").addClass("hidden");
			$("#categoryMenu .show").removeClass("show");
			$("#categoryMenu .on").removeClass("on");
			$showMenu = "#menu_" + $(this).attr("id");
			$($showMenu).removeClass("hidden");
			$($showMenu).addClass("show");
			$(this).addClass("on");
			breadcrumbArray = $("#breadcrumbs").html().split(" &gt; ");
			$("#breadcrumbs").html(breadcrumbArray[0] + " &gt; " + breadcrumbArray[1]);
			if($("#categoryMenu .on").html() != "ALL")
				$("#breadcrumbs").append(" &gt; <a href=\"browser.php?cid=" + $(this).attr("id") + "\">" + $("#categoryMenu .on").html() + "</a>");
			if($("#pressOfficeClient").get(0))
				$("#breadcrumbs").append(" &gt; <a href=\"browser.php?ccid=" + $("#pressOfficeId").html() + "\">" + $("#pressOfficeClient").html() + "</a>");
			$().loadBrowser("0", "", "", "", "", "", "", "", "y", "y");
		}
	});
	$("#categoryMenu li .level2").click(function() {
		if(location.pathname != "/browser.php") {
			path = window.location.protocol + "//" + window.location.host + "/browser.php?cid=" + $("span.on").attr("id") + "&scid=" + $(this).attr("id").substr(1);
			if($("#clientMenu").get(0))
				path = path + "&ccid=" + $("#clientMenu").html();
			window.location.replace(path);
		}
		else {
			$("#searchString").val($("#searchString").attr("title"));
			$("#searchWithin").val($("#searchWithin").attr("title"));
			$("#categoryMenu .subon").removeClass("subon");
			$(this).addClass("subon");
			breadcrumbArray = $("#breadcrumbs").html().split(" &gt; ");
			$("#breadcrumbs").html(breadcrumbArray[0] + " &gt; " + breadcrumbArray[1] + " &gt; " + breadcrumbArray[2] + " &gt; <a href=\"browser.php?scid=" + $(this).attr("id") + "\">" + $(this).html() + "</a>");
			if($("#pressOfficeClient").get(0))
				$("#breadcrumbs").append(" &gt; <a href=\"browser.php?ccid=" + $("#pressOfficeId").html() + "\">" + $("#pressOfficeClient").html() + "</a>");
			$().loadBrowser("0", "", "", "", "", "", "", "", "y", "y");
		}
	});
	if($("#pressOfficeClient").get(0) && $("#categoryMenu .on").html() == "ALL")
		$("#breadcrumbs").append(" &gt; <a href=\"browser.php?ccid=" + $("#pressOfficeId").html() + "\">" + $("#pressOfficeClient").html() + "</a>");
	$("#miniBasket").droppable({
		tolerance: "touch", 
		activate: function(event, ui) {
			$(this).addClass("basketActive");
		}, 
		deactivate: function(event, ui) {
			$(this).removeClass("basketActive");
		}, 
		over: function(event, ui) {
			$(this).addClass("basketOver");
		}, 
		out: function(event, ui) {
			$(this).removeClass("basketOver");
		}, 
		drop: function(event, ui) {
			$(this).removeClass("basketOver");
			$().basket("add", $(ui.draggable).attr("id"), "mini");
		}
	});
	$("#basketOpen, #openBasket, #email").click(function() {
		if($("#quickFormConfirmation").html() != "")
			$("#quickFormConfirmation").addClass("hidden");
		$("#quickBasket").removeClass("hidden");
		$().basket("show", "", "mid");
	});
	if($(".autoLoadBasket").get(0)) {
		$().basket("show", "", "mid");
	}
	$("#basketClose").click(function() {
		$("#quickBasket").addClass("hidden");
		$().basket("show", "", "mini");
	});
	$("#quickMonthly").click(function() {
		if($(this).attr("checked") == true)
			$("#formDay").addClass("hidden");
		else
			$("#formDay").removeClass("hidden");			
	});
	$("#quickResearching").click(function() {
		if($(this).attr("checked") == true) {
			$("#formDate").addClass("hidden");
			$("#formResearching").removeClass("hidden");
			$("#formReCheckbox").addClass("padout");
		}
		else {
			$("#formDate").removeClass("hidden");
			$("#formResearching").addClass("hidden");
			$("#formReCheckbox").removeClass("padout");
		}
	});
	$("#basketButton").click(function() {
		if($("#quickMonthly").attr("checked") == true)
			monthly = "y";
		else
			monthly = "";
		if($("#quickResearching").attr("checked") == true)
			researching = "y";
		else
			researching = "";
		if($("#quickFromEmail").get(0))
			femail = $("#quickFromEmail").val();
		else
			femail = "";
		if($("#quickEmail").val() == "" || ($("#quickClient").val() == "" && (researching == "" && $("#quickPublication").val() == "") || (researching == "y" && $("#quickWhat").val() == "")))
			alert("Please complete all required fields.");
		else {
			var todaysDate = new Date();
			thisYear = todaysDate.getYear();
			if(thisYear < 1000)
				thisYear = thisYear + 1900;
			if(researching != "y" & ((parseFloat($("#formYear").val()) == thisYear && parseFloat($("#formMonth").val()) == (parseFloat(todaysDate.getMonth()) + 1) && parseFloat($("#formDay").val()) < todaysDate.getDate()) || (parseFloat($("#formYear").val()) == thisYear && parseFloat($("#formMonth").val()) < (parseFloat(todaysDate.getMonth()) + 1)))) {
				alert("Please select a valid issue date or select 'Just researching'.");
			}
			else if(researching == "y" && $("#quickWhat").val() == "") {
				alert("Please let us know what you are researching.");
			}
			else {
				$("#basketButton").attr("value", "Sending...");
				$("#basketButton").attr("disabled", true);
				$("#quickFormConfirmation").load("../ajax/aj_email_images.php", {
						email: $("#quickEmail").val(), 
						femail: femail, 
						publication: $("#quickPublication").val(), 
						subject: $("#quickSubject").val(), 
						what: $("#quickWhat").val(), 
						message: $("#quickMessage").val(), 
						resolution: $("#resolution input[type='radio']:checked").val(), 
						yyyy: $("#formYear").val(), 
						mm: $("#formMonth").val(), 
						dd: $("#formDay").val(), 
						monthly: monthly, 
						researching: researching, 
						ccid: $("#quickClient").val()
					}, function() {
					$("#quickFormConfirmation").removeClass("hidden");
					$().basket("empty", "", "mid");
					$("#basketButton").attr("value", "Send email");
					$("#basketButton").attr("disabled", false);
				});
			}
		}
	});
	$("#downloadNow").click(function() {
		if($("#quickMonthly").attr("checked") == true)
			monthly = "y";
		else
			monthly = "";
		if($("#quickResearching").attr("checked") == true)
			researching = "y";
		else
			researching = "";
		var todaysDate = new Date();
		thisYear = todaysDate.getYear();
		if(thisYear < 1000)
			thisYear = thisYear + 1900;
		if(researching != "y" & ((parseFloat($("#formYear").val()) == thisYear && parseFloat($("#formMonth").val()) == (parseFloat(todaysDate.getMonth()) + 1) && parseFloat($("#formDay").val()) < todaysDate.getDate()) || (parseFloat($("#formYear").val()) == thisYear && parseFloat($("#formMonth").val()) < (parseFloat(todaysDate.getMonth()) + 1)))) {
			alert("Please select a valid issue date or select 'Just researching'.");
		}
		else if(researching == "y" && $("#quickWhat").val() == "") {
			alert("Please let us know what you are researching.");
		}
		else {
			$("#downloadNow").attr("value", "Sending...");
			$("#downloadNow").attr("disabled", true);
			$("#downloadNowConfirmation").load("../ajax/aj_email_images.php", {
					pid: $("#quickPid").val(), 
					email: $("#quickEmail").val(), 
					publication: $("#quickPublication").val(), 
					subject: $("#quickSubject").val(), 
					what: $("#quickWhat").val(), 
					message: $("#quickMessage").val(), 
					resolution: $("#resolution").val(), 
					yyyy: $("#formYear").val(), 
					mm: $("#formMonth").val(), 
					dd: $("#formDay").val(), 
					monthly: monthly, 
					researching: researching
				}, function() {
				$("#thickBoxContainer .bodyForm").addClass("hidden");
				$("#downloadNowConfirmation").removeClass("hidden");
				$("#downloadNowTable").removeClass("hidden");
				$("#downloadNow").attr("value", "Download");
				$("#downloadNow").attr("disabled", false);
				document.location = $("#downloadURL").val();
			});
		}
	});
	if($("#browserContainer").get(0)) {
		$().loadBrowser("0", "", "", "", "", "", "", "", "y", "y");
		$(window).scroll(function() {
			if(parseFloat($("#from").html()) < parseFloat($("#count").html())) {
   				if($(window).scrollTop() >= ($(document).height() - $(window).height()) - 460 && $(window).scrollTop() <= ($(document).height() - $(window).height()) - 360 && loading == "n") {
					loading = "y";
					$().loadBrowser($("#from").html(), "", "", "", "", "", "", "", "", "y");
				}
			}
		});
	}
	$().makeDraggable("parent");
	$("#orderBy, #clientFilter").change(function() {
		$().loadBrowser("0", "", $("#orderBy").val(), "", "", "", $("#clientFilter").val(), "", "y", "y");
	});
	$("#filterSubmit").click(function() {
		$().loadBrowser("0", "", "", $("#searchString").val(), "", "", "", "", "y", "y");
	});
	$("#browseNext").click(function() {
		if(parseFloat($("#from").html()) < parseFloat($("#count").html())) {
			$().loadBrowser($("#from").html(), "", "", "", "", "", "", "", "y", "n");
			$("#viewing").html($("#from").html());
		}
	});
	$("#browsePrev").click(function() {
		if(parseFloat($("#viewing").html()) > 1) {
			startFrom = parseFloat($("#viewing").html()) - 24;
			$().loadBrowser(startFrom, "", "", "", "", "", "", "", "y", "n");
			$("#viewing").html(startFrom);
		}
	});
	$("#newsletterSubmit").click(function() {
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
		if($("#newsletterName").val() == "" || $("#newsletterName").val() == "name" || $("#newsletterEmail").val() == "" || $("#newsletterEmail").val() == "email" || $("#newsletterPublication").val() == "" || $("#newsletterPublication").val() == "publication/company" || emailPattern.test($("#newsletterEmail").val()) == false)
			alert("Please provide your name, a valid email address and the publication or company you work for.");
		else {
			$("#newsletterSignUp form").addClass("hidden");
			$("#newsletterConfirmation").load("../ajax/aj_newsletter_subscribe.php", {
				email: $("#newsletterEmail").val(), 
				name: $("#newsletterName").val(), 
				publication: $("#newsletterPublication").val(), 
				type: $("input[name='type']:checked").val()
			}, function() {
				$("#newsletterConfirmation").removeClass("hidden");
			});
		}
	});
	$("#requestSubmit").click(function() {
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
		if($("#requestName").val() == "" || $("#requestPublication").val() == "" || $("#requestRequest").val() == "" || $("#requestEmail").val() == "email" || emailPattern.test($("#requestEmail").val()) == false)
			alert("Please provide your name, a valid email address, the publication and your request.");
		else {
			var iids = "";
			$("#iids :checked").each(function() {iids += "|" + $(this).val()});
			$("#request form").addClass("hidden");
			$("#requestConfirmation").load("../ajax/aj_send_request.php", {
				iids: iids, 
				remail: $("#requestEmail").val(), 
				rname: $("#requestName").val(), 
				rphone: $("#requestPhone").val(), 
				rpublication: $("#requestPublication").val(), 
				rissue: $("#requestPhone").val(), 
				request: $("#requestRequest").val(), 
				ddate: $("#theYear").val() + "-" + $("#theMonth").val() + "-" + $("#theDay").val(), 
				owndb: $("#owndb").val(), 
				ownlist: $("#ownlist").val()
			}, function() {
				$("#requestConfirmation").removeClass("hidden");
			});
		}
	});
	$("#requestToUpload").click(function() {
		var iids = "";
		$("#iids :checked").each(function() {iids += "|" + $(this).val()});
		$("#requestConfirmation").load("../ajax/aj_send_request.php", {
			saveOnly: "y", 
			iids: iids, 
			requestEmail: $("#requestEmail").val(), 
			requestName: $("#requestName").val(), 
			requestPhone:$("#requestPhone").val(), 
			requestPublication: $("#requestPublication").val(), 
			requestPhone: $("#requestPhone").val(), 
			requestRequest: $("#requestRequest").val(), 
			theYear: $("#theYear").val(), 
			theMonth: $("#theMonth").val(), 
			theDay: $("#theDay").val()
		}, function() {
			window.location.replace("uploader.php");
		});
	});
	$("#searchWithinSubmit").click(function() {
		if($("#searchWithin").val() != $("#searchWithin").attr("title")) {
			$searchString = $("#searchWithin").val();
			$().loadBrowser("0", "", "", $searchString, "", "", "", "", "y", "y");
			$("#breadcrumbs").append(" &gt; Containing \"" + $("#searchWithin").val() + "\"");
		}
	});
	if($("#searchWithin").get(0)) {
		if($("#searchWithin").val() != $("#searchWithin").attr("title")) {
			$breadcrumbs = "";
			if($("#categoryMenu .on").html() != "ALL") {
				$breadcrumbs = " &gt; <a href=\"browser.php?cid=" + $("#categoryMenu li .on").attr("id") + "\">" + $("#categoryMenu li .on").html() + "</a>";
				if($("#categoryMenu li .subon").get(0))
					$breadcrumbs += " &gt; <a href=\"browser.php?scid=" + $("#categoryMenu li .subon").attr("id") + "\">" + $("#categoryMenu li .subon").html() + "</a>";
			}
			if($("#pressOfficeClient").get(0) && $("#categoryMenu .on").html() != "ALL")
				$breadcrumbs += " &gt; <a href=\"browser.php?ccid=" + $("#pressOfficeClientId").html() + "\">" + $("#pressOfficeClient").html() + "</a>";
			$breadcrumbs += " &gt; Containing \"" + $("#searchWithin").val() + "\"";
			$("#breadcrumbs").append($breadcrumbs);
		}
	}
	if($("#releaseLoftResults").get(0)) {
		$().loadReleaseLoft("y", "0");
		$(window).scroll(function() {
			if(parseFloat($("#from").html()) < parseFloat($("#count").html())) {
   				if($(window).scrollTop() >= ($(document).height() - $(window).height()) - 460 && $(window).scrollTop() <= ($(document).height() - $(window).height()) - 360)
					$().loadReleaseLoft("", "");
			}
		});
	}
	if($("#featureLoftResults").get(0)) {
		$().loadFeatureLoft("y", "0");
		$(window).scroll(function() {
			if(parseFloat($("#from").html()) < parseFloat($("#count").html())) {
   				if($(window).scrollTop() >= ($(document).height() - $(window).height()) - 460 && $(window).scrollTop() <= ($(document).height() - $(window).height()) - 360)
					$().loadFeatureLoft("", "");
			}
		});
	}
	$(".basketAdd").click(function() {
		imageAddArray = $(this).attr("id").split("|");
		$().basket("add", imageAddArray[0], "mini");
		$("#addConfirmImage").html("<img src=\"" + imageAddArray[1] + "\" width=\"65\" height=\"65\" class=\"borderAll\" />");
		$("#addConfirm").fadeIn(1);
		$("#addConfirm").delay(1000).fadeOut(1000);
		$(this).html("ADDED");
	});
	$(".basketAddFromPrevious").click(function() {
		$().basket("add", $(this).attr("id"), "previous");
		$(this).removeClass("basketAddFromPrevious");
		$(this).html("Added");
	});
	$("#emailPRSubmit").click(function() {
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
		if($("#emailPRMessage").val() == "" || $("#emailPREmail").val() == "email" || emailPattern.test($("#emailPREmail").val()) == false)
			alert("Please provide a message and a valid email address.");
		else {
			var iids = "";
			$("#iids :checked").each(function() {iids += "|" + $(this).val()});
			$("#thickBoxContainer form").addClass("hidden");
			$("#emailPRConfirmation").load("../ajax/aj_send_email_pr.php", {
				ccid: $("#ccid").val(), 
				rid: $("#rid").val(), 
				pid: $("#pid").val(), 
				email: $("#emailPREmail").val(), 
				message: $("#emailPRMessage").val()
			}, function() {
				$("#emailPRConfirmation").removeClass("hidden");
			});
		}
	});
	$("#clientSelect").change(function() {
		$("#browseByClient").submit();
	});
	$("#industryCheckboxes .industryCheckall").click(function() {
		industryArray = $(this).attr("id").split("_");
		if($("#industry_" + industryArray[1] + ":checked").val()) {
			$("#catRow" + industryArray[1] + " INPUT[type='checkbox']").attr("disabled", true);
			$("#catRow" + industryArray[1] + " INPUT[type='checkbox']").attr("checked", true);
		} else {
			$("#catRow" + industryArray[1] + " INPUT[type='checkbox']").attr("disabled", false);
			$("#catRow" + industryArray[1] + " INPUT[type='checkbox']").attr("checked", false);
		}
	});
	if($("#directoryResults").get(0)) {
		$().loadDirectory();
	}
	$("#directoryIndex span").click(function() {
		$("#directoryIndex span.on").removeClass("on");
		$(this).addClass("on");
		$().loadDirectory();
	});
	if($(".datepicker").get(0)) {
		$(".datepicker").datepicker({
			changeMonth: true, 
			changeYear: true, 
			dateFormat: "dd/mm/yy"
		});
	};
	$(".tooltip, .tooltip2").tooltip();
	// **IE7 z-index fix
	if($.browser.msie && $.browser.version == "7.0" && !$(".upgradeButton").get(0)) {
		var zIndexNumber = 1000;
		$("div").each(function() {
			$(this).css("z-index", zIndexNumber);
			zIndexNumber -= 10;
		});
	};
	$("#ownSchema table thead th").draggable({
		helper: "clone", 
		opacity: 0.75, 
		start: function(event, ui) {
			$(ui.helper).css("width", $(this).width() + "px");
			$(ui.helper).addClass("selected");
			$(ui.helper).css("cursor", "move");
		}
	});
	$().tableSchema();
	$().addCustomTrigger();
	$("#ownSchema table thead").disableSelection();
	$("form#uploadProcess input.button").click(function() {
		if($("#matchUp").val() == "") {
			alert("You must match up at least one field from your database.");
			return false;
		}
		else {
			$(this).attr("value", "Processing...");
			$(this).attr("disabled", true);
			$(this).css("background-color", "#808080");
			$("#uploadProcess").submit();
		}
	});
	$(".directoryCheckbox").click(function() {
		currentList = $("#ids").val();
		if($(this).attr("checked")) {
			$("#ids").val(currentList + "," + $(this).val());
		}
		else {
			listArray = currentList.split(",");
			newList = "";
			for(i = 0; i < listArray.length; i++) {
				if(listArray[i] != $(this).val() && listArray[i] != "")
					newList = newList + "," + listArray[i];
  			}
			$("#ids").val(newList);
		}
	});
	$("#checkAll").click(function() {
		if($(this).attr("checked")) {
			newList = "";
			$(".directoryCheckbox").each(function(index) {
				$(this).attr("checked", true);
				newList = newList + "," + $(this).val();
			});
			$("#ids").val(newList);
		}
		else {
			$(".directoryCheckbox").each(function(index) {
				$(this).attr("checked", false);
			});
			$("#ids").val("");
		}
	});
	if($(".multiselect").get(0)) {
		$(".multiselect").multiselect({sortable: false, searchable: false});
	}
	$(".ui-multiselect div.selected").each(function(index) {
		$(this).attr("style", "width: 124px");
	});
	$(".ui-multiselect div.available").each(function(index) {
		$(this).attr("style", "width: 125px; float: right;");
	});
	$(".ui-multiselect ul.selected").each(function(index) {
		$(this).attr("style", "height: 167px");
	});
	$(".ui-multiselect ul.available").each(function(index) {
		$(this).attr("style", "height: 167px");
	});
	$(".ui-multiselect").each(function(index) {
		$(this).attr("style", "width: 250px");
	});
	$("#orderBySubmit, #orderBySubmit2, #orderBySubmit3").change(function() {
		$("#filterOptions").submit();
	});
	$(".cmsTable .toggler").click(function() {
		$("#form" + $(this).parents("tr").attr("id").substr(4)).toggle();
	});
	if($("#uploadify3").get(0)) {
		$("#uploadify3").uploadify({
			uploader : "library/flash-uploadify.swf", 
			script : "processes/_uploader.php", 
			scriptData : {uid: $("#uid").val()}, 
			cancelImg : "css/images/bg_exit.png", 
			folder : "uploads", 
			queueID : "fileQueue", 
			auto : true, 
			multi : false, 
			fileDesc : "CSV/XLS Files", 
			fileExt : "*.csv;*.xls", 
			sizeLimit : 8388608, 
			buttonText : "Select database", 
			onAllComplete: function(event, data) {
				window.location.replace("uploaded.php");
			}
		});
	}
	$("#ownlist").change(function() {
		$("#owndb").attr("checked", "checked")
	});
	$("#billing_address").click(function() {
		if($(this).is(":checked")) {
			$("#billing_address1").attr("disabled", true);
			$("#billing_address2").attr("disabled", true);
			$("#billing_address3").attr("disabled", true);
			$("#billing_postcode").attr("disabled", true);	
		}
		else {
			$("#billing_address1").attr("disabled", false);
			$("#billing_address2").attr("disabled", false);
			$("#billing_address3").attr("disabled", false);
			$("#billing_postcode").attr("disabled", false);	
		}
	});
});

$.fn.preparePrompts = function() {
	$(".formField").focus(function() {
		if($(this).val() == $(this).attr("title")) {
			$(this).val("");
			$(this).removeClass("prompt");		
		}
	});
	$(".formField").blur(function() {
		if($(this).val() == "") {
			$(this).addClass("prompt");	
			$(this).val($(this).attr("title"));		
		}
	});
	$(".serviceToggle").click(function() {
		if($("#codeType").val() != "groupprice") {
			if($("#codeType").val() == "xmonthsfree")
				divName = "#theCostAfter";
			else
				divName = "#theCost";
			currentTotal = parseFloat($(divName).html());
			thisCost = parseFloat($(this).nextAll(".serviceSignupCost").html().substr(1));
			if($(this).hasClass("checked")) {
				$(this).removeClass("checked");
				$(this).nextAll(".serviceSignupCost").removeClass("highlight");
				newTotal = currentTotal - thisCost;
			}
			else {
				$(this).addClass("checked");
				$(this).nextAll(".serviceSignupCost").addClass("highlight");
				newTotal = currentTotal + thisCost;
			}
			$(divName).html(newTotal.toFixed(2));
			checkbox = "." + $(this).attr("id");
			$(checkbox).trigger("click");
		}
		return false;
	});
	$(".serviceToggle").mouseover(function(){
		$(this).prev().show();
	});
	$(".serviceToggle").mouseout(function(){
		$(".serviceDescription").hide();
	});
	if($("#paymentForm").get(0)) {
		$("#paymentForm").delay(5000).submit();
	};
	$("#signUpForm .term").click(function() {
		window.location.replace("?step=0&term=" + $(this).val());
	});
	$("#directoryFilter").change(function() {
		$("#filterOptions").submit();
	});
	if($("#contactPR").get(0)) {
		$("#contactPR").trigger("click");
	}
}

$.fn.createDropDown = function(source, fieldset, targetName) {
    var sourceRef = $(source);
    var selected = sourceRef.find("option[selected]");
    var options = $("option", sourceRef);
	var style = "";
	var styleDropdown = "";
	if(source == "#searchDropDownSource") {
		styleDropdown = " class=\"borderBottom\"";
	}
	else if(source == "#latestDropDownSource") {
		style = " borderBottom";
		styleDropdown = " class=\"borderBottom\"";
	}
    $(fieldset).append("<dl id=\"" + targetName + "\" class=\"dropdown" + style + "\"></dl>")
    $("#" + targetName).append("<dt>" + selected.text() + "<span class=\"value\">" + selected.val() + "</span></dt>")
    $("#" + targetName).append("<dd><ul" + styleDropdown + "></ul></dd>")
    options.each(function() {
        $("#" + targetName + " dd ul").append("<li class=\"id" + $(this).val() + "\">" + $(this).text() + "<span class=\"value\">" + $(this).val() + "</span></li>");
    });
	$("#" + targetName + " dt").click(function() {
		$("#" + targetName + " dd ul").toggle();
	});
	$("#" + targetName + " dd ul li").click(function() {
		var text = $(this).html();
		$("#" + targetName + " dt span").html(text);
		$("#" + targetName + " dd ul").hide();
	}); 
	$(document).bind("click", function(e) {
		var $clicked = $(e.target);
		if (! $clicked.parents().hasClass("dropdown"))
			$("#" + targetName + " dd ul").hide();
	});
	$("#" + targetName + " dd ul li").click(function() {
		var text = $(this).html();
		$("#" + targetName + " dt").html(text);
		$("#" + targetName + " dd ul").hide();
		sourceRef.val($(this).find("span.value").html());
		if(targetName == "latestTarget") {
			$().loadLatest($(this).find("span.value").html());
			$(".scrollable").scrollable().reload().begin();
		}
		else if(targetName == "releasesTarget")
			$().loadPressReleases($(this).find("span.value").html());
	});
}

$.fn.loadLatest = function(iid) {
	url = "../ajax/aj_latest.php";
	if($("#a").get(0))
		url = url + "?a=y";
	$("#latestImagesList").load(url, {iid: iid}, function() {$().makeDraggable("#latestImages");});
}

$.fn.loadPressReleases = function(iid) {
	$("#latestPressReleases").load("../ajax/aj_releases.php", {iid: iid});
}

$.fn.basket = function(action, pid, type) {
	if(type == "previous")
		$.post("../ajax/aj_basket.php", {action: action, pid: pid, type: type});
	else if(type == "mini")
		$("#miniBasketItems").load("../ajax/aj_basket.php", {action: action, pid: pid, type: type});
	else if(type == "mid") {
		$("#midBasket").load("../ajax/aj_basket.php", {action: action, pid: pid, type: type}, function() {
			$("#midBasket .del").click(function() {
				$().basket("delete", $(this).attr("id"), "mid");
			});
		});
	}
}

$.fn.loadBrowser = function(from, iid, orderBy, searchString, cid, scid, ccid, view, clear, resetCounter) {
	if(clear == "y")
		$("#browserResults").empty();
	$("#browserResults").append("<img src=\"../css/images/an_loading.gif\" width=\"400\" height=\"352\" class=\"loadingImage\" alt=\"Loading...\" />");
	if(iid == "") {
		iidArray = $("body").attr("id").split("_");
		iid = iidArray[1];
	}
	if(cid == "")
		cid = $("#categoryMenu .on").attr("id");
	if(scid == "" && $("#categoryMenu .subon").get(0))
		scid = $("#categoryMenu .subon").attr("id").substr(1);
	if(view == "")
		view = $("#browserToolbar .on").attr("id");
	if(orderBy == "")
		orderBy = $("#orderBy").val();
	if(ccid == "" && $("#pressOfficeId").get(0))
		ccid = $("#pressOfficeId").html();
	if(searchString == "" && $("#currentSearch").get(0)) {
		searchString = $("#currentSearch").html();
		scid = "";
		cid = "";
	}
	else if(searchString == "" && $("#searchWithin").val() != $("#searchWithin").attr("title")) {
		searchString = $("#searchWithin").val();
	}
	if($("#advancedSearchOptions").get(0)) {
		stype = $("#advancedSearchOptions span.stype").html();
		if($("#advancedSearchOptions span.sid").get(0))
			sid = $("#advancedSearchOptions span.sid").html();
		else
			sid = "";
		if($("#advancedSearchOptions span.state").get(0))
			state = $("#advancedSearchOptions span.state").html();
		else
			state = "";
		if($("#advancedSearchOptions span.excludeCompany").get(0))
			excludeCompany = "y";
		else
			excludeCompany = "";
		if($("#advancedSearchOptions span.minSize").get(0))
			minSize = $("#advancedSearchOptions span.minSize").html();
		else
			minSize = "";
		if($("#advancedSearchOptions span.minPrice").get(0))
			minPrice = $("#advancedSearchOptions span.minPrice").html();
		else
			minPrice = "";
		if($("#advancedSearchOptions span.maxPrice").get(0))
			maxPrice = $("#advancedSearchOptions span.maxPrice").html();
		else
			maxPrice = "";
		if($("#advancedSearchOptions span.style").get(0)) {
			if($("#advancedSearchOptions span.style").html() == "Cut out only")
				style = "cutout";
			else if($("#advancedSearchOptions span.style").html() == "Lifestyle only")
				style = "lifestyle";
			else
				style = "other";
		}
		else
			style = "";
	}
	else {
		stype = "";
		sid = "";
		state = "";
		excludeCompany = "";
		minSize = "";
		minPrice = "";
		maxPrice = "";
		style = "";
	}
	if(from == 0 && searchString != "")
		record = "y";
	else
		record = "";
	$.get("../ajax/aj_browser.php", {
		from: from, 
		iid: iid, 
		orderBy: orderBy, 
		searchString: searchString, 
		cid: cid, 
		scid: scid, 
		ccid: ccid, 
		view: view, 
		record: record, 
		sid: sid, 
		state: state, 
		stype: stype, 
		excludeCompany: excludeCompany, 
		minSize: minSize, 
		minPrice: minPrice, 
		maxPrice: maxPrice, 
		style: style
	}, function(data) {
		newFrom = parseFloat(from) + 24;
		if(newFrom > parseFloat($("#browserTotal").html()))
			newFrom = $("#count").html();
		$("#from").html(newFrom);
		$(".loadingImage").addClass("hidden");
		$("#browserResults").append(data);
		if(parseFloat($("#viewing").html()) == 0 || resetCounter == "y")
			$("#viewing").html("1");
		if(from == 0) {
			$("#count").html($("#browserTotal").html());
			if(parseFloat($("#browserTotal").html()) < "24")
				$("#from").html($("#browserTotal").html());
		}
		if($("#browserTotal").html() == "0") {
			$("#viewing").html("0");
			window.location.replace("noresults.php?url=" + $(location).attr('href'));
		}
		if(parseFloat($("#from").html()) > parseFloat($("#count").html()))
			$("#from").html($("#count").html());
		$().makeDraggable("parent");
		$("#browserToolbar li").click(function() {
			$("#browserToolbar .on").removeClass("on");
			$(this).addClass("on");
			if($(this).attr("id") == "list") {
				$(".imageItem").each(function() {
					$(this).removeClass("thumbImageItem");
					$(this).removeClass("detailImageItem");
					$(this).addClass("listImageItem");
				});
			}
			else if($(this).attr("id") == "thumb") {
				$(".imageItem").each(function() {
					$(this).removeClass("listImageItem");
					$(this).removeClass("detailImageItem");
					$(this).addClass("thumbImageItem");
				});
			}
			else if($(this).attr("id") == "detail") {
				$(".imageItem").each(function() {
					$(this).removeClass("listImageItem");
					$(this).removeClass("thumbImageItem");
					$(this).addClass("detailImageItem");
				});
			}
		});
		tb_init(".thickbox");
		$(".basketAdd").click(function() {
			imageAddArray = $(this).attr("id").split("|");
			$().basket("add", imageAddArray[0], "mini");
			$("#addConfirmImage").html("<img src=\"" + imageAddArray[1] + "\" width=\"65\" height=\"65\" class=\"borderAll\" />");
			$("#addConfirm").fadeIn(1);
			$("#addConfirm").delay(1000).fadeOut(1000);
			$(this).html("ADDED");
		});
		if($("#clientFilter").get(0) && from == 0 && ccid == "") {
			$("#clientFilter").html("");
			$("#clientFilter").append($("<option></option>").val("").html("(Filter by company)"));
			clientArray = $("#browserClients").html().split("|");
			for(var i in clientArray) {
				clientSplit = clientArray[i].split(",");
				$("#clientFilter").append($("<option></option>").val(clientSplit[0]).html(clientSplit[1]));
			}
		}
		loading = "n";
	});
}

$.fn.makeDraggable = function(appendTo) {
	$(".draggable").draggable({
		revert: "invalid", 
		addClasses: false, 
		helper: "clone", 
		opacity: 0.75, 
		scroll: false, 
		zIndex: 10002, 
		appendTo: appendTo, 
		start: function(event, ui) {
			$(ui.helper).addClass("borderAll");
		}
	});
}

$.fn.loadReleaseLoft = function(clear, from) {
	if(clear == "y")
		$("#releaseLoftResults").empty();
	if($("#ccid").val() == "")
		thisccid = "";
	else
		thisccid = $("#ccid").val();
	if($("#searchReleases").val() == "" || $("#searchReleases").val() == "search press releases")
		searchFor = "";
	else
		searchFor = $("#searchReleases").val();
	if(from == "")
		from = $("#from").html();
	$("#releaseLoftResults").append("<img src=\"../css/images/an_loading.gif\" width=\"400\" height=\"352\" class=\"loadingImage\" alt=\"Loading...\" />");
	$.get("../ajax/aj_releases.php", {
		from: from, 
		ccid: thisccid, 
		searchFor: searchFor
	}, function(data) {
		newFrom = parseFloat(from) + 25;
		if(newFrom > parseFloat($("#total").html()))
			newFrom = $("#count").html();
		$("#from").html(newFrom);
		$(".loadingImage").addClass("hidden");
		$("#releaseLoftResults").append(data);
		$("#viewing").html("1");
		if(from == 0) {
			$("#count").html($("#total").html());
			if(parseFloat($("#total").html()) < "24")
				$("#from").html($("#total").html());
		}
	});
}

$.fn.loadFeatureLoft = function(clear, from) {
	if(clear == "y")
		$("#featureLoftResults").empty();
	if(from == "")
		from = $("#from").html();
	$("#featureLoftResults").append("<img src=\"../css/images/an_loading.gif\" width=\"400\" height=\"352\" class=\"loadingImage\" alt=\"Loading...\" />");
	$.get("../ajax/aj_features.php", {
		from: from
	}, function(data) {
		newFrom = parseFloat(from) + 25;
		if(newFrom > parseFloat($("#total").html()))
			newFrom = $("#count").html();
		$("#from").html(newFrom);
		$(".loadingImage").addClass("hidden");
		$("#featureLoftResults").append(data);
		$("#viewing").html("1");
		if(from == 0) {
			$("#count").html($("#total").html());
			if(parseFloat($("#total").html()) < "24")
				$("#from").html($("#total").html());
		}
	});
}

$.fn.loadDirectory = function() {
	$("#directoryResults").empty();
	letter = $("#directoryIndex span.on").html();
	$("#directoryResults").append("<img src=\"../css/images/an_loading.gif\" width=\"400\" height=\"352\" class=\"loadingImage\" alt=\"Loading...\" />");
	$.get("../ajax/aj_directory.php", {
		letter: letter
	}, function(data) {
		$(".loadingImage").addClass("hidden");
		$("#directoryResults").append(data);
		tb_init(".thickbox");
	});
}

$.fn.addCustomTrigger = function() {
	$("#siteSchema table th.addCustom").click(function() {
		currentCols = parseFloat($("#currentColumns").val());
		thisColumn = currentCols + 1;
		$(this).html("<input type=\"text\" name=\"custom" + (currentCols - 12) + "\" placeholder=\"custom field\" size=\"20\" />");
		$(this).attr("id", "col" + currentCols);
		$(this).attr("class", "drop");
		$(this).removeClass("addCustom");
		$(this).unbind("click");
		$("#currentColumns").val(thisColumn);
		if(thisColumn < 18) {
			$(this).after("<th id=\"col" + thisColumn + "\" class=\"addCustom\"><b>+</b> <span>Add a custom column</span></th>");
			$("#siteSchema table tbody td.col" + currentCols).each(function(index) {
				$(this).after("<td class=\"col" + thisColumn + " drop\"></td>");
  			});
			$().addCustomTrigger();
			$().tableSchema();
		}
	});
}

$.fn.tableSchema = function() {
	$("#siteSchema table thead th.drop, #siteSchema table tbody td.drop").droppable({
		tolerance: "pointer", 
		activate: function(event, ui) {
			$(this).addClass("active");
		}, 
		deactivate: function(event, ui) {
			$(this).removeClass("active");
		}, 
		over: function(event, ui) {
			$(this).addClass("over");
			if($(this).width() < $(ui.draggable).width())
				$(this).css("width", $(ui.draggable).width() + "px");
		}, 
		out: function(event, ui) {
			$(this).removeClass("over");
			$(this).css("width", "");
		}, 
		drop: function(event, ui) {
			var dom = $(this).get(0);
			if(dom.tagName == "TH") {
				element = "#" + $(this).attr("id");
				newColumn = $(this).attr("id");
			} else {
				thisArray = $(this).attr("class").split(" ");
				element = "#" + thisArray[0];
				newColumn = thisArray[0];
			}
			if($(element).attr("class") == "drop ui-droppable over matched active" || $(element).attr("class") == "drop ui-droppable matched active" || $(element).attr("class") == "drop ui-droppable matched") {
				alert("This field has already been matched.");
			}
			else {
				columnHeading = $(element).html();
				$("#ownSchema table tbody td.col" + $(ui.draggable).attr("id")).each(function(index) {
					$("#siteSchema table tbody tr.row" + index + " td." + newColumn).html($(this).text());
				});
				$("#ownSchema table thead th#" + $(ui.draggable).attr("id")).hide();
				$("#ownSchema table tbody td.col" + $(ui.draggable).attr("id")).hide();
				$(element).addClass("matched");
				$(element).html("<div class=\"originalName\">" + columnHeading + "</div><div class=\"matchedTo\">matched to</div><div id=\"ownField_" + $(ui.draggable).attr("id") + "\">" + $(ui.draggable).html() + "</div><img src=\"../css/images/bg_exit.png\" width=\"20\" height=\"20\" class=\"cancelMatch\" />");
				currentMatchup = $("#matchUp").val();
				newMatchup = currentMatchup + "," + newColumn.substr(3) + "|" + $(ui.draggable).attr("id");
				$("#matchUp").val(newMatchup);
				$("#siteSchema table thead th img.cancelMatch").click(function() {
					idArray = $(this).prev().attr("id").split("_");
					origID = $(this).parent().attr("id").substr(3);
					$("#ownSchema table thead th#" + idArray[1]).show();
					$("#ownSchema table tbody td.col" + idArray[1]).show();
					$(this).parent().removeClass("matched");
					$(this).parent().removeClass("over");
					$(this).parent().html($(this).prevAll("div.originalName").html());
					$("#siteSchema table tbody td.col" + origID).empty();
					currentMatchup = $("#matchUp").val();
					matchupArray = currentMatchup.split(",");
					newMatchup = "";
					removeMatch = origID + "|" + idArray[1];
					for(var i in matchupArray) {
						if(removeMatch != matchupArray[i] && matchupArray[i] != "")
							newMatchup = newMatchup + "," + matchupArray[i];
					}
					$("#matchUp").val(newMatchup);
				});
			}
		}
	});
}
