
(function($, undefined) {

	// lf.ad object
	lf.ad = {

		getContactForm: function(adKey) {
		  	$.ajax({
		  		type: "GET",
		  		url: lf.getConfig("ajaxUrl") + "shoes/get_contact_form.php",
		  		data: ({ 
		  			'k': adKey
		  		}),
		  		beforeSend: function() {
		  		  $("#adContactFormParent").html("<img src='" + lf.getConfig("imagesUrl") + "spinny_green.gif' />");
		  		},
		  		success: function(msg){
		  		  $("#adContactFormParent").html(msg);
		  		}
		  	});
		},
			
		displayContactForm: function(adKey) {
			if($("#adContactFormParent").html().length == 0) {
				this.getContactForm(adKey);
			}
			$("#viewContactFormLink").css( {width: 'auto'} );
			$("#adContactFormParent").show();
		},

		hideContactForm: function() {
		    $("#adContactFormParent").fadeOut(400, function() {
		    	$("#viewContactFormLink").animate( { width: '150px'}, 500);
		  	});
		},
			
		submitContactForm: function() {
		    this.toggleContactFormButtons();
		
		  	$.ajax({
		  		type: "POST",
		  		url: lf.getConfig("ajaxUrl") + "shoes/submit_contact_form.php",
		  		data: $("#adContactForm").serialize(),
		  		success: function(msg){
		  			$("#contactFormSuccess").html(msg);
		  			$("#contactFormSuccess").show();
		  			$("#viewContactFormLink").hide();
		  			$("#adContactFormParent").hide();
		  			this.toggleContactFormButtons();
		  		},
		
		  		// xhr = XMLHttpRequest object
		  		error: function (xhr, ajaxOptions, thrownError) {
			        if(xhr.status == 500) {
			        	$("#contactFormAlert").html(xhr.statusText).show();
			        }
			        else {
			            $("#contactFormAlert").html("Oops. An error has occurred.");
			  			$("#contactFormAlertRow").show();
			        }
			        this.toggleContactFormButtons();
		  		} 
		  	});
		},
			
		toggleContactFormButtons: function() {
			$("#contactFormButtons").toggle();
			$("#contactFormButtonsSpinny").toggle();
		},
		
		go: function(key) {
			window.location = lf.getConfig("baseUrl") + "shoes/go.php?k=" + key;
		},
			
		confirmDeleteToggle: function() {
			if($("#adDeleteLink").css("display") == "none") {
				$("#adDeleteConfirm").hide("fast", function() {
					$("#adDeleteLink").show("fast");
				});
			} else {
				$("#adDeleteLink").hide("fast", function() {
					$("#adDeleteConfirm").show("fast");
				});
			}
		},
			
		/**
		 * Highlights all of the banned words in a given element
		 *
		 * @param idArray  An array of element id's to check
		 */
		highlightBannedWords: function(idArray) {
			$.each(
					idArray, 
					function(intIndex, elementId) {
						$.ajax({
							type:    "GET",
							url:     lf.getConfig("ajaxUrl") + "shoes/highlight_banned_words.php",
							data:    {"dirty": $("#"+elementId).text()},
							success: function(msg) {
								$("#"+elementId).html(msg);
								c(msg);
							}
						});
					}
			);
		}
	};
	// end lf.ad	
	
	
	lf.ad.edit = {
		displayPriceSelect: function() {
		    $("#enterPrice").fadeOut("fast", function() {
		    	$("#ad_price").val("0");
		    	$("#price_choose").val("free");
		    	$("#priceSelect").fadeIn("fast");
			});
		},

		hidePriceSelect: function() {
			$("#priceSelect").fadeOut("fast", function() {
				$("#enterPrice").fadeIn("fast");
			});
		},

		togglePrice: function() {
			if($("#price_choose").val() == "notfree") {
				this.hidePriceSelect();
			} else {
				this.displayPriceSelect();
			}
		},

		displayAppropriatePriceInput: function() {
			var priceVal = $("#ad_price").val();
			if(parseInt(priceVal)){
				this.hidePriceSelect();
			} else {
				this.displayPriceSelect();
			}
		},

		updatePrice: function(newValue) {
			$("#ad_price").val($("#ad_price_input").val());
		},

		addNew: function() {
			$("#newPostPlaceholder").show(800, function() {
				// display popup
				this.displayAdNewPopup();
			});
		},

		displayImagePopup: function() {
			var viewPhotoLinkOffset = $("#viewPhotoLink").offset();
			$("#adImageSmall").dialog( { 
				modal:     false,
				resizable: false,
				width:     240,
				position: [viewPhotoLinkOffset.left, viewPhotoLinkOffset.top + 20] });
		},

		displayAdNewPopup: function() {
			var popup = $("#addNewPopup");
			var popupArrow = $("#addNewPopupArrow");
			var placeholderOffset = $("#newPostPlaceholder").offset();
			popup.css( { 'position': 'absolute',
				'top': placeholderOffset.top - 10,
				'left': placeholderOffset.left + $("#newPostPlaceholder").width() + 16
			})

			popupArrow.css( { 'position': 'absolute',
				'top': placeholderOffset.top + 20,
				'left': placeholderOffset.left + $("#newPostPlaceholder").width()
			})

			popup.show("fast", function() {
				popupArrow.show();
			});
		},

		deletePhoto: function() {
			// so the content doesnt bounce up and down as the elements
			// are hidden and then displayed
			$("#managePhoto").css( { 'height': $("#managePhoto").height() } );
			$("#viewPhotoLink").hide("fast");
			$("#deletePhotoLink").hide("fast", function() {
				$("#deletePhotoUndoLink").show("fast");
			});

			$("#deletePhoto").val("1");
		},

		undoDeletePhoto: function() {
			$("#deletePhotoUndoLink").hide("fast", function() {
				$("#deletePhotoLink").show("fast");
				$("#viewPhotoLink").show("fast");
			});

			$("#deletePhoto").val("0");
		},

		init: function() {
			$("#submitButtonContainer").click(
					function() {
						$("#buttonSubmit").hide();
						$("#lightBlueSpinny").show();
						$('#newAdForm').submit();
					}
			)
		}
	};
	// end lf.ad.edit object
	
	
	lf.ad.reject = {
		displayReasonOther: function() {
			if($("#rejectReason").val() == "other") {
				$("#rejectReasonOther").show("fast");
			} else {
				$("#rejectReasonOther").hide();
			}
		},
		
		init: function() {
			$("#rejectReason").change(function() {
				this.displayReasonOther();
			});
		}
	};
	// end lf.ad.reject
	

	lf.ad.list = {
		showAdDetails: function(key, queryString) {
			$("#dataFilter").hide();  
			$("#adListContainer").hide();
			this.getAdDetails(key);
		},

		showAdDetailsPopup: function(el, key) {
			this.getAdDetails(key, true);
		},

		getAdDetails: function(key, incrementViewCounter) {
			var incrementViewCounter = incrementViewCounter || false;
			//$(document).unbind("endlessScroll");

			// this establishes some facebox settings
			$('#adDetailsContainer').facebox({ 
				loadingImage: 'http://dev_static.lowfive.org/scripts/facebox/loading.gif',
				closeImage:   'http://dev_static.lowfive.org/scripts/facebox/closelabel.gif',
				opacity:      0.5,
				overlay:      true,
				isModal:      false
			});

			// an outer facebox function will cause the loadingImage
			// to display while the ajax results are received
			$.facebox(function() {
				$.ajax({
					type: "GET",
					url: lf.getConfig("ajaxUrl") + "shoes/get_ad_details.php",
					data: ({ 
						'k': key,
						'plusView': incrementViewCounter
					}),

					beforeSend: function() {
				},

				success: function(msg){
					//  		  $("#adDetails").html(msg);
					//  		  jQuery.facebox({ 
					//  		    div: '#adDetailsContainer'
					//  		  });

					jQuery.facebox(msg); // this works

//					$(document).bind('reveal.facebox', function() { 
//					map.checkResize();
//					});

					//  		  $("#adDetailsContainer").dialog( { modal:     true,
					//        		                              resizable: false,
					//  		                                      width:     890,
					//  		                                      position: 'center'});
				}
				});
			});
		},

		hideAdDetails: function() {
			$("#adDetailsContainer").toggle("fast", function() {
				$("#dataFilter").toggle("fast");
				$("#adListContainer").toggle("fast");

				// cant toggle() here because the display might already
				// be displayed
				$("#olderPostsLink").css( {'display': 'block'} );
			});
		},

		adSearch: function(formName) {
			$.ajax({
				type: "POST",
				url: lf.getConfig("ajaxUrl") + "shoes/ad_search.php",
				data: $("#"+formName).serialize(),
				beforeSend: function() {
				$("#getMoreArrow").hide();
				$("#getMoreSpinny").show();
			},

			complete: function() {
				$("#getMoreSpinny").hide();
				$("#getMoreArrow").show();
			},

			success: function(msg){
				//				$("#adSmallContainer:last").after(msg);
				$("#seeOlderPostsHighlight").before(msg);
				if(parseInt($("#currentPage").val()) >= parseInt($("#totalPages").val())) {
					$("#seeOlderPostsHighlight").hide();
					$("#noMorePosts").show();
				}
			}
			});
		},
			
		paginate: function(formName) {
			var currPageNum = parseInt($("#currentPage").val());
			var totalPages  = parseInt($("#totalPages").val());

//			c("currently have " + parseInt($("#resultsPerPage").val()) * parseInt(currPageNum+1) + " of "+$("#totalCount").val()+" total results");
//			c("currPageNum = " + parseInt(currPageNum+1));
//			c("totalPages = " + totalPages);

			if(currPageNum < totalPages) {
				$("#currentPage").val(currPageNum + 1);
				this.adSearch(formName);
			}
		},
			
		displayMessagePopup: function() {
			$('#messageContainer').facebox({ 
				loadingImage: 'http://dev_static.lowfive.org/scripts/facebox/loading.gif',
				closeImage:   'http://dev_static.lowfive.org/scripts/facebox/closelabel.gif',
				opacity:      0.5,
				overlay:      true,
				isModal:      false
			});

			jQuery.facebox({ div: '#messageContainer' });

//			$("#messageContainer").dialog({ dialogClass: 'message',
//			modal:     true,
//			resizable: false,
//			width:     505,
//			position: 'center' });
		},
			
		init: function() {
			$(".adSmallHighlight").hover(
				function() {
					$(this).css({ 'background-color': '#f4f0e6' });
				}, 
				function() {
					$(this).css({ 'background-color': '' });
				}
			);
		}
	};
	// end lf.ad.list
	

	lf.ad.list.searchFilter = {
		formName: 'searchForm',
		defaultValueString: '',
        
		init: function() {
			var that = this;
		
			$("#ad_gender, #ad_size, #ad_width, #ad_price, #ad_condition, #ad_brand, #ad_loc_country, #ad_loc_state, #ad_loc_city").bind("change", function(e) {
				//$(document).trigger("filterChange.adList");
				lf.ad.list.searchFilter.getResultCount();
			});
			
			$("#ad_brand").bind("click", function() {
				that.clearPlaceholderVal("ad_brand");
			});
			
			$("#price_choose").bind("change", function() {
				that.togglePrice();
			});
			
			$("#buttonSearch").bind("click", function() {
				that.doSearch();
			});
		},
	
		setFormName: function(searchFormName) {
			this.formName = searchFormName;
		},

		setDefaultString: function(str) {
			this.defaultValueString = str;
		},

		doSearch: function(formName) {
			$("#paginate").val("0");
			$("#" + this.formName).submit();
		},

		displayPriceSelect: function() {
			$("#enterPrice").fadeOut("fast", function() {
				$("#ad_price").val("");

				// needed for this.getResultCount() to work properly
				$("#ad_price").trigger("change");

				if($("#price_choose").val() != ""){
					$("#price_choose").val("free");
				}

				$("#priceSelect").fadeIn("fast");
			});
		},

		togglePrice: function() {
			if($("#price_choose").val() == "notfree") {
				$("#priceSelect").fadeOut("fast", function() {
					$("#enterPrice").fadeIn("fast");
				});

			} else if($("#price_choose").val() == "free") {
				$("#ad_price").val("0");

				// needed for this.getResultCount() to work properly
				$("#ad_price").trigger("change");

			} else  {
				this.displayPriceSelect();
			}
		},

		locationSearchCallback: function() {
			this.getResultCount();
		},

		getResultCount: function() {
			$.ajax({
				type: "POST",
				url: lf.getConfig("ajaxUrl") + "shoes/list/get_filter_result_count.php",
				data: $("#" + this.formName).serialize(),

				beforeSend: function() {
				$("#filterNumResultsVal").html("<img src='" + lf.getConfig("imagesUrl") + "loading_small.gif'/>");
			},

			success: function(msg){
				$("#filterNumResultsVal").html(msg);
				$("#filterNumResults").show();
			}
			});
		},

		clearPlaceholderVal: function(id) {
			if($("#"+id).val() == "(any)") {
				$("#"+id).val("");
			}
		}
	};
	// end lf.ad.list.searchFilter
	
 
	lf.ad.list.intro = {
		showFind: function() {
			var popup    = $("#introFindPopup");
			var position = $(".dataFilter").offset();
			var that = this;
			
			popup.css( {'position': 'absolute',
						'top':      position.top,
						'left':     position.left + $(".dataFilter").width(),
						'width':    '220px' });
			popup.fadeIn("fast");
		
			// close the others
			this.hideOffer();
		
			setTimeout(function() {
				that.hideFind();
			}, 4000);
		},

		showOffer: function() {
			var popup    = $("#introOfferPopup");
			var position = $("#buttonAddNew").offset();
			var that = this;
			
			popup.css({ 'position': 'absolute',
				'top':      position.top + $("#buttonAddNew").height(),
				'left':     position.left + 4,
				'width':    '223px'
			});
			popup.fadeIn("fast");

			// close the others
			this.hideFind();

			setTimeout(function() {
				this.hideOffer();
			}, 6000);
		},

		hideFind: function() {
			$("#introFindPopup").hide();
		},

		hideOffer: function() {
			$("#introOfferPopup").hide();
		}
	};
	// end lf.ad.list.intro
	
	
	lf.ad.list.monsterMash = {
		init: function() {
			$(".adSmallMonster").hover(
				function() {
					$(this).css( {"background-position": "-227px 0"} );
					$(".adSmallMonster div.adSmallMonsterText").show();
				},

				function() {
					$(this).css( {"background-position": "0 0"} );
					$(".adSmallMonster div.adSmallMonsterText").hide();
				}
			)
		}
	};
	// end lf.ad.list.monsterMash
	
	
})(jQuery);

//lf.log(this);

