var flashvars1 = {};
    var flashvars2 = {};
    var params1 = {
        menu: false,
        loop: true
    };
    var params2 = {
        menu: false,
        loop: true
    };            
    var attributes1 = {};
    var attributes2 = {};
    
    swfobject.embedSWF("video/dana.swf", "danaflash", "460", "186", "9.0.0", "expressInstall.swf", flashvars1, params1, attributes1);
    swfobject.embedSWF("video/carrie.swf", "carrieflash", "460", "186", "9.0.0" , "expressInstall.swf",  flashvars2, params2, attributes2);
    
    var isClicked = false;
    var current_index = 0;
    var isInfoOn = false;
    
    var stack = { //allows delayed iteration with jQuery.each() - see stack.actions.push(function(){ }) below.
	    delay: 200,
	    actions:[],
	    run: function() {
	        if (stack.actions.length) {
	            stack.actions.shift()();
	            setTimeout(stack.run, stack.delay);
	        }
	    }
	};
	
	var init = false;
	var isText = true;
	var carousel_init = true;
	
	var timer;
	
	var expire_date = new Date();
    expire_date.setTime(expire_date.getTime() + (5 * 1000));
    
    var isAccordionInit = false;
    var isTop = true;
    var isDropDown = false;


    var currentLatitude;
    var currentLongitude;
    
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();
	var map;
	
	var isiPhone = false;
	
	scrollUp = false;
	scrollDown = false;



    function handle_geolocation_query(position){ 
        currentLatitude = parseFloat(position.coords.latitude);
        currentLongitude = parseFloat(position.coords.longitude);
        /* alert(currentLatitude + " " + currentLongitude); */
        var office = new google.maps.LatLng(40.704587, -73.987083);
		var clientLocation = new google.maps.LatLng(currentLatitude, currentLongitude);
	    var request = {
	        origin:clientLocation, 
	        destination:office,
	        travelMode: google.maps.DirectionsTravelMode.WALKING
	    };
	    directionsService.route(request, function(response, status) {
	      if (status == google.maps.DirectionsStatus.OK) {
	        directionsDisplay.setDirections(response);
	      }
	    });
	    
	    var marker = new google.maps.Marker({
		    position: clientLocation,
		    map: map,
		    icon: "/images/you.png",
		    title:"F train"
		});

          
    }
    
    function handle_errors(error)  
    {  
        switch(error.code)  
        {  
            case error.PERMISSION_DENIED: alert("user did not share geolocation data");  
            break;  

            case error.POSITION_UNAVAILABLE: alert("could not detect current position");  
            break;  

            case error.TIMEOUT: alert("retrieving position timed out");  
            break;  

            default: alert("unknown error");  
            break;  
        }  
    }  
    
    function getDirections(){
        navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
    }  
    
    
    
    
    $(document).ready(function(){
		var deviceAgent = navigator.userAgent.toLowerCase();
		var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
		if (agentID) {
		    isiPhone = true;
		}
		
        $("#btnInit").click(function(){getDirections();});
        
        $(".init p").delay(2000).css("visibility","visible");
        /* Cufon */	
    
        $("#map_canvas").css("visibility","hidden");
        
        
        var sections = $(".nav a span");
		sections.hide();
	
		sections.each(function(){
	        var el = this;
	        stack.actions.push(function(){
				jQuery(el).fadeIn('slow');
	        });
		});

        /* popup for external website */
        $("a[rel^='prettyPhoto[iframes]']").prettyPhoto();
        /* end */
        
        /* initial fadeIn */
        $("#wrapper").delay(1000).fadeIn(1000, function(){
            if($(".contact_page").length != 0){
                loadMaps();
            }			
            stack.run();
                
        });
        /* end */
        
        if(isiPhone == false){
	        /* homepage carousel */
	        var carousel_size = $(".slide").size() - 1 ;
	        
	        $('#homepage-carousel').cycle({ 
			    fx: 'scrollHorzFade',
			    timeout: 8000,
			    delay: 4000,
			    prev: "#prev",
			    next: "#next",
			    speed: 1000,
			    sync: 1,
			    startingSlide: 1,
			    prevNextClick: afterClick,
			    before: onBefore,
			    pager: '#nav'
		    });
		    
		    /* $(".init").hide(); */
		    
		    $('.project_carousel').cycle({ 
		        fx: 'scrollHorzFade',
		        timeout: 8000,
		        delay: 4000,
		        prev: "#prev",
		        next: "#next",
		        speed: 1000,
		        sync: 1,
		        startingSlide: 0,
		        prevNextClick: afterClick,
		        before: onBefore,
		        pager: '#nav'
		    });
	    }else{
	    	$(".black-image").remove();
	    	$("#main .next").remove();
	    	window.homepageSwipe = new Swipe(
	    	  document.getElementById('homepage-carousel-wrapper'), {startSlide: 1}
	    	);
	    	
	    	window.projectSwipe = new Swipe(
	    	  document.getElementById('project_carousel_wrapper')
	    	);
	    }
	    
	    
	    $('#homepage-carousel').cycle("pause");
	    
	    $(".init").delay(3000).fadeOut(600, function(){
	    	if(isiPhone){
	    		$("#main .prev").css("opacity", 1);
	    		$("#main .prev").animate({left: 30}, 1000, function() { $(this).fadeOut(200);});
	    	}
            $('#homepage-carousel').cycle("resume");
//            $("#homepage-carousel-wrapper").hover(
//                function(){
//                    if(isText){$(this).css("cursor","default");}else{$(this).css("cursor","pointer");}
//                    if(isClicked){
//                    }else if($(".on").attr("name")=="textpage"){
//                    
//                    }else{
//                        $("#info_button").fadeIn();  
//                    }
//                    /* $('#homepage-carousel').cycle("pause"); */                    
//                },
//                function(){
//                    if(isClicked){}else{
//                        $("#info_button").fadeOut();
//                        /* $('#homepage-carousel').cycle("resume"); */
//                    }
//                }
//            );            
        });
           
        /* end */
        			    



	    $("#info_button").click(
            function(event){
                event.preventDefault();                    
            }
        );

        
//        $("#homepage-carousel-wrapper").click(
//            function(event){
//            event.preventDefault();
//            if(isText){
//            }else{
//                if(isClicked == false){
//                    $("#info_button").fadeOut();
//                    $(".project-info").show();
//                    $(".project-info").stop(true, true);
//                    $(".project-info").animate({left: 440}, 500);
//                    $('#homepage-carousel').cycle("pause");
//                    $(".black-image").stop(true, true).fadeOut();
//                    isClicked = true;
//                    clearTimeout(timer);
//                }else{
//                    $(".project-info").stop(true, true);
//                    $(".project-info").animate({left: 960}, 500, function(){$(".project-info").hide();});
//	                $('#homepage-carousel').cycle("pause");
//	                $(".black-image").stop(true, true).fadeIn();
//	                isClicked = false;
//	                timer = setTimeout(nextCarousel, 2500);
//                }
//            }	                    
//        });
//
//		$("#homepage-carousel-wrapper").click(function(){
//			var href = $(this).find(".on").attr("url");
//			window.location = href;
//		});
		
//		Assign handlers to the simple direction handlers.
//		var swipeOptions={
//			threshold:0,
//			allowPageScroll:"vertical",
//			swipeLeft:swipe1, 
//			swipeRight:swipe1
//		}
//					
//		Enable swiping...
//		$("#homepage-carousel").swipe( swipeOptions );
//		$(".project_carousel").swipe( swipeOptions );
        
        $("#subject").bind("click",function(event){
            event.preventDefault();
            if(isDropDown){
                $("#select-options ul").hide();
                isDropDown = false;
                $("#select_icon").text("+");
            }else{
                $("#select-options ul").show();
                isDropDown = true;
                $("#select_icon").text("-");
            }
        });
        
        $("#select_icon").bind("click",function(event){
            event.preventDefault();
            if(isDropDown){
                $("#select-options ul").hide();
                isDropDown = false;
                $(this).text("+");
            }else{
                $("#select-options ul").show();
                isDropDown = true;
                $(this).text("-");
            }
        });

        
        $("#select-options ul li").click(function(event){
            event.preventDefault();
            var subject_value = $(this).text();
            $("#subject").attr("value",subject_value);
            $("#select-options ul").hide();
            isDropDown = false;
        });
        
	    
        
/*
        $(".info").click(function(event){
                if($(this).html() != "close"){
                event.preventDefault();
                $('#homepage-carousel').cycle("pause");
                $(".project-info").fadeIn();
                if($(".on").attr("name") != "textpage"){
                    $(".carousel-control").fadeOut();
                    isInfoOn = true;
                    isClicked = true;
                }
            }else{
                event.preventDefault();
                $('#homepage-carousel').cycle("pause");
                $(".project-info").fadeOut();
            }
            
        });

        

        $(".close-info").click(function(event){
            event.preventDefault();
            $(".project-info").fadeOut();
            $('#homepage-carousel').cycle("pause");
            $(".black-image").stop(true, true).fadeIn();
            isClicked = false;
        });
*/	
        
        jQuery('.homepage .recently-list').accordion({
			collapsible: true,
			active: false,
			change: function(event,ui){
			    disableCarousel();
			    if($('h4[aria-expanded="true"]').length != 0){
			       isAccordionInit = true; 
			    }
			    if(isiPhone==false){
				    if($('h4[aria-expanded="true"]').length != 0){
				        $.scrollTo($('h4[aria-expanded="true"]'), 500, {offset: {top: -50}});
				        $('h4[aria-expanded="true"] .plus').html("&#8212;");
				        $('h4[aria-expanded="false"] .plus').html("+");
				    }
				    $("h4[aria-expanded='true']").each(function(){
				    	if($(this).next("div").css("display") == "none"){
				    		$(this).find(".plus").html("+");
				    	}
				    });
			    }
			}
		});
		
/*
		$("#mask").hover(
		    function(){
		        enableCarousel();
		    },
		    function(){
		    
		    }
		);
*/
		var tempScrollTop, currentScrollTop = 0; 
		
		$(document).scroll(function(){
		    currentScrollTop = $(this).scrollTop();
		    
		    if(tempScrollTop > currentScrollTop && $(this).scrollTop() < 300 && scrollUp==false){
		        if(isClicked){}else{
		            enableCarousel();
		            if(isAccordionInit){
		                if($('h4[aria-expanded="true"]').length != 0){
			                isAccordionInit = false;
		                }
		            }else{
		                
		            }

		 	    }
		    }else if($(this).scrollTop() > 480 && tempScrollTop < currentScrollTop && scrollDown==false ){
		        disableCarousel();
		        if(isAccordionInit){}else{
		            if($('h4[aria-expanded="true"]').length == 0){
//		                jQuery('.recently-list').accordion("activate", 0);
		                isAccordionInit = true;
		            }   
		        }
		    }
		    tempScrollTop = currentScrollTop; 
		});
		
		var options = {
		    success: showResponse
		}
		
		$("#contact_form").submit(function(){
		    $(this).ajaxSubmit(options);
		    return false;
		});
		
        if($(".ua-ie").length != 0){
	        $(".project_carousel").hover(function(){
	        	$("#main .prev, #main .next").show();
	        }, function(){
	        	$("#main .prev, #main .next").hide();
	        });
	        
	        $(".projects_page #main .prev, .projects_page #main .next").hover(function(){
	        	$("#main .prev, #main .next").show();
	        }, function(){
	        	$("#main .prev, #main .next").show();
	        });
	        
	       $("#homepage-carousel-wrapper").hover(function(){
	       	$("#main .prev, #main .next").show();
	       }, function(){
	       	$("#homepage-carousel-wrapper .prev, #homepage-carousel-wrapper .next").hide();
	       });
	       
	       $(".homepage #main .prev, .homepage #main .next").hover(function(){
	       	$("#main .prev, #main .next").show();
	       },function(){$("#main .prev, #main .next").show();}); 
        
        }
        
        $(".projects_page #main .prev").click(function(event){
        	event.preventDefault();
        	$(".black-image").remove();
        	$('.project_carousel').cycle('pause');
        	$('.project_carousel').cycle('prev');
        });

		$(".projects_page #main .next").click(function(event){
			event.preventDefault();
			$(".black-image").remove();
			$('.project_carousel').cycle('pause');
			$('.project_carousel').cycle('next');
		});
        
        $(".homepage #main .prev").click(function(event){
        	event.preventDefault();
        	event.stopPropagation();
        	$(".black-image").remove();
        	$('#homepage-carousel').cycle('pause');
        	$('#homepage-carousel').cycle('prev');
        });

		$(".homepage #main  .next").click(function(event){
			event.preventDefault();
			event.stopPropagation();
			$(".black-image").remove();
			$('#homepage-carousel').cycle('pause');
			$('#homepage-carousel').cycle('next');
		});
		
		$("#nav a").click(function(){
			$(".black-image").remove();
			$('.project_carousel').cycle('pause');
		});
		
		$("#latest_tweet").tweet({
		  count: 1,
		  username: "ownentity",
		  loading_text: "searching twitter..."
		});
		        
/*
        
        $("#prev_project").click(function(event){
            event.preventDefault();
            var total = $("#homepage-carousel div.slide").length/4;
            var prev_project_index = parseInt((current_index) / 4) - 1;
            if(prev_project_index < 0){
                $('#homepage-carousel').cycle((total-1)*4);
                current_index = (total-1)*4;
            }else{
                $('#homepage-carousel').cycle( prev_project_index*4 );
                current_index = prev_project_index*4;
            }
        });
        
        $("#next_project").click(function(event){
            event.preventDefault();
            var total = $("#homepage-carousel div.slide").length/4;
            var next_project_index = parseInt((current_index) / 4) + 1;
            if(next_project_index > total-1){
                $('#homepage-carousel').cycle(0);
                current_index = 0
            }else{
                $('#homepage-carousel').cycle( next_project_index*4 );
                current_index = next_project_index*4;
            }
        });

*/  
    });
    
    (function( win ){
    	if($("ua-mobile-iphone").length != 0 ){
	    	var doc = win.document;
	    
		    // If there's a hash, or addEventListener is undefined, stop here
		    if( !location.hash && win.addEventListener ){
		    
			    //scroll to 1
			    window.scrollTo( 0, 1 );
			    var scrollTop = 1,
			    getScrollTop = function(){
			    return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
		    },
		    
		    //reset to 0 on bodyready, if needed
		    bodycheck = setInterval(function(){
			    if( doc.body ){
			    	clearInterval( bodycheck );
			    	scrollTop = getScrollTop();
			    	win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
			    }
		    }, 15 );
		    
		    win.addEventListener( "load", function(){
		    	setTimeout(function(){
			    //at load, if user hasn't scrolled more than 20 or so...
			    if( getScrollTop() < 20 ){
			    //reset to hide addr bar at onload
		    		win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
		    			}
		    		}, 0);
		    	} );
		    }
	    }
    })( this );
       
    function showResponse(){
        $.scrollTo("#wrapper", 500);
        $("#email_response").delay(600).slideDown();
        $("#email_response").delay(3000).slideUp();
        
    }
    
    function nextCarousel(){
        $("#homepage-carousel").cycle('next');
        $("#homepage-carousel").cycle('resume');
    }
    
    function disableCarousel(){
        $("#homepage-carousel").cycle("pause");
        $("#mask").stop(true, true);
	    $(".black-image").remove();
	    $("#mask").fadeIn(1500);
	    isClicked = false;
    }
    
    function enableCarousel(){
        $("#mask").stop(true, true);
        $("#mask").fadeOut(1500);
//        $("#homepage-carousel-wrapper").hover(
//            function(){
//                if(isClicked){
//                }else if($(".on").attr("name")=="textpage"){
//                
//                }else{
//                    $("#info_button").fadeIn();  
//                }
//                /* $('#homepage-carousel').cycle("pause"); */                    
//            },
//            function(){
//                if(isClicked){}else{
//                    $("#info_button").fadeOut();
//                    /* $('#homepage-carousel').cycle("resume"); */
//                }
//            }
//        );   
//        if(isClicked){
//        }else{         
//            $("#homepage-carousel").cycle("resume");
//        }
    }
    
    function afterClick(){
        $('#homepage-carousel').cycle("pause");
        $(this).html("info");
        isClicked = true;
    }
    
    function onBefore(curr, next, opts){
        $(".slide").removeClass("on");
        $(next).addClass("on");
        var name = $(next).attr("name");
        current_index = opts.currSlide;
/*
        var index = opts.nextSlide;
        index = index%4;
*/
        
        if(carousel_init){
            $(next).find(".black-image").delay(6000).fadeOut(1000).delay(3000).fadeIn(1000);
            carousel_init = false;
        }else{
            $(next).find(".black-image").delay(2500).fadeOut(1000).delay(3000).fadeIn(1000);
        }
        
        if(name == ""){
            opts.sync = 1;
            opts.speed = 1000;
            opts.timeout = 8000;
            opts.fx = "scrollHorzFade";
            /* $(".image-header").fadeIn(); */
            isText = false;
        }else if(name == "init"){
            opts.sync = 1;
            opts.speed = 1000;
            opts.timeout = 8000;
            opts.fx = "scrollHorzFade";
            isText = false;
        }else if(name == "textpage"){
            opts.sync = 1;
            opts.speed = 1000;
            opts.timeout = 8000;
            opts.fx = "scrollHorzFade";
            isText = true;
            $("#info_button").fadeOut();
        }else if(name == "last"){
            opts.sync = 1;
            opts.speed = 1000;
            opts.timeout = 8000;
            opts.fx = "scrollHorzFade";
            isText = false;
        }
        isClicked = false;                
        $(".project-info").css("left","960px");
        $(".project-info").hide();

    }
    
    //Swipe handlers.
    //The only arg passed is the original touch event object			
    function swipe1(event, direction){
    	if(direction == "left"){    		
			$(this).find(".black-image").remove();
			$(this).cycle("next");
			$(this).cycle("pause");
		}else if (direction == "right") {
			$(this).find(".black-image").remove();
			$(this).cycle("prev");
			$(this).cycle("pause");
		}
    }
    
    function loadMaps(){
        directionsDisplay = new google.maps.DirectionsRenderer();
		var brooklyn = new google.maps.LatLng(40.7035, -73.987083);
		var office = new google.maps.LatLng(40.704587, -73.987083);
		var F_train = new google.maps.LatLng(40.701364,-73.986654);
		var clientLocation = new google.maps.LatLng(currentLatitude, currentLongitude);
		
		var stylez = [
		    {
		      featureType: "all",
		      elementType: "all",
		      stylers: [
		        { saturation: -100 } // <-- THIS
		      ]
		    }
		];
		
		var colorz = [
		    {
		      featureType: "all",
		      elementType: "all",
		    }
		];
		
		var mapOptions = {
		    zoom: 16,
		    center: brooklyn,
		    streetViewControl: false,
		    navigationControlOptions: {
                style: google.maps.NavigationControlStyle.SMALL                        
            },
		    mapTypeControlOptions: {
		         mapTypeIds: [ 'colorz', 'tehgrayz']
		    }
		};

		map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
		
		var colorMapType = new google.maps.StyledMapType(colorz, { name:"Color" });    
		map.mapTypes.set('colorz', colorMapType);
		
		var mapType = new google.maps.StyledMapType(stylez, { name:"Grayscale" });    
		map.mapTypes.set('tehgrayz', mapType);
		map.setMapTypeId('tehgrayz');
		
		var marker;
		
		var marker = new google.maps.Marker({
		    position: office,
		    map: map,
		    title:"Ownentity",
		    icon: "/images/oelogomap.png"
		});
		
		marker = new google.maps.Marker({
		    position: F_train,
		    map: map,
		    icon: "/images/F_train_gray.png",
		    title:"F train"
		});
		
/*
		marker = new google.maps.Marker({
		    position: clientLocation,
		    map: map,
		    title:"Your Location"
		    
		});
*/
		
		google.maps.event.addListener(map, 'tilesloaded', function() {
		    if(init == false){
		        $("#map_canvas").hide();
		        $("#map_canvas").css("visibility","visible");
		        $("#map_canvas").fadeIn(1500);
		        $("#btnInit").fadeIn(1500);
		        init = true;
		    } 
		});
		
		directionsDisplay.setMap(map);
		directionsDisplay.setOptions( { suppressMarkers: true, polylineOptions: { strokeOpacity: 0.0} } );
		
    }
        
    


