//variables
map = null;
mapDefaultGeo = false;

//start setting up the page as quickly as possible
$(document).ready(function() {
	
	x.loadJSTemplates(function(e){ _pageInit(e);});
	x.getImageURLs();

	if(confirmed == true) {
		alert("Your listing has been activated");
	}
	if(confirmed == false) {
		alert("We were unable to activate your listing");
	}
	
	$("#mapspace").hover(function(){
		$("#largemap_link img").fadeIn("slow");
		},
		function() {
		$("#largemap_link img").fadeOut("fast");
		});

	$("#search__content").listen( { 13:"$.cookie('location',$('#search__content').val());x.search()"} );
	
	$('#search__submit').click(function(){

		if(searchString = urlParam("searchString")) {
			$("#search__content").val(decodeURI(searchString));
		}
		x.search();
		$.cookie('location',$("#search__content").val());
		
	});
	
	if ($.cookie('location')) {
		$('#search__content').val($.cookie('location'));	
		$('#searchString').append($.cookie('location'));
	}
	
	$('.close').click(function(){
		$(this).parent().fadeOut();	
		$.cookie('noresults', '1');
	});
	
	if ($.cookie('noresults') == 1){
		$('.close').parent().css('display','none');	
	};
	
	// Function to make all <a href="#"> tags not reset page to top
	
	
	// Function to allow for delays in Jquery Animation
	$.fn.delay = function(time, callback)
		{
		    return this.animate({ opacity: '+=0' }, time, callback);
	}
	
	// Form Functions
	$('input:not(:submit)').focus(function(){
		if(this.value == this.defaultValue){
			this.value = "";
        	this.select();
    	};
	});
	$("textarea").focus(function(){
		if(this.value == this.defaultValue){
			this.value = "";
        	this.select();
    	}
	});
	
	$('#create_listing_boxes .home_box, .home_roll_btn').hover(function(){
		$(this).find('img').fadeIn('slow');
	}, function(){
		$(this).find('img').fadeOut('slow');	
	});
	
	$('.createlistingboxdiv').load('_tpl/html_sm/library/createlisting.box.html');
	
	
});


// Show Modal Function (jonas)

function showModal(modalname){
		var m = '#' + modalname;
		function modal() {
			var api1 = $(m).expose({color:"#06646e", api: true, maskId:'expose'});
			// Adjust modal height for screen (should change to $(window).height() and make it variable)
			if (screen.height < 600){
				$(m).css('max-height','200px')
				.css('overflow','auto').css('top','10px');
			} else if (screen.height < 700){
				$(m).css('max-height','275px')
				.css('overflow','auto').css('top','10px');
			} else if (screen.height < 800){
				$(m).css('max-height','350px')
				.css('overflow','auto').css('top','50px');
			}
			$(m).fadeIn();
			api1.load();
			$("#expose").click(function(){
				api1.close();
				$(m).fadeOut();
			});		
			$('.close').click(function(){
				api1.close();
				$(m).fadeOut();
			});		
				// ContactUs Functions
			$('input:not(:submit)').focus(function(){
				if(this.value == this.defaultValue){
					this.value = "";
		        	this.select();
		    	};
			});
			$("textarea").focus(function(){
				if(this.value == this.defaultValue){
					this.value = "";
		        	this.select();
		    	}
			});
		}
		if ($(m).length == 0) {
			$('#modal').append('<div id="' + modalname + 'container"></div>');
			$(m + 'container').load('_tpl/html_js/' + modalname + '.html', function(){
				modal();
			});
		} else {
			modal();	
		}
		
		

}
	// Tried to create a separate function so it worked in IE8 and ran into too much work 
	// rerouting tpE snippet stuff, so I think it makes more sense to start creating new function 
	// For a new database along with these.
	/* function showEditListingModal2(inMode, inListing){
			var m = '#editListing';
			function modal() {
			
				var api1 = $(m).expose({color:"#06646e", api: true, maskId:'expose'});
				var tpE = {"listingModal_header":"Create a new Listing", "saveButtonText":"Submit", "id":-1};
			
				editListing.sendMode = "new";
			
			
				if(typeof(inMode) == "string" && inMode == "edit") {
					tpE.listingModal_header = "Edit your Listing";
					tpE.saveButtonText = "Save Changes";
					tpE.id = inListing.id;
					tpE.s_confirm = inListing.s_confirm;
					editListing.sendMode = "edit";
				}
				$.modal($.snippet("edit_listing", tpE), editListingConfig);
				$("#listing__zip").listen(
						{	27:function(e, listener) { $("#listing__zip").val("");},
							"regEx":/^[0-9]{0,5}-?([0-9]){0,4}$/,					
							"invalidAction":"swallowKey"
						}
				);
				$("#listing__listing_type").val(inListing.type);
			
			
				// Adjust modal height for screen (should change to $(window).height() and make it variable)
				if (screen.height < 600){
					$(m).css('max-height','200px')
					.css('overflow','auto').css('top','10px');
				} else if (screen.height < 700){
					$(m).css('max-height','275px')
					.css('overflow','auto').css('top','10px');
				} else if (screen.height < 800){
					$(m).css('max-height','350px')
					.css('overflow','auto').css('top','50px');
				}
			
				$(m).fadeIn();
				api1.load();
			
				$("#expose").click(function(){
					api1.close();
					$('#editListing').fadeOut();
				});		
				$('.close').click(function(){
					api1.close();
					$(m).fadeOut();
				});		
			
				// ContactUs Functions
				$('input:not(:submit)').focus(function(){
					if(this.value == this.defaultValue){
						this.value = "";
			        	this.select();
			    	};
				});
				$("textarea").focus(function(){
					if(this.value == this.defaultValue){
						this.value = "";
			        	this.select();
			    	}
				});
			}
			if ($(m + 'container').length == 0) {
				$('#modal').append('<div id="' + m + 'container"></div>');
				$(m + 'container').load('_tpl/html_js/' + modalname + '.html', function(){
					modal();
				});
			} else {
				modal();	
			}
		
		

	} */



