(function($){
	jQuery(document).ready(function() {

		/**
		 * @description Used in /Brochures and is triggered when user selects
		 * a language in the dropdown.
		 */
		$("#country").change( function() { startLoading(); $("form#brochures").submit(); });

		/**
		 * @description This event handler is used in combination with the website toolbar
		 * on the mdb siteaccess (obviously, since it's in mediadatabase.js). It changes 
		 * the destination folder based on what you want to create.
		 * If you create a File, it'll change source to '/Media/Files'. 
		 * An image will be put in '/Media/Images' and so on. 
		 * @see website_toolbar.tpl inside the kvg-mdb2 extension.
		 */
		$("#ezwt input[name='NewButton']").click( function()
		{
			nodeId   = $("#ezwt-create").children(":selected").attr('id');
			objectId = $("#ezwt-create").children(":selected").attr('class');
			
			$("#ezwt input[name='NodeID']").val( nodeId );
			$("#ezwt input[name='ContentNodeID']").val( nodeId );
			$("#ezwt input[name='ContentObjectID']").val( objectId );
		});

		/**
		 * @description This is used to automatically trigger the AJAX Tag Drilldown®
		 * when the page has finished loading.
		 */
		if( $("form#tags select[name='coreProduct']").html() != null )
		{
			_refreshProductFamilyByCore();
			if( $("form#tags select[name='productFamily']").val() )
			{
				_refreshProductsByFamily();
			}
			else
			{
				_refreshProductsByCore();
			}
		}
		
		/**
		 * @description When the core product is changed both products and 
		 * product families will update. 
		 * If a product family is already chosen from last HTTP request
		 * that is taken into account when drilling.
		 */
		$("form#tags select[name='coreProduct']").change( function()
		{
			_refreshProductFamilyByCore();
			_refreshProductsByCore();
		});

		/**
		 * @description When a product family is chosen products are 
		 * updated based on family value.
		 */
		$("form#tags select[name='productFamily']").change( function() {
			_refreshProductsByFamily();
		});
	
		$("#mdbsearch_more_options").click(clickMoreOptions);
		$("#mdbsearch_update").click(clickUpdate);
		$(".mdbsearch_text").keydown(textInputKeydown);
		$(".mdbsearch_result").hover(function(){resultHover(this);},function(){resultHoverLeave(this);});
		$("#mdbsearch_results_lightbox").hover(function(){lightBoxHover(this);},function(){lightBoxLeave(this);});

		//Brochure
		$("#mdbsearch_show_brochure_order_form").click(clickShowBrochure);
		$("#mdbsearch_invoice_same_as_shipping").click(invoiceSameAsShipping);
		$("#mdbsearch_shipping_address").find("input:text").change(shippingAddressChanged);
		$("#mdbsearch_brochure_order_confirm_button").click(clickConfirm);
		$("#mdbsearch_brochure_order_info").find("input:text").focusin( function() { resetAllInput(); });
		$("#mdbsearch_brochure_order_info").find("input:radio").click( function() { resetAllInput(); });

		/**
		 * @description Left menu
		 * Assumes a sturcture like this:
		 * <li class="x-brand">
		 *     <a>Brand</a>
		 *     <ul>
		 *         <li class="x-product-area">
		 *             <a>Product Area</a>
		 *         </li>
		 *     </ul>
		 * </li>
		 */
		$(".x-brand > a").click( function(e) 
		{
			$(this).parent().siblings().children("ul:visible").slideUp();
			$(this).next().slideToggle();
			e.preventDefault(); 
		});

		$(".x-product-area > a"). click( function() { startLoading(); });
	});

	/**
	 * @description Genereic loading
	 */
	function startLoading()
	{
		$("#options").slideUp('fast'); 
		$("#criteria > h4").addClass("loading");
	}

	/**
	 * @param {jQuery Object} selectNode The select element that should be updated
	 * @param {String} remoteMethod Method name for /ezjscore/call/mdb::<remoteMethod>.
	 * For a list of available methods see classes/ezjscore_mdb.php.
	 * @description Performs a GET request that returns a JSON formatted list
	 * and adds the result to the select node. 
	 * Also toggles "loading" class on a an uncle - the TD that encapusalates the label.
	 */
	function _refreshOptions( selectNode, remoteMethod )
	{
		remoteUrl = "/ezjscore/call/mdb::" + remoteMethod;
		$(selectNode).parent().prev().addClass("loading");
		$.getJSON( remoteUrl, { query: $("form.search").serialize() }, function( result )
		{
			var selectedValue = $(selectNode).children(":selected").text();
			$(selectNode).empty();
			if( result.content.length != 1 )
			{
				$(selectNode).append( "<option />" );
			}
			$.each( result.content, function( i, value )
			{
				if( selectedValue == value )
				{
					html = '<option selected="selected">' + value + '</option>';
				}
				else
				{
					html = '<option>' + value + '</option>';
				}
				$(selectNode).append( html );
			});
			$(selectNode).parent().prev().removeClass("loading");
		});
	}

	/**
	 * @description These are helper methods for _refreshOptions().
	 * Basically the arguments are, update where(1) with what(2).
	 * @see _refreshOptions for detailed info.
	 */
	function _refreshProductFamilyByCore() { _refreshOptions( $("select[name='productFamily']"), "findProductFamilyTagsByCore" ); }
	function _refreshProductsByFamily()    { _refreshOptions( $("select[name='product']"),       "findProductTagsByFamily" ); }
	function _refreshProductsByCore()      { _refreshOptions( $("select[name='product']"),       "findProductTagsByCore" ); }

	function shippingAddressChanged(){
		if (invoiceToShippingIsSelected()) updateInvoiceToShipping();
	}
	
	function resetAllInput()
	{
		$("#mdbsearch_brochure_order_info").find("input:text").css("border","1px solid #ccc");
		setTrBorder($("#mdbsearch_input_shipment_type"),"1px hidden transparent");
	}

	function invoiceToShippingIsSelected(){
		return $("#mdbsearch_invoice_same_as_shipping").attr('checked');
	}
	
	function updateInvoiceToShipping(){
		var sa=$("#mdbsearch_shipping_address").find("input:text");
		var ia=$("#mdbsearch_invoice_address").find("input:text");
		for (var i=0;i<sa.length;i++){
			$(ia[i]).val($(sa[i]).val()).attr('disabled', 'disabled');
		}
	}
	
	function invoiceSameAsShipping(e){
		if (invoiceToShippingIsSelected()) updateInvoiceToShipping();
		else $("#mdbsearch_invoice_address").find("input").removeAttr('disabled');
		return true;
	}

	function lightBoxHover(e){}
	function lightBoxLeave(e){
		$("#mdbsearch_results_lightbox").stop().hide();
	}

	function resultHoverLeave(e){}
	function resultHover(e){
		var p=$(e).offset();
		var i=$("img",$(e));
		$("#mdbsearch_results_lightbox").empty();
		$(e).clone().children().appendTo("#mdbsearch_results_lightbox");
		$("img","#mdbsearch_results_lightbox").attr('width',$(i).attr('width')*1.4).attr('height',$(i).attr('height')*1.4);
		$("#mdbsearch_results_lightbox").css("left",(p.left-15)+"px").css("top",(p.top-14)+"px").stop().show();
	}

	
	function textInputKeydown(e){
		if (e.keyCode == '13'){
			clickUpdate();
			window.location.href=$("#mdbsearch_update").attr("href");
		}
	}


	function postOrder(){
		$("#mdbsearch_brochure_order_form").submit();
	}

	function setTrBorder(tr,value){
		$(tr).contents("td").css({'border': value, 'border-left': 'none', 'border-right': 'none'});
		$(tr).contents("td:first").css('border-left', value);
		$(tr).contents("td:last").css('border-right', value);
	}


	// Clickers
	function clickShowBrochure(e){
		$("#mdbsearch_brochure_order_info").stop().slideToggle('fast');
		return false;
	}

	function clickUpdate(){
		var options=$("#mdbsearch_update").attr("href");
		$(".mdbsearch_select").each(function(i){
			var val=jQuery.trim($(this).val());
			if (val.length>0){
				var key=$(this).val().split(":")[1];
				if (key.length>0) options+="&"+$(this).attr("name")+"="+key;
			}
		});
		$(".mdbsearch_text").each(function(i){
			var val=jQuery.trim($(this).val());
			if (val.length>0) options+="&"+$(this).attr("name")+"="+val;
		});
		var type="";
		$(".mdbsearch_type:checked").each(function(i){
			var val=jQuery.trim($(this).val());
			if (val.length>0) type+="|"+val;
		});
		if (type.length>0) options+="&type="+type.substring(1);
		$("#mdbsearch_update").attr("href",options);
		return true;
	}

	function clickMoreOptions(){
		$("#mdbsearch_options").stop().slideToggle('fast');
		return false;
	}
	
	function clickConfirm(){
		var err=0;
		$("#mdbsearch_brochure_order_info").find(".mdbsearch_input_required:text").each(function(){
			if ($.trim($(this).val())==""){
				$(this).css("border","1px solid red").animate({'background-color': "#aaa"},1500,function(){});
				err++;
			}
		});
		var ct="";
		$("#mdbsearch_shipment").find("input:radio[name='mdbsearch_input_shipment_type']:checked").each(function(){
			ct=$(this).val();
		});
		if (ct=="") {
			setTrBorder($("#mdbsearch_input_shipment_type"),"1px solid red");
			err++;
		}
		if (err==0) postOrder();
		return false;
	}
})(jQuery);

