﻿var SendToAFriend={
	init:function () {
	},
	
	showForm:function (adId,relative) {		
		Mantis.EyeBlaster.Services.SendToAFriendService.GetSendToAFriendFormSource(adId,function (source) {
			var el=new Element("div").adopt(Element.fromMarkup(source,true));
			SendToAFriend.initForm(el,adId);
			
			(function(){var lb=new SiteLightbox(el).show();}).delay(50); 
			
		});
	},
	
	mailRx:/^[\w-\.]+@([a-z0-9\-]+\.)+[a-z]{2,5}$/i,
	
	initForm:function (element,adId) {		
		var query="/SendAdToAfriendOpen?adId="+adId;				
		Site.trackStats(query);
		
		var form=element.getElement("form");
		
		form.addReplacingEvent("submit",function (e) {
			//check fields
			var emailToValue = form["send-friend-EmailTo"].value.trim();
			if(!SendToAFriend.mailRx.test(emailToValue)){alert("Please enter a valid email"); return;}

			var yourNameValue = form["send-friend-YourName"].value.trim();
			if(!yourNameValue) {alert("Please enter your name"); return;}
			
			var yourEmailValue = form["send-friend-YourEmail"].value.trim();
			if(!SendToAFriend.mailRx.test(yourEmailValue)){alert("Please enter a valid email"); return;}
			
			var yourNotesValue = form["send-friend-YourNotes"].value.trim();
			
			var attachMyNotes = false;
			if(form.getElement(".designed-checkbox")){
				if(form.getElement(".designed-checkbox").className=="designed-checkbox checked"){
					attachMyNotes = true;
				}
			}
			
			SendToAFriend.sendToAFriend(adId,emailToValue,yourNameValue,yourEmailValue,yourNotesValue,attachMyNotes,SendToAFriend.FormSent.bind(null));			
		});
		form.getElement(".cancel").addEvent("click",function () {
			Lightbox.hide();
		});
	},
	
	sendToAFriend:function (adId,emailTo,yourName,yourEmail,yourNotesValue,attachMyNotes,callback) {
		var query="/SendAdToAfriendSubmit?adId="+adId;
		Site.trackStats(query);
		Mantis.EyeBlaster.Services.SendToAFriendService.SendToAFriend(adId,emailTo,yourName,yourEmail,yourNotesValue,attachMyNotes,function (success) {
			if (callback) callback(success);
		});
	},
	
	FormSent:function () {
		$("send-friend-form-form").hide();
		$("send-friend-after").show();
		(function () {
			Lightbox._container.effect("opacity").start(0).chain(function () {
				Lightbox.hide();
				Lightbox._container.setStyle("opacity",1);
			});
		}).delay(2000);		
	}

};

Events.makeObjectEventable(SendToAFriend);

$DL(SendToAFriend.init);