// Main Y2G Send by Jonas(found from http://www.faridhadi.com/submitting-a-form-without-reloading-the-page-using-jquery-and-ajax/)
	function y2gSend(form) { 
		$('#' + form + '.formProgress').html('Mail is being processed');
		$('#' + form + '.submit').attr("disabled", "disabled");
		var isFocus=0;
		var isError=0;
		// Get the data from the form
		var to=$('#' + form + ' #form_to').val();
		var name=$('#' + form + ' #sender_name').val();
		var email=$('#' + form + ' #sender_email').val();
		var subject=$('#' + form + ' #form_subject').val();
		var message=$('#' + form + ' #sender_message').val();
		var location=$('#' + form + ' #sender_location').val();
		
		//Validate 
	
		if(name=='' || name=='your name') {
			$('#' + form + ' input#sender_name').siblings('span').show().html('required');
			$('#' + form + ' #sender_name').focus();
			isFocus=1;
			isError=1;
		}
		if((email=='') || (email == 'your email')) {
			$('#' + form + ' input#sender_email').siblings('span').show().html('required');
			if(isFocus==0) {
				$('#' + form + ' #sender_email').focus();
				isFocus=1;
			}
			isError=1;
		} else {
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			if(reg.test(email)==false) {
				$('#' + form + ' #sender_email').siblings('span').show().html('required');
				if(isFocus==0) {
					$('#' + form + ' #sender_email').focus();
					isFocus=1;
				}
				isError=1;
			}
		}
		if(message=='' || message == 'message') {
			$('#' + form + ' #sender_message').siblings('span').show().html('required');
			if(isFocus==0) {
				$('#' + form + ' #sender_message').focus();
				isFocus=1;
			}
			isError=1;
		}
		// Terminate the script if an error is found
		if(isError==1) {
			$('#' + form + ' .formProgress').html('');
			$('#' + form + ' .formProgress').hide();	
			// Activate the submit button
			$('#' + form + ' .submit').attr("disabled", "");
			$('#' + form + ' span').fadeOut(6000 ,function(){ });
			return false;
		}
		
		$.ajaxSetup ({  
			cache: false  
		});
		var dataString = 'name='+ name + '&to=' + to + '&email=' + email + '&location=' + location + '&subject=' + subject + '&message=' + message;  
		$.ajax({  
			type: "POST",
			url: "scripts/y2gContactUs.php",
			data: dataString,
			success: function(msg) {
				// Check to see if the mail was successfully sent
				if(msg=='Mail sent') {
					// Update the progress bar
					// Clear the fields textbox
					$('#' + form + ' input:not(:submit)').val('');
					$('#' + form + ' textarea').val('');
					// Fade Out Form
					$('#' + form + '').fadeOut();
					// Success Message
					$('#' + form + ' .formProgress').show().html('Congratulations! Your message was sent, we will get back to you soon.').delay(2000).fadeOut(400);
					// Fade Form Container
					$('#' + form + 'container').fadeOut();
					// Fade Out expose and Modal
					$('#expose').fadeOut();
					// remove contact form from HTML
					$('#' + form + 'container').remove();
				} else {
					$('#' + form + ' .formProgress').html('Message could not be sent').delay(2000).fadeOut(400);
					alert('There was an error sending your email. Please try again later, or contact jesse@y2g.org directly.');
				}
				// Activate the submit button
				$('#' + form + ' .submit').attr("disabled", "");
				
			},
			error: function(ob,errStr) {
				
				$('#' + form + ' .formProgress').html('');
				alert('There was an error sending your email. Please try again.');
				// Activate the submit button
				$('#' + form + ' .submit').attr("disabled", "");
				
			}
		});
		return false;
	
	}
	
