(function($){

	$.contact_form = function(options) {	
	
		var base = this;
		var theForm = $(options.form);
		var theItems = options.items;
		var selectItems = options.selectItems;
		var checkBoxItems = options.checkBoxItems;
		
		var successMsg = options.successMsg;
		var errorMsg = options.errorMsg;
		var emailErrorMsg = options.emailErrorMsg;
		var phoneErrorMsg = options.phoneErrorMsg;
		var noTwoWordsMsg = options.noTwoWordsMsg;
		
		var submitBtn = theForm.find(options.submitBtn);
		
		var statusMsgBox = $(options.statusMsgBox);
				
		var emailSubject = options.emailSubject;
		
		var targetEmail = options.targetEmail;		
		if (options.targetEmail_2) var targetEmail_2 = options.targetEmail_2;
		
		var phpSender = options.phpSender;
		var typeOfForm = options.typeOfForm;
		
		base.init = function() {
			
			base.setFlds();
			submitBtn.click(function () {
				base.sendForm();
			})
			
		}
	
		base.setFlds = function () {
			for (var i=0;i<theItems.length;i++) {
				if (theItems[i].interactive != '0') {
					var item = theItems[i];
					var fld = theForm.find("#"+item.fld);
					
					fld.data('orig', item.orig);					
					//fld.data('errorMsg', item.errorMsg);			
						
					fld.attr('value',item.orig);	
					fld.focus(function() {
						if ( $(this).val() == $(this).data('orig') ) $(this).attr('value','');
					})
					fld.blur(function() {
						if ($(this).val() == "") $(this).attr('value', $(this).data('orig'));
					})
				}
			}
		}
	
		base.resetFlds = function () {	
				
			for (var i=0;i<theItems.length;i++) {
				if (theItems[i].interactive != '0') {
					var item = theItems[i];
					var fld = theForm.find("#"+item.fld);
					
					fld.attr('value','');
				}
			}
			
			
			if (selectItems.length > 0) {
				for (i=0;i<selectItems.length;i++) {
					theForm.find("#"+selectItems[i].fld).val( jQuery("option:first", theForm.find("#"+selectItems[i].fld)).val() );
					
				}
			}
			
			if (checkBoxItems.length > 0) {
				for (i=0;i<checkBoxItems.length;i++) {
					theForm.find("#"+checkBoxItems[i].fld).attr('checked','checked');
				}
			}
			
		}
		
		
		base.validate_form = function () {
			
			for (var i=0;i<theItems.length;i++) {
				
				var theFld = theForm.find("#"+theItems[i].fld);
				
				if (theItems[i].req == '1' && (theFld.val() == null || theFld.val() == "" || base.testWhiteSpace( theFld.val() ) || theFld.val() == theItems[i].orig)) {
					alert(theItems[i].errorMsg);
					answer = false;
					break;
				} else {					
					if (theItems[i].fld == "senderMail") {
						
						if ( base.validate_email(theItems[i]) == false ) {
							theForm.find("#"+theItems[i].fld).focus();
							answer = false;
							break;
						} else {
							answer =  true;
						}
						
					} else if (theItems[i].fld == "senderPhone" ) {
						
						if ( base.validate_phone(theItems[i]) == false ) {
							theForm.find("#"+theItems[i].fld).focus();
							answer = false;
							break;
						} else {
							answer =  true;
						}
						
					} else if (theItems[i].fld == "senderName") {
						
						if ( base.twoWordsCheck(theForm.find("#"+theItems[i].fld).val()) == false ) {							
							theForm.find("#"+theItems[i].fld).focus();
							answer = false;
							alert(noTwoWordsMsg);
							break;							
						} else {
							answer =  true;
						}
						
					} else {
						answer =  true;
					}
				}								
			}
			
			// validate select dropdown
			if (answer == true) {
				for (var i=0;i<selectItems.length;i++) {				
					var theFld = theForm.find("#"+selectItems[i].fld);
					if (selectItems[i].req == '1' && theForm.find("#"+selectItems[i].fld).val() == "-") {
						alert(selectItems[i].errorMsg);
						answer = false;
						break;
					} else {
						answer = true;
					}
				}
			}
			
			
			
			if (typeOfForm == "sideBarContact" && answer == true && checkBoxItems.length > 0) {	//make sure checkbox is checked!	(for yandi)				
				for (i=0;i<checkBoxItems.length;i++) { 					
					if (!theForm.find("#"+checkBoxItems[i].fld).is(':checked')) {	
						alert ("נא לאשר קבלת עדכונים")					
						answer = false;
						break;
					} else {
						answer = true;
					}
				}
			}			
						
			return answer;	
					
		}
		
		base.testWhiteSpace = function (str) {
			return /^\s*$/.test(str)			
		}
	
		base.twoWordsCheck = function (str) {
			//var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
			var tagCheckRE = new RegExp("([א-תa-zA-Z]+)(\\s+)([א-תa-zA-Z]+)");
			return tagCheckRE.test(str);		
		}
				
		base.validate_phone = function (item) {
			var stripped = theForm.find("#"+item.fld).val().replace(/[\(\)\.\-\ ]/g, '');			
			
			if (item.req == "1") {				
				
				if (!isNaN(parseInt(stripped)) && ( (stripped.length == 7 && stripped.charAt(0) != "0") || (stripped.length == 9 && stripped.charAt(0) == "0") || (stripped.length == 10 && stripped.charAt(0) == "0") ) ) {
					return true;
					
				} else {
					alert(phoneErrorMsg);
					return false;
				}
			
			} else  {
				if (theForm.find("#"+item.fld).val() == item.orig || theForm.find("#"+item.fld).val() == "") {
					return true;
				} else {					
					
					if (!isNaN(parseInt(stripped)) && ( (stripped.length == 7 && stripped.charAt(0) != "0") || (stripped.length == 9 && stripped.charAt(0) == "0") || (stripped.length == 10 && stripped.charAt(0) == "0") ) ) {
					return true;
					
					} else {
						alert(phoneErrorMsg);
						return false;
					}
				}
			}
		}
		
		base.validate_email = function (item) {
			
			if (item.req == "1") {
				field = theForm.find("#"+item.fld);
				apos = field.val().indexOf("@");			
				dotpos = field.val().lastIndexOf(".");
				
				if (apos<1||dotpos-apos<2) {
					alert(emailErrorMsg);
					return false;
				} else {
					return true;
				}
			
			} else  {
				if (theForm.find("#"+item.fld).val() == item.orig || theForm.find("#"+item.fld).val() == "") {
					return true;
				} else {
					field = theForm.find("#"+item.fld);
					apos = field.val().indexOf("@");			
					dotpos = field.val().lastIndexOf(".");
					
					if (apos<1||dotpos-apos<2) {
						alert(emailErrorMsg);
						return false;
					} else {
						return true;
					}
				}
			}
		}
		
		
		base.sendForm = function () {
			
			if (theForm.find("#human").val() == "") {
				
	    		if (base.validate_form()) {
	    			//alert (theForm.find("#nameOfShow").val())
					var valuesToSend = "human="+theForm.find("#human").val() + "&subject="+encodeURIComponent(emailSubject) + "&targetEmail="+targetEmail + "&senderMail="+theForm.find("#senderMail").val() + "&senderName="+encodeURIComponent(theForm.find("#senderName").val());
					
					if (typeOfForm != "order") {
						
						for (var i=0;i<theItems.length;i++) {
							var temp = ( theForm.find("#"+theItems[i].fld).val() != theItems[i].orig ) ?  theForm.find("#"+theItems[i].fld).val()  :  "(Empty)" ;
							valuesToSend += "&fld_"+ i + "="+theItems[i].orig + "&val_"+ i + "="+encodeURIComponent(temp);						
						}
						
						if (selectItems.length > 0) {
							for (i=0;i<selectItems.length;i++) {
								valuesToSend += "&selectItem_"+ i + "="+selectItems[i].orig + "&selectVal_"+ i + "="+encodeURIComponent(theForm.find("#"+selectItems[i].fld).val());
							}
						}
						
						if (checkBoxItems.length > 0) {
							for (i=0;i<checkBoxItems.length;i++) { 
								valuesToSend += "&checkBoxItem_"+ i + "="+checkBoxItems[i].orig + "&checkVal_"+ i + "="+theForm.find("#"+checkBoxItems[i].fld).is(':checked');
							}
						}
						
						if (typeOfForm == "contact" && targetEmail_2 && $("#senderUpdates").is(":checked")) {
							valuesToSend += "&targetEmail_2="+targetEmail_2;
						}
						
					} else {						
						
						for (i=0;i<theItems.length;i++) {
							temp = ( theForm.find("#"+theItems[i].fld).val() != theItems[i].orig ) ?  theForm.find("#"+theItems[i].fld).val()  :  "(Empty)" ;
							valuesToSend += "&"+ theItems[i].fld + "="+temp;						
						}
						
						if (selectItems.length > 0) {
							for (i=0;i<selectItems.length;i++) {
								valuesToSend += "&"+ selectItems[i].fld + "=" + encodeURIComponent(theForm.find("#"+selectItems[i].fld).val());
							}
						}
						
						if (checkBoxItems.length > 0) {
							for (i=0;i<checkBoxItems.length;i++) { 
								valuesToSend += "&"+ checkBoxItems[i].fld + "=" + theForm.find("#"+checkBoxItems[i].fld).is(':checked');
							}
						}
						
					}
					
					
					//alert(valuesToSend)
										
					$.ajax({
						url: phpSender,
						type: 'POST',						
						data: valuesToSend,
						
						error: function(){
							alert('Error loading PHP script.');
						},
						
						success: function(answer){
							
							//statusMsgBox.html(answer);
							//alert (answer)						
							if (answer == "good") {
								if (typeOfForm != "order") {
									//alert (statusMsgBox.attr('id') + " : " + successMsg)
									statusMsgBox.html(successMsg);
									statusMsgBox.css('color','#69bd44')
									statusMsgBox.css('border','1px dotted #69bd44')
									base.resetFlds();
									statusMsgBox.css('display','block');
									setTimeout(function () {statusMsgBox.css('display','none'); base.setFlds()},5000);
								} else {
									
									gotoPage(BASE_URL+'/order_success.php');
									
								}
								
							} else {
								statusMsgBox.html(errorMsg);
								statusMsgBox.css('color','#C41111')
								statusMsgBox.css('border','1px dotted #C41111')
								statusMsgBox.css('display','block');
								setTimeout(function () {statusMsgBox.css('display','none')},5000);
							}
							
							
						}
					});
	
					
				}
	    	}
		}
			
		base.init();
		 
	};
	 
	
    $(document).ready(function() {
		$.fn.contact_form = function (options) {
		    return this.each(function() {
		        (new $.contact_form(options));
		    });
		};
	});

})(jQuery);



