/*
 * Main JS file for www.verkuhl.com 
 *
 */

jQuery(function($){
	var featureBuilder = {
	  // code for building the feature sections of the pages
	  settings: {
	    // defaults
	    delay:0, // initial delay
	    interval:10000, // time between features in ms
	    speed:300, 
	    subDelay:700, // delay between components
	    loop:false, 
	    effect:null // the effect to use
	  },
	  features: [
          {prop: "top", to:"0", from:"400px"},
          {prop: "opacity", to:"1", from:"0"},
          {prop: "left", to:"10px", from:"939px"}
	  ],  
	  init: function(settings, features) {
	     // set up clickthroughs
      $('div.feature-item').each(function(){
        if($(this).children('a').length == 0){
          $(this).css('cursor', 'auto');
        }
      })
	     $('div.feature-item').click(function(){
         if($(this).children('a').length != 0){
           window.location.href = $(this).children('a').attr('href');
         }
	     })
	    // set up variables
	    var featureItems = $("div.feature-item");
      var activeFeature = $("div.feature-item").first();
      var lastFeature = $("div.feature-item").length - 1;
      var timeouts = [];
      playFeature();
       
       $('div#feature-controls  nav  a').click(function(e){
           e.preventDefault();
           if($(this).index() != activeFeature.index()){
               var oldFeature = activeFeature;
               activeFeature = $("div.feature-item").slice($(this).index(), $(this).index()+1);
               oldFeature.removeClass('active');
               oldFeature.stop(true)
               clearAllTimeouts();
               var that = $(this)
               oldFeature.fadeOut(500, function(){
                playFeature();
                $('div#feature-controls  nav  a').each(function(){
                    $(this).removeClass('active');
                })
                that.addClass('active')
             })
           }
       })
       function clearAllTimeouts(){
           for (var i = timeouts.length - 1; i >= 0; i--){
            clearTimeout(timeouts[i]);
           };
       }
      // feature animations
      function playFeature(){
        var useCSS = main.supportsCSSTransition();
        var prop = features[activeFeature.index()].prop;
        var from = features[activeFeature.index()].from;
        var to = Object();
        to[prop] = features[activeFeature.index()].to;
        activeFeature.addClass('active');
        var components = activeFeature.children('.feature-component');
        //
        if(useCSS){
            $("div#feature-shadow").css({"display":"block", "opacity":"0"})
      	    $("div#feature-shadow").animateWithCss({opacity:1}, settings.speed, "cubic-bezier");
      	    activeFeature.css("display", "block")
            activeFeature.animateWithCss({opacity:1},500, "cubic-bezier");
        } else {
            activeFeature.show();
            // fade in the shadow
            $("div#feature-shadow").fadeIn(settings.speed);
        }
        components.each(function() {
          $(this).css("display","none")
        });
        var last = components.length - 1;
        // if we are only using images then we need to ignore components
        if(components.length == 0){
          timeouts[timeouts.length] = setTimeout(function(){
            $("div#feature-shadow").fadeOut(500);
            activeFeature.fadeOut(500, function() {
              activeFeature.removeClass('active');
              if(activeFeature.index() != lastFeature){
                activeFeature = activeFeature.next('div.feature-item');
              } else {
                activeFeature = featureItems.first();                                        
              }
              $('div#feature-controls  nav  a').each(function(){
                $(this).removeClass('active');
              })
              $('div#feature-controls  nav  a').slice(activeFeature.index(), activeFeature.index()+1).addClass('active');
              playFeature();     
            });
          }, settings.interval);
        } else {
          // otherwise use components
            $.each(components, function(index,value){
                var that = $(this);
                var delayTime = (settings.subDelay + settings.speed) * parseInt(index);
                if(parseInt(index) == 0){
                  delayTime = 0;
                }
                timeouts[timeouts.length] = setTimeout(function(){
                    that.css(prop, from);
                    that.show();
                    // begin check for CSS support      
                    if(!useCSS){
                      // use jQuery
                        that.animate( to, settings.speed, "easeInOutExpo", function() {   
                            if(parseInt(index) == last){
                                // set interval to go to the next one
                                timeouts[timeouts.length] = setTimeout(function() {
                                    $("div#feature-shadow").fadeOut(500);
                                    activeFeature.fadeOut(500, function() {
                                        activeFeature.removeClass('active');
                                      if(activeFeature.index() != lastFeature){
                                          activeFeature = activeFeature.next('div.feature-item');
                                        } else {
                                          activeFeature = activeFeature.parents("div.feature-animated").children('div.feature-item').first();                                        
                                      }
                                      $('div#feature-controls  nav  a').each(function(){
                                          $(this).removeClass('active');
                                      })
                                      $('div#feature-controls  nav  a').slice(activeFeature.index(), activeFeature.index()+1).addClass('active')
                                      playFeature();     
                                    });
                                  }, settings.interval);
                                }
                            });
                    } else {
                        // use css
                        that.animateWithCss(to, settings.speed, "cubic-bezier", function(){
                            if(parseInt(index) == last){
                                activeFeature.removeClass('active');
                                // set interval to go to the next one
                                timeouts[timeouts.length] = setTimeout(function() {
                            	      $("div#feature-shadow").animateWithCss({opacity:0}, settings.speed, "cubic-bezier");
                                    activeFeature.animateWithCss({opacity:0},500,"cubic-bezier", function() {
                                    if(activeFeature.index() != lastFeature){
                                        activeFeature = activeFeature.next('div.feature-item');
                                      } else {
                                        activeFeature = activeFeature.parents("div.feature-animated").children('div.feature-item').first();                                        
                                    }
                                    $('div#feature-controls  nav  a').each(function(){
                                        $(this).removeClass('active');
                                    })
                                    $('div#feature-controls  nav  a').slice(activeFeature.index(), activeFeature.index()+1).addClass('active')
                                    playFeature();     
                                  });
                                }, settings.interval);
                              }
                          })
                      } 
                     // end check for CSS support        
                    }, delayTime)
                  })
                }
            }
          }  
	  };
	
	var main = {
		message:null,
		isIOS: function(){
		  var bool
		  switch(navigator.platform){
				case "iPad":
				bool = true;
				break;
				case "iPhone":
				bool = true;
				break;
				case "iPod":
				bool = true;
				break;
				default :
				bool = false;
				break;
			}
			return bool;
		},
		supportsCSSTransition: function() {
      // don't like how these animations are shaking out so I'm disabling this for now
		  if($("html").hasClass('cssanimations')){
		    return false;
		  } else {
		    return false;
		  }
		},
		init: function (){
        // smooth scroll named anchors
        $('a[href^=#]').smoothScroll();
		    // listeners for work items
		    // taking off the hover listeners for iOS 
		     if(!main.isIOS()){
		         $('div.work-item').hover(function(){
     		        var that = $(this);
     		        if(!that.hasClass('inMotion')){
         		        that.addClass('inMotion')
                    that.children('.work-item-text').fadeOut(300)
                    that.children('.work-item-learnmore').slideDown(300);
                    that.children('.work-item-bg').fadeIn(300, function(){
                        that.removeClass('inMotion')
                    });
     		        }
     		    }, function(){
     		        var that = $(this);
                that.children('.work-item-text').fadeIn()
                that.children('.work-item-learnmore').slideUp();
                that.children('.work-item-bg').fadeOut();
     		    })
     		    
		     }
		     $('div.work-item').click(function() {
		       // make a click on the item go to the href in the learn more link
           window.location.href = $(this).children(".work-item-learnmore").children('a').attr('href');
		     });
		     
		  if($('#map_canvas').length != 0){
		    main.createMap();
		  }
			// check for iphone 
			// and make mailto links open mail instead of modal form
			var useMailTo = main.isIOS();
			// set up listeners
			// select all text on focus of form fields
			$("input, textarea").focus(function(){
				this.select();
			});
			$("input, textarea").mouseup(function(e){
			  e.preventDefault();
			});
			// detect enter keypress while in a form field
			$("input").keypress(function(e) {
				var formId = ($(this).parents(["form"]).attr("id"));
				switch(e.keyCode){
					case(13):
					if (formId == "notify_form") {
						$("a#notify_submit").click();
					} else if (formId == "contact_form") {
						$("a#contact_submit").click();
					};
					break;
					default:
					break;
				}
			});
			// get token for the forms
			$.get('/data/cookie.php', function(data){
			 $("#notify_form").append('<input type = "hidden" name = "token" id = "notify_token" value="' + data + '"/>');
			 $("#contact_form").append('<input type = "hidden" name = "token" id = "contact_token" value="' + data + '"/>');
			});
			// listener for modal contact form popup
			// check to see if the device runs iOS
			if (useMailTo === false) {
				$("a.contact-link").click(function(event){
					event.preventDefault();
					// set the modal to the true center of the document
					var posX = $(document).width() - ($("#modal").width / 2);
					// display the modal
					$("#modal").modal({
						opacity:75, 
						overlayClose:true, 
						position:[70, posX],
						onOpen: main.open, 
						onClose: main.contactClose
					});
				});
			};
			$("a#notify_submit").click(function(event) {
				event.preventDefault();
				// validate input locally
				main.validate($(this).attr("id"))
			});
			$("a#contact_submit").click(function(event) {
				event.preventDefault();
				main.validate($(this).attr("id"))
			});
			// check for textarea placeholder support, fallback with jQuery
			// function to test for support
			function elementSupportsAttribute(element, attribute) {
			  var test = document.createElement(element);
			  if (attribute in test) {
			    return true;
			  } else {
			    return false;
			  }
			};
			// test for placeholder
			if (!elementSupportsAttribute('textarea', 'placeholder')) {
				$("#contact_message")
			    .data("originalText", $("#contact_message").text())
			    .focus(function() {
			        var $el = $(this);
			        if (this.value == $el.data("originalText")) {
			          this.value = "";
			        }
			    })
			    .blur(function() {
			      if (this.value == "") {
			          this.value = $(this).data("originalText");
			      }
			    });
			} else {
			  // Browser does support HTML5 placeholder attribute, so use it.
			  $("#contact_message")
			    .attr("placeholder", $("#contact_message").text())
			    .text("");
			}
		},
		// opening and closing animations
		open: function(dialog){
			dialog.overlay.fadeIn(200, function(){
				dialog.container.fadeIn(200, function(){
					dialog.data.slideDown('slow')
				})
			})
		},
		close: function(dialog){
			dialog.data.slideUp('slow', function(){
				dialog.container.fadeOut(200, function(){
					dialog.overlay.fadeOut(200, function(){
						$.modal.close();
					})
				})
			})
		},
		contactClose : function(dialog){
			$("#modal_alert").hide();
			dialog.data.slideUp('slow', function(){
				dialog.container.fadeOut(200, function(){
					dialog.overlay.fadeOut(200, function(){
						$.modal.close();
					})
				})
			})
			
		},
		error: function(xhr){
			
		},
		
		// helper functions and callbacks go here
		validate: function(form){
			switch(form) {
				case "notify_submit":
				// check for defaults, empties and invalid email addresses
				if($("#notify_name").val() == "" || $("#notify_email").val() == "" || main.validateEmail($("#notify_email").val()) != true || $("#notify_name").val() == "your name" || $("#notify_email").val() == "your email"){
					// make the text orange
					$("#notify_form input").animate({color:'#f89e02'}, 200);
					// add an error message
					$("#alert").addClass("error");
					$("#alert p").html("Sorry, we need these in order to contact you")
					// fade it out if it's already there
					// so the user has feedback on the button
					$("#alert").fadeOut(200);
					$("#alert").fadeIn(200)
				}  else {
					// generate xhr request to compose an email to hello_at_verkuhl.com
					$.post('/data/contact.php',{
						action:"send",
						name:$("#notify_name").val(),
						subject:"notify me when verkuhl.com is live, please.",
						email:$("#notify_email").val(),
						ts:$("#notify_token").val()
					},
					 function(data){
					});
					$("#alert").fadeOut(200);
					$("#notify_submit").slideUp(200);
					$("#notify_form").slideUp(200, function(){
						$("p#notify").fadeOut(200, function(){
							$("p#notify").html("Thanks. We&rsquo;ll let you know when our site is up!");
							$("p#notify").fadeIn(200);
						});
					});
				}
				break;
				case "contact_submit":
				if($("#contact_name").val() == "" || $("#contact_email").val() == "" || main.validateEmail($("#contact_email").val()) != true || $("#contact_name").val() == "your name" || $("#contact_email").val() == "your email"){
					// invalid
					$("#contact_form input").animate({color:'#f89e02'}, 200);
					// pop a div over the message
					$("#contact_inner").append("<div id = 'modal_alert' style='display:none'><p>Sorry, we need these in order to contact you</p></div>");
					var theTop = ($("#contact_message").position().top);
					var theLeft = ($("#contact_message").position().left);
					// safari does add a couple of pixels padding...
					var thePaddingBottom = ($("#contact_message").css('padding-bottom'));
					var thePaddingRight = ($("#contact_message").css('padding-right'));
					// so let's add them to the w & h
					var theHeight = parseInt($("#contact_message").css('height')) + parseInt(thePaddingBottom);
					var theWidth = parseInt($("#contact_message").css('width')) + parseInt(thePaddingRight);
					// alert(theLeft)
					$("#modal_alert").fadeIn(300, function(){
						var that = $(this);
						setTimeout(function(){
							that.fadeOut(300, function(){
								that.remove();
							})
						}, 2000)
					})
					$("#modal_alert").css({'top':theTop, 'left':theLeft, height:theHeight, width:theWidth})
					
					return;
				} else {
					// valid
					$.post('/data/contact.php',{
						action:"send",
						name:$("#contact_name").val(),
						subject:"message from verkuhl.com holdpage",
						email:$("#contact_email").val(),
						message:$("#contact_message").val(),
						ts:$("#contact_token").val()
						},
					 function(data){
						if(data == "success"){
							$("#contact_header h2").html("");
							$("#contact_inner p").html("");
							$("#contact_form").remove();
							$("#contact_submit").remove();
							$("#modal #contact_body").animate({height:97}, "fast");
							$("#modal #contact_inner").animate({height:68}, "fast");
							$("#simplemodal-container").animate({marginTop:120, height:165}, "fast");
							$('#modal').animate({ height: 165}, "fast", function () {
								$("#contact_header h2").html("thank you!");
								$("#contact_inner p").html("we got your note and will be in touch soon.");
								setTimeout(function(){
									$.modal.close();
								}, 
								5000);
							});
						} else {
							// just do nothing
						}	
					});
				}
				default:
				break;
			}
		},
		createMap: function() {
		  if($("#map_canvas").length != 0){
        var latlng = new google.maps.LatLng(40.740802,-73.991982);
        var myOptions = {
          zoom: 17,
          center: latlng,
          disableDefaultUI: true,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map($("#map_canvas")[0],myOptions);
        var marker = new google.maps.Marker({
          position: latlng
        });
        marker.setMap(map)

        var contentString = '<div id="content">'+
            '<div id="siteNotice">'+
            '</div>'+
            '<h1><img src="images/verkuhl_logo_small.png" width="88" height="23" alt="VerkuhlLogo"> </h1>'+
            '<div id="bodyContent">'+
            '<p style="width:250px;padding-left:30px">Verkuhl is a full-service digital marketing agency that combines strong strategic thinking with an eye for innovative, intuitive design to create uniquely engaging digital experiences — all delivered with an unparalleled commitment to client service.</p>'+
            '<p style="width:250px;padding-left:30px"><a href="http://maps.google.com/maps?hl=en&georestrict=input_srcid:240ff29a237aed3d&ie=UTF8&view=map&f=d&daddr=22+w+21st+st+8th+fl,+New+York,+NY+10010&geocode=CRL6tPp_p00UFVqnbQId3fiW-yFh3D_1BXtFwA&ved=0CBMQ_wY&sa=X&ei=QucnTbPpJov6yAWijrH2DA">Check us out</a></p>'+
            '</div>'+
            '</div>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        google.maps.event.addListener(marker, "click", function(){
          infowindow.open(map,marker);
        })
		  }
		},
		// 
		validateEmail: function (email) {
			var at = email.lastIndexOf("@");
			// Make sure the at (@) sybmol exists and  
			// it is not the first or last character
			if (at < 1 || (at + 1) === email.length)
				return false;
			// Make sure there aren't multiple periods together
			if (/(\.{2,})/.test(email))
				return false;
			// Break up the local and domain portions
			var local = email.substring(0, at);
			var domain = email.substring(at + 1);
			// Check lengths
			if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
				return false;
			// Make sure local and domain don't start with or end with a period
			if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
				return false;
			// Check for quoted-string addresses
			// Since almost anything is allowed in a quoted-string address,
			// we're just going to let them go through
			if (!/^"(.+)"$/.test(local)) {
				// It's a dot-string address...check for valid characters
				if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
					return false;
			}
			// Make sure domain contains only valid characters and at least one period
			if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
				return false;	
			return true;
		}
	};
	main.init();	
	if($("body").hasClass("home") || $("body").hasClass("about")){
  	    featureBuilder.init(featureBuilder.settings, featureBuilder.features);
	}
	if($("div.movie").length != 0){
	  $('a.video').click(function(e){
       $("div.movie").eq($(this).index('a.video')).modal({
					opacity:75, 
					overlayClose:true,
					persist:true, 
					closeHTML:'<a class="movie-close modalCloseImg simplemodal-close" title = "close" href="#"></a>'          
				})
				return false;
	  })
	}
})