// Resend Confirmation Function
function resendConfirmation() {
			
			$sql = " SELECT s_confirm, title, email FROM listing WHERE email = 'jgoslow@gmail.com', active = 'true' ";
			print ('listing');
			
			//email
			//require("../smarty_setup.php");
			//$smarty->assign("listing", $inListing);
			//$smarty->assign("domain_url", W_ROOT);
			//$mailBody = $smarty->fetch("email_confirm.html");
			
			//$headers = "From: Yards to Gardens <" . $this->noReply . ">\r\nReply-To: Yards to Gardens <" . $this->noReply . ">\r\nX-Mailer: PHP/" . phpversion();
			//$result = mail($inListing["email"], "Y2G listing - " . $inListing["title"], $mailBody, $headers);
			//return($this->ro(true, "", "Please check your email for a confirmation code to publish your listing. <br /> <br /> If you don't recieve anything soon, check your spam box to make sure it wasn't flagged, or email help@y2g.org and we'll send you another activation email. <br /><br /> thanks!"));
	
		
			//{{$domain_url}}index.php?confirm={{$listing.s_confirm}}	
			
}

//called after getting js templates. Various elements depend on them.
function _pageInit(inSnippets)  {
	if(inSnippets.ok) {
		$.setSnippetLib(inSnippets.data);
	} else {
		$.log(inSnippets);
		alert("there was some html we couldn't load. Some aspects of the page may not function properly.");
	}

	if(confirmString) {
		x.editListing(confirmString);
	}

	if(document.getElementById("map_canvas")!= null) {
		google.load("maps", "2", {callback:_gmapInit});
	}
	validate = new Validation();
}

function _gmapInit() {
	map = new google.maps.Map2(document.getElementById("map_canvas"));
		map = new GMap2(document.getElementById("map_canvas"));
		mapDefaultGeo = new GLatLng(44.9771, -93.2655);
		if(google.loader.ClientLocation) {
			mapDefaultGeo = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
		}
		map.setCenter(mapDefaultGeo, 13);
		map.setUIToDefault();
		map.disableScrollWheelZoom();
		if(searchString = urlParam("searchString")) {
			$("#search__content").val(decodeURI(searchString));
		}
		x.search();
}

function clearInput(inName) {
	switch(inName) {
		case "search__content" :
			if("enter address or zip here" == $("#" + inName).val())
				$("#" + inName).val("");
			break;
		default :
			$("#" + inName).val("");
	}
}

function getIframeBody(inID) {
	mainMenu.select(inID);
	$("#mainPanel").html($('#contentFrame').contents().find('body').html());
	//alert($('#contentFrame').contents().find('title').html());
	document.title = "Edible Exchange - " + $('#contentFrame').contents().find('title').html();
}


	

	
	Common.prototype.emailListing_cb = function(e) {
		if(!e.ok) {
			alert("couldn't email"); return(false);
			$.modal.close();
		}
		else {
			$('#contact-container .contact-title').html("Success!");
			$("div.contact-content form").html("<table style='width:100%; height:100%;'><tr><td valign='middle' align='center'>Message sent.</td></tr></table>");
		}
		
		
	}




function showContactListingModal(inID) {
	var tpE = false;
	for(i in x.searchResults.listings) {
		if(x.searchResults.listings.hasOwnProperty(i)) {
			if(x.searchResults.listings[i].id == inID) {
				tpE = x.searchResults.listings[i]
			}
		}
	}
	if(tpE) {
		$.modal.close(); 
		$.modal($.snippet("contact_listing", tpE), editListingConfig);
	} else {
		alert("couldn't find the listing you want to contact");
	}
}


function showEditListingModal(inMode, inListing) {
	var tpE = {"listingModal_header":"Create a new Listing", "saveButtonText":"Submit", "id":-1};
	editListing.sendMode = "new";
	if(typeof(inMode) == "string" && inMode == "edit") {
		tpE.listingModal_header = "Edit your Listing";
		tpE.saveButtonText = "Save Changes";
		tpE.id = inListing.id;
		tpE.s_confirm = inListing.s_confirm;
		editListing.sendMode = "edit";
	}
	$.modal.close(); 
	$.modal($.snippet("edit_listing", tpE), editListingConfig);
	$("#listing__zip").listen(
			{	27:function(e, listener) { $("#listing__zip").val("");},
				"regEx":/^[0-9]{0,5}-?([0-9]){0,4}$/,					
				"invalidAction":"swallowKey"
			}
	);
	$("#listing__listing_type").val(inListing.type);	
}

