$(document).ready(function(){

	var modal = 0;
	var pmodal = modal;
	var tweetform = fbform = linkform = mailform = false; // no forms opened yet not opened yet

	// preload gif animations
	$(['/app/img/link-animation.gif']).preload();
	$(['/app/img/fb-animation.gif']).preload();
	$(['/app/img/tweet-animation.gif']).preload();
	$(['/app/img/sending-mail.gif']).preload();

	$("#shareBtnContainerCover").click(function(){
		var virgin = $(this).css('display');
		//log(virgin);
		if(virgin=='block'){
			$('#msg').focus();

			$('#alert').show();
		
			setTimeout(function(){
				dtFade('alert', 0, 1000);
				
				setTimeout(function(){
					$('#alert').show();
				},1000);
			},2000);
		
			return;
		}else{
			return;
		}
	});

	//This changes global modal var, hides the right stuff, and fires up dialog based on rel attr of btn
	$('.dlg').click(function(){
		modal = $(this.parentNode).attr('rel');
		//hideshow( modal, 'hide');
		var dlgdiv = 'dtpimp';
		if(modal=='mailpimp'){dlgdiv=modal;}
		hideshow(dlgdiv,'hide');
		//log('modal is now: '+modal);
		eval(modal+'()'); //this fires the right modal;
	});

	$('.dlgCancel').click(function(){
		var _modal = getmodal();
		//log('mdst  is: ' + _modal);
		//hideshow( _modal, 'show');
		if(_modal=='mailpimp'){hideshow(_modal,'show');}else{hideshow('dtpimp','show');}
		modal = 0;
		$("#dlgResponseBtn").html("");//clean up for sharing service buttons
	});

	function getmodal(){
		return modal;
	}

	function shareDlg(state){
	
		var _m = srvcs[modal];
		var m = '#dtpimp';
	
		if(state==0){ 
			//show and hide stuff when activated
			//log('state is: '+state);
			$(m).find('#dlgTitle').html(_m.dlgTitle);
			$(m).find('#dlgWait').html(_m.dlgWait);//chain this together
			$(m).find('#dlgWait').show();
			$(m).find('#dlgResponse').hide();
			$(m).find('.dlgCancel').show();
			$(m).find('#dlgSubmit').hide();

		}else{ 
			//dialog changes on callback response
			$(m).find('#dlgTitle').html(_m.dlgTitleOnResponse);
			$(m).find('#dlgWait').hide();
			$(m).find('#dlgResponse').show();
			if(modal=='linkpimp'){
				$(m).find('.dlgCancel').hide();
				$(m).find('.btn').show();
				$(m).find('#dlgResponseInput').show();
				$(m).find("#dlgResponseBtn").hide();
			}else{
				$(m).find('#dlgResponseInput').hide();			
				$(m).find("#dlgResponseBtn").show();
				$(m).find('.btn').hide();
			}

		}
	}

	function mailpimp(){
	
		if (mailform==false){ // If first time, load event handlers for form
			mailform='true';
		
			$('.emailInput').live('click', function(){
				//log('clicked on email input');
				val = $(this).val();
				//log('val:|'+val+'|');
				defval = $(this).attr('title');
				//log('defval:|'+defval+'|');

				if(val == defval) { 
			       //log("val:|" + val + "| defval:|" + defval + "| = setting val to blank");
			       $(this).val("");
			    }else {
			       //log("val:|" + val + "| defval:|" + defval + "| = change");
			    }
			    if(val == ""){
				   //log("         Value is blank, so setting val to default");  
			       $(this).val(defval);     
			    }

			});
		
			$('.emailInput').live('blur', function(){
				//log('clicked on email input');
				val = $(this).val();
				//log('val:|'+val+'|');
				defval = $(this).attr('title');
				//log('defval:|'+defval+'|');

			    if(val == ""){ 
				   $(this).val(defval);
				   //log('         Value was blank, returning to default');
				}else{
				   //log('         Value is '+val);
				}
			});	
		
			//This will call formcheck() for check, then domail() to send mail
			$("#sendEmail").click(function(ev){
					//log('sendEmail clicked, calling form check first...');
					var good = formcheck();

					if (good == true){
					//log('form checked out');					
						// Calling do mail here
						doemail();
						//log('just called domail()');						
					}	
		  	});
		}
	
		//hideshow('mailpimp','hide'); // Hide other dt UI elements and show mailpimp div
		
		var email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // For form checking
		
		//This function checks the form, calls domail() if it checks out
		function formcheck(){
				  //log('we are in formcheck function');

			       var send_email = $("#sendEmailAddress").val();
					   //log('                    to email is '+send_email);
			       if(! email_regex.test(send_email)){

					  var send_email_fail=true;
			       }else {
			          $("#sendEmailAddressError").html('');
			          //log('                    send email regex match');
					  var from_email_fail=false;
			       }

			       var from_email = $("#sendEmailFromAddress").val();
			       if(! email_regex.test(from_email)){
			          //log('                    ...from email regex fail');
			          var from_email_fail=true;
			       }else {
			          $("#sendEmailFromAddressError").html('');
	         
								var from_email_fail=false;
			       }

					if(send_email_fail==true || from_email_fail==true){
						 if(send_email_fail==true){
						 $("#sendEmailAddressError").html("<span>&#42;please enter a valid email address</span>");
						 //log('                    ...send email address error');
						 }
					     if(from_email_fail==true){
						 $("#sendEmailFromAddressError").html("<span>&#42;please enter a valid email address</span>");
						 //log('                    ...from email address error');
						 }
						 if(send_email_fail==true){
							$("#sendEmailAddress").select();
						 }else{
							$("#sendEmailFromAddress").select();
						 }
					 //log('                    ...returning false');
					 return false;
					}


			   //log('                    ...returning true');
			   return true;
		}
	
		function doemail(){
				//log('inside domail()');
			
				emailStatus();
			
				function emailStatus(){ //this is where to show fields and do callback
				// Faking it here before domail response is even called
						$("#sendEmailFields").hide();
						$("#status").show();
						$("#emailDlgTitle").hide();
		                $("#status").html("<img src='/app/img/sending-mail.gif' border='0' />");
										
						setTimeout(function(){ // Fires after 4 sec, shows spinning email

							 $("#status").html("<span 			    id='email_checkmark'>&#10003;</span>");
						
							setTimeout(function(){ //Fires after 2 sec (5 secs)
							
								//Hides dialog, takes 0.6 sec
								hideshow('mailpimp', 'show');
							
								setTimeout(function(){ //Fires after 1.5 sec (6.5 secs)
									//log('hiding status and mailpimp');
									$("#status").hide();
									$("#sendEmailFields").show();
									$("#emailDlgTitle").show();
								},1500);
							},2000);
						},4000);
					}

				var theme = "theme="+encodeURIComponent(document.dreamForm.theme.value);
				var msg = "msg="+encodeURIComponent($("#msg").val());
				var postartist = 'artist='+encodeURIComponent($("#artist").val());
				var t = 'template='+encodeURIComponent($("#html_email_template").val());
				var from_name = 'from_name='+encodeURIComponent($("#sendEmailFromName").val());
				var from_address = 'from_address='+encodeURIComponent($("#sendEmailFromAddress").val());
				var to_address = 'to_address='+encodeURIComponent($("#sendEmailAddress").val());
				var img_format = 'img_format='+format;
				var postvars=theme+'&'+msg+'&'+postartist+'&'+t+'&'+from_name+'&'+from_address+'&'+to_address+'&'+img_format;
	
				$.ajax({
				  type: 'POST',
				 // url: './email/Swift-4.0.6/sendemail-simple-caching.php',
				  url: './app/includes/sg.php',
				  data: postvars,
				  complete: function(o){
					//log('responseText '+o.responseText);
				  }
		          //failure:responseFailure
				});
			
				return false;//Why false?
		}

	}

	function linkpimp(){
		shareDlg(0); //turns stuff on
		
		var src = document.dreamForm.dreamImg.src;	
		var src_e = encodeURIComponent(src);
		var type = 'scdn';
		var postvars = 'url=' + src_e + '&type='+type;
		log('http://www.dreamtype.com/createshare/getcdnNew.php?'+postvars);
		$.ajax({
		  type: 'POST',
		  url: '/createshare/getcdnNew.php',
		  data: postvars,
		  complete: function(o){
			log('responseText to jq ajax call in linkpimp is: '+o.responseText);
			var imglink = o.responseText;
			$('#responseInput').val(imglink);		
			shareDlg(1); //turns stuff off
		  }
	      //failure:responseFailure
		});
	
	}

	function fbpimp(){
		shareDlg(0); //turns stuff on

		var src = document.dreamForm.dreamImg.src;
		var src_e = encodeURIComponent(src);
		var type = 'lp';
	
		var postvars = 'url=' + src_e + '&type='+type;

		log('passing in: http://dreamtype.com/createshare/getcdnNew.php?'+postvars);
		$.ajax({
		  type: 'POST',
		  url: '/createshare/getcdnNew.php',
		  data: postvars,
		  complete: function(o){
			log('responseText to jq ajax call in fbpimp is: '+o.responseText);
			
			var resp = o.responseText.split('__:__');

			var lp_url = resp[0];
			var lp_url_e = encodeURIComponent(lp_url);
		
			var shareurl='http://www.facebook.com/sharer/sharer.php?u='+lp_url_e+'&t=Dreamtype';
			$("#dlgResponseBtn").html("<div id='fbShareLinkStatusBtn'><a href='"+shareurl+"' target='blank'></a></div>");
			shareDlg(1); //turns stuff off
		  }
	      //failure:responseFailure
		});

	}
	
	function tumblrpimp(){
		shareDlg(0); //turns stuff on

		var src = document.dreamForm.dreamImg.src;
		var src_e = encodeURIComponent(src);
		var type = 'lp';
		var postvars = 'url=' + src_e + '&type='+type;

		$.ajax({
		  type: 'POST',
		  url: '/createshare/getcdnNew.php',
		  data: postvars,
		  complete: function(o){
			//log('responseText to jq ajax call in teetpimp is: '+o.responseText);
							
			var resp = o.responseText.split('__:__');

			var lp_url = resp[0];
			var lp_url_e = encodeURIComponent(lp_url);

			var cdn_url = resp[1];
			var cdn_url_e = encodeURIComponent(cdn_url);
		
			var tumblr_photo_source = cdn_url_e;
			var tumblr_photo_caption = encodeURIComponent("&quot;" + $("#msg").val() + "&quot; &raquo; made at http://dreamtype.com");
			var tumblr_photo_click_thru = lp_url_e;
			
			var shareurl="http://www.tumblr.com/share/photo?source="+tumblr_photo_source+"&caption="+tumblr_photo_caption+"&clickthru="+tumblr_photo_click_thru;
			
			$("#dlgResponseBtn").html("<div id='tumblrShareLinkStatusBtn'><a href='"+shareurl+"' target='blank'></a></div>");
			shareDlg(1); //turns stuff off
		  }
		});
	
	
	}

	function tweetpimp(){
		shareDlg(0); //turns stuff on

		var src = document.dreamForm.dreamImg.src;
		var src_e = encodeURIComponent(src);
		var type = 'lp';
		var postvars = 'url=' + src_e + '&type='+type;
		log('passing in: http://dreamtype.com/createshare/getcdnNew.php?'+postvars);

		$.ajax({
		  type: 'POST',
		  url: '/createshare/getcdnNew.php',
		  data: postvars,
		  complete: function(o){
			log('responseText to jq ajax call in teetpimp is: '+o.responseText);
		
			var resp = o.responseText.split('__:__');

			var lp_url = resp[0];
			var lp_url_e = encodeURIComponent(lp_url);

			var shareurl='http://twitter.com/?status='+lp_url_e+'&t=Dreamtype';
			$("#dlgResponseBtn").html("<div id='tweetShareLinkStatusBtn'><a href='"+shareurl+"' target='blank'></a></div>");
			shareDlg(1); //turns stuff off
		  }
		});
	
	
	}

	//Default behaviors for modal flavors
	var srvcs ={
		linkpimp : {
			dlgTitle : " &nbsp;Generating link...",
			dlgTitleOnResponse :  "Short URL for this image",
			dlgWait : "<img src='/app/img/link-animation.gif' border='0' />"
		},
		fbpimp : {
			dlgTitle : " &nbsp;Generating link...",
			dlgTitleOnResponse : "Click to share",
			dlgWait : "<img src='/app/img/fb-animation.gif' border='0' />"
		},
		tweetpimp : {
			dlgTitle : " &nbsp;Generating link...",
			dlgTitleOnResponse :  "Click to share",
			dlgWait : "<img src='/app/img/tweet-animation.gif' border='0' />"
		
		},
		tumblrpimp : {
			dlgTitle : " &nbsp;Generating link...",
			dlgTitleOnResponse :  "Click to share",
			dlgWait : "<img src='/app/img/tumblr-animation.gif' border='0' />"
		}, 
		mailpimp : {
			dlgTitleOnResponse :  ""
		}	
	}

});//end of onready