function urlParam(param) {
    var regex = '[?&]' + param + '=([^&#]*)';
    var results = (new RegExp(regex)).exec(window.location.href);
    if(results) return results[1];
    return false;
}




var editListing = {
		message: null,
		open: function (dialog) {
			// add padding to the buttons in firefox/mozilla
			if ($.browser.mozilla) {
				$('#contact-container .contact-button').css({
					'padding-bottom': '2px'
				});
			}
			// input field font size
			if ($.browser.safari) {
				$('#contact-container .contact-input').css({
					'font-size': '.9em'
				});
			}

			// dynamically determine height
			var h = 480;
			var wh = $(window).height() - 800;
			if ($('#contactListing__message').length > 0) {
				h -= 145;
			}
			if ($(window).height() < 600){
				h = wh + 650;
				$('#contact-container .contact-content').css('overflow','auto');
			}
			if ($('#embed_listings').length < 0) {
				h = 470;
				if ($('#contactListing__message').length > 0) {
					h -= 145;
				}
				
				if ($('#embed_listings').height() < 600){
					lh = ('#embed_listings').height() - 800;
					h = lh + 650;
					$('#contact-container .contact-content').css('overflow','auto');
				}
			}
			//if ($('#contact-cc').length) {
			//	h += 22;
			//}

			var title = $('#contact-container .contact-title').html();
			$('#contact-container .contact-title').html('Loading...');
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200, function () {
						$('#contact-container .contact-content').animate({
							height: h
						}, function () {
							$('#contact-container .contact-title').html(title);
							$('#contact-container form').fadeIn(200, function () {
								$('#contact-container #contact-name').focus();

								$('#contact-container .contact-cc').click(function () {
									var cc = $('#contact-container #contact-cc');
									cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
								});

								// fix png's for IE 6
								if ($.browser.msie && $.browser.version < 7) {
									$('#contact-container .contact-button').each(function () {
										if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
											var src = RegExp.$1;
											$(this).css({
												backgroundImage: 'none',
												filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
											});
										}
									});
								}
							});
						});
					});
				});
			});
		},
		show: function (dialog) {
			x.getNewToken();
			$('#contact-container .contact-send').click(function (e) {
				e.preventDefault();
				//validate form
				var values = validate.listing();				
				if(!values) {
					alert("please check the colored fields");
				} else {
					values.token = x.currentToken;
					if(parseInt(values.id) < 0) {
						x.newListing(values);
					} else {
						values.s_confirm = $("#listing__s_confirm").val();
						x.saveListing(values);
					}
					$('#contact-container .contact-title').html('Sending...');
				}
			});
			$('#contact-container .contact-send-email').click(function (e) {
				e.preventDefault();
				x.contactListing();
			});
		},
		close: function (dialog) {
			$('#contact-container .contact-message').fadeOut();
			$('#contact-container .contact-title').html('Goodbye...');
			$('#contact-container form').fadeOut(200);
			$('#contact-container .contact-content').animate({
				height: 40
			}, function () {
				dialog.data.fadeOut(200, function () {
					dialog.container.fadeOut(200, function () {
						dialog.overlay.fadeOut(200, function () {
							$.modal.close();
						});
					});
				});
			});
		},
		error: function (xhr) {
			alert(xhr.statusText);
		}
	};

	
function Validation() {
	return(this);
}


Validation.prototype.email = function(inEmail) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(inEmail) == false) {
      return false;
   } 
   return true;
}


Validation.prototype.zip = function(inZip) {
	var reg = /^[0-9]{5}(-[0-9]{4})?$/;
	if(reg.test(inZip) == false) {
		return false;
	} 
	return true;
}


Validation.prototype.listing = function() {
	var listing = $.ofd(["id", "title", "name", "email", "description", "street", "zip", "phone", "listing_type"],"listing__");
	var ret = true;
	$("#listing__email, #listing__name, #listing__street, #listing__zip").css("background", "");
	if(!this.email(listing.email)) {
		ret = false;
		$("#listing__email").css("background", "#FFAAAA");
	}
	if(listing.name.length < 2) {
		ret = false;
		$("#listing__name").css("background", "#FFAAAA");
	}
	if(listing.street.length < 2) {
		ret = false;
		$("#listing__street").css("background", "#FFAAAA");
	}
	if(!this.zip(listing.zip)) {
		ret = false;
		$("#listing__zip").css("background", "#FFAAAA");
	}
	if(!ret) {
		return false;
	}
	return listing;
}


//CONFIG OBJECTS
editListingConfig = {
	close: false,
	position: ["10%",],
	overlayId: 'contact-overlay',
	containerId: 'contact-container',
	onOpen: editListing.open,
	onShow: editListing.show,
	onClose: editListing.close
}

