//speechbubble n0   0    1     2     3     4     5     6     7     8
var speechStart = [400, 900, 1500, 2600];
var scrollStreetAmount;
var adjustmentTop;
var speechBubblesDurationOriginal = 500;
var speechBubblesDurationCurrent;
var cityHeightOriginal = 4000;
var cityHeightCurrent;
var currentBubble = -1;
var isBubbleVisible = false;
var iScroller;
var iScrollCheck = false;
var iPhone = false;
var scrollStep;
var scrollCount;
var animationDuration = 500;
var timers = [];
var isBenVisible = false;
var benTopCurrent;
var hideBenBeginningTopCurrent;
var ben;
var benImg;
var city;

// Window dimensions updated on updateBrowserHeight
var windowHeight;
var windowWidth;
// End --------------------------------------------


var speechBubbles = [
    {start: speechStart[0], text: "Hi, welcome to my Web Site, I'm Simone Mimun"},
    {start: speechStart[1], text: "I'm actually the Project Director of the Hitframe"},
    {start: speechStart[2], text: "I'm specialized in: Web Sites Creation, iPhone WebApp, SEO and Internet Positioning, SEM, Motion Graphic, Flash Development, Graphic and Web Design,   Advertising"},
    {start: speechStart[3], text: "Contact me and follow me for further information"},
   
];

// Horizontal animations varialbes
var horizAnimOriginal = {
    thief : {start: 1100, duration: 900, side: 'left' , hiding:500},
    train : {start: 4300, duration: 1400, side: 'right' , hiding:3000}
};

var horizAnimCurrent = {
    thief : {},
    train : {}
};

var stolen;
var thiefLegsSpeedOriginal = 15; //Number of pixels horizontally for each image (higher value = slower legs speed)
var thiefLegsSpeedCurrent;
// End ---------------------------


// Ben legs speed var
var benLegsSpeedOriginal= 80; //Number of pixels verically for each image (higher value = slower legs speed)
var benLegsSpeedCurrent; 




if(document.querySelectorAll && (navigator.platform == "iPad" || navigator.platform.substring(0, 6) == "iPhone" || navigator.platform == "iPod")) {
	
	//miniFrameWorkMethods for iPhone and iPad

	function x$(query) {
		return document.querySelectorAll(query);
	}
	
    function addClassMobile(name, el){
		  if(el && el.className.search(name) == -1) {
			    el.className += el.className ? ' ' + name : name;
		  }
        return true;
    }
	
	function removeClassMobile(name, el){
		if(el && el.className.search(name) != -1) {
			    el.className = el.className.replace(name, ' ');
		}
        return true;
    }	
	
	
	//hide and show
	
	function webkitHide(el) {
		 el.style.display = "none";		 	
	}
	
	function slideShow(el){
		 el.style.display = "inline-block";		
    }
	
	function slideHide(el){		
		 el.style.display = "none";			 
    }	
	
	// functions to 1. create array for things to be launched on DOMready
	//              2. loop through array on DOMready and remove listener
	//              3. add listener for DOMready
	
	var readyFunc = [];
	
	function DOMReady () {
		for(var i=0, l=readyFunc.length; i<l; i++) {
			readyFunc[i]();
		}
	
		readyFunc = null;
		document.removeEventListener('DOMContentLoaded', DOMReady, false);
	}

	function ready (fn) {
		if (readyFunc.length == 0) {
			document.addEventListener('DOMContentLoaded', DOMReady, false);
		}
	
		readyFunc.push(fn);
	}
	
	//document.ready for iPhone and iPad
	
	ready(function() {
		iScrollCheck = true;		  
		updateBrowserHeight();
		
		if (navigator.platform == "iPad") {
			loadIscroll();
        } else {
			iPhone = true;
			loadIscroll();

            window.onload = function() {
                setTimeout(function() {
                    window.scrollTo(0, 1);

                }, 0);
            }
        }


        // Scroll to the bottom if ancor subscribed is detected on the URL
        var urlSplitted = String(document.location).split('#');
        if (urlSplitted[1] && urlSplitted[1] == 'subscribed') {
			var form = document.getElementById('sign_up_form');
            //iScroller.scrollTo(0, -cityHeightCurrent - adjustmentTop - document.getElementById('sign_up_form').offsetTop, '0');
			iScroller.scrollTo(0, -cityHeightCurrent - adjustmentTop - form.offsetTop - form.offsetHeight , '0');
        }
        // End

		document.getElementById("toTheTop").onclick = function() {
				removeClassMobile("visible", benImg);
				iScroller.scrollTo(0, 0, '200ms');
		}
		
		document.getElementById("toTheContact").onclick = function() {
				removeClassMobile("visible", benImg);
				iScroller.scrollTo(0, 0, '200ms');
		}

		setTimersForStartAnimation();

		addEmailField();

		/* code for fine-tuning the speech-bubbles ------------------------------------------------------------------------------------------------------------------*/
//		for (var i in speechBubbles) {
//			var top = speechBubbles[i].start + benTopCurrent + ben.offsetHeight;
//			var theString = '<div style="border: 2px solid #ff00ff; width: 10%; background-color: #f0f; color: #222; position: absolute; z-index: 1000; top: ' + top + 'px; height: ' + (speechBubblesDurationCurrent - ben.offsetHeight) + 'px; ">' + speechBubbles[i].text + '</div>';
//			x$("#ground")[0].innerHTML += theString;
//		}
		/* end code for speech-bubble tuning ------------------------------------------------------------------------------------------------------------------*/
	});

} else {

	$(document).ready(function() {

        updateBrowserHeight();
		$(window).scroll(function(){
			scrollEventHandler($(window).scrollTop());
		});
		$(window).resize(function() {
			updateBrowserHeight();
		});
		addEmailField();

		setTimersForStartAnimation();

		$("#toTheTop").click(function() {
			var scrollToStart = $("#city").position().top - 100;
			$("html, body").animate( { scrollTop: scrollToStart }, 500 );
			return false;
		});
		
			$("#toTheContact").click(function() {
			var scrollToStart = $("#contact").position().top + 400;
			$("html, body").animate( { scrollTop: scrollToStart }, 500 );
			return false;
		});
		
		// Twitter Share button
		
        $('#form_description').append("<div><iframe src='http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fbenthebodyguard.com%2F&amp;layout=box_count&amp;locale=en_US&amp;show_faces=false&amp;width=48&amp;action=like&amp;colorscheme=dark&amp;height=65' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:55px; margin-left: 20px; margin-top: 2px; height:65px;' allowTransparency='true'></iframe></div><div><a href='http://twitter.com/share' class='twitter-share-button' data-text='Taking a walk with @benthebodyguard (@ The Mean Streets)' data-count='vertical'> Tweet </a><script type='text/javascript' src='http://platform.twitter.com/widgets.js'></script></div>");



		/* code for fine-tuning the speech-bubbles ------------------------------------------------------------------------------------------------------------------*/
/*		for (var i in speechBubbles) {
			var top = speechBubbles[i].start + benTopCurrent + $(ben).height();
			var theString = '<div style="border: 2px solid #ff00ff; width: 10%; background-color: #f0f; color: #222; position: absolute; z-index: 1000; top: ' + top + 'px; height: ' + (speechBubblesDurationCurrent - $(ben).height()) + 'px; ">' + speechBubbles[i].text + '</div>';
			$("body").append(theString);
		} */
		/* end code for speech-bubble tuning ------------------------------------------------------------------------------------------------------------------*/

	});

}

// setting the timer to move page in the beginning
// noAnimation variable is set in index.php if the user returns to confirm email

function setTimersForStartAnimation() {
	if(typeof noAnimation == "undefined") {
			timers[0] = setTimeout('showScrollSign()', 4000);
	}
}

// Called from the iPad DOMready function above
function loadIscroll() {
    iScroller = new iScroll('ground', {hScrollbar:false}, 'accessories', 'accessoriesFixed');
    document.addEventListener('touchmove', function(e) {
        e.preventDefault();
	});
}

// function to hide the address-bar. otherwise that one always appear when orientation changes on iPhone.
window.onorientationchange = function() {
	if(iPhone) {
		window.scrollTo(0, 1);
	}
	updateBrowserHeight();
}


/* functions for the animation at the beginning */

 function showScrollSign() {
	 var goal = speechBubbles[1].start-windowHeight/2;
	 if (!iScrollCheck && $(window).scrollTop() < scrollStreetAmount) {
			$("#hide-wrapper").prepend('<img id="scrollImage" src="images/scroll-sign.gif">');
			$("#scrollImage").animate({ bottom: "2%" }, 280);
			$("#scrollImage").click(function() { $("html, body").animate({ scrollTop: goal }, 500); });
		//removed with the same function that makes ben appear
	 } else if (iScrollCheck && iScroller.y > -scrollStreetAmount) {
         document.getElementById('scrollImage') && (document.getElementById('scrollImage').style.display = 'block');
//		 document.getElementById('scrollImage').onclick = function() { iScroller.scrollTo(0, -adjustmentTop, '400ms'); }
		 document.getElementById('scrollImage').onclick = function() { 
		 	goal += Math.pow(15, windowHeight/480);
		 	iScroller.scrollTo(0, -goal, '400ms'); 
			setTimeout('scrollEventHandler(' + goal + ')', 400);
			}
	 }
 }


 /* function to add Email field on start */

 function addEmailField() {

	var emailField = document.createElement('div');
	emailField.id="upperForm";

	if (!iScrollCheck) {
		emailField = $(emailField);
		$(".connect").append(emailField);
		emailField.hide();
		emailField.append("<form action='http://madmimi.com/signups/subscribe/19050' method='post'><input id='signup_email' class='text' name='signup[email]' type='email' placeholder='Your e-mail address' value='Your e-mail adress' required><input name='commit' class='button submit' type='submit' value='Sign Up!'></form>");
		//$("#email").click(function() {
//			emailField.toggle('fast');
			$("#email").toggle(
				function() { emailField.fadeIn(300); emailField.css("display", "block"); }, // last row added for iE 8 compatibility
				function() { emailField.fadeOut(300); }
			);
//		});

	} else if (!iPhone) {
		x$(".connect")[0].appendChild(emailField);

		emailField.innerHTML = "<form action='http://madmimi.com/signups/subscribe/19050' method='post'><input id='signup_email' name='signup[email]' class='text' type='email' placeholder='Your e-mail address' value='Your e-mail adress' required><input name='commit' class='button submit' type='submit' value='Sign Up!'></form>";

		webkitHide(emailField);
		document.getElementById('email').onclick = function() {
			if(emailField.style.display == "none") {
				slideShow(emailField);
			} else {
				slideHide(emailField);
			}
		}

	}
 }


// Add and remove speechBubble –––––––– Also controls the yakuza sign –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– //
// Yakuza sign is triggered when the right text comes in!! //

function addBubble(spokenText) {
	if(!iScrollCheck) {
	    $('#speechBubble').stop(true, true).slideDown('fast', function() {
            $('#speechBubble').html(spokenText);
        });
	} else {
        document.getElementById('speechBubble').innerHTML = spokenText;
        document.getElementById('speechBubble').style.opacity = 1;
		}
}

function removeBubble() {
	if(!iScrollCheck) {
        $('#speechBubble').fadeOut('fast', function() {
            $('#speechBubble').html('');
        });
		$("#ben").css("z-index", "20");
	} else {
        ben.style.zIndex = '20';
        document.getElementById('speechBubble').style.opacity = 0;
    }
}

//------------- function for extras to happen omong other speechBubbles ---------------------------- //

function startAnimations(number) {
	switch(number) {
        case 0:
            if (!iScrollCheck) {
                $("#ben").css("z-index", "5000");
            } else {
                ben.style.zIndex = '500';
            }
            break;
		case 6:
			if(!iScrollCheck) {
				$("#yakuza").addClass("animated");
				$("#ben").css("z-index", "50");
			} else {
                document.getElementById('yakuza').src = document.getElementById('yakuza').src.replace('still', 'anim');
                ben.style.zIndex = '500';
            }
		break;
	}
}


function scrollEventHandler(position) {


    //on touch devices, setPosition in iScroll is used to call this function
	//on other types, its called via $(window).scroll() in the $(document).ready() above.

    // Speech Bubbles -----------------------------------------------------------------------------------------------
    if (isBubbleVisible) {
        if (position > speechBubbles[currentBubble].start + speechBubblesDurationCurrent ) {
            isBubbleVisible = false;
            removeBubble();
        }
        else if (position < speechBubbles[currentBubble].start) {
            isBubbleVisible = false;
            removeBubble();
            currentBubble--;
        }
    } else {
        if (currentBubble + 1 < speechBubbles.length && position >= speechBubbles[currentBubble + 1].start && position < speechBubbles[currentBubble + 1].start + speechBubblesDurationCurrent) {
            isBubbleVisible = true;
            addBubble(speechBubbles[currentBubble + 1].text);
            currentBubble++;
			startAnimations(currentBubble); //start animations, for example yakuza sign
        } else if(currentBubble > -1 && position < speechBubbles[currentBubble].start + speechBubblesDurationCurrent && position > speechBubbles[currentBubble].start) {
            isBubbleVisible = true;
            addBubble(speechBubbles[currentBubble].text);
			startAnimations(currentBubble); //start animations, for example yakuza sign
        } else if(speechBubbles[currentBubble] && position < speechBubbles[currentBubble].start + speechBubblesDurationCurrent){
            currentBubble--;
        } else if(speechBubbles[currentBubble+1] && position > speechBubbles[currentBubble + 1].start){
            currentBubble++;
        }

    }
    // End -----------------------------------------------------------------------------------------------

//    console.log($(benImg).height());
	// Make ben appear when you scroll down and disappear when u scroll back up
	if(!iScrollCheck) {
        if (position < hideBenBeginningTopCurrent - benTopCurrent + 200/*tolerance*/) {
            isBenVisible && $(benImg).removeClass("visible") && (isBenVisible = false);
			
			//$('#speechBubble').css("opacity", 0);
            //$('#speechBubble').html('');
			
        } else {
            !isBenVisible && $(benImg).addClass("visible") && (isBenVisible = true);
			$("#scrollImage") && $("#scrollImage").animate({bottom: "-200px"}, 200, function() {
                $(this).remove()
            });
        }
	} else {
        if (position < hideBenBeginningTopCurrent - benTopCurrent + 200 * cityHeightCurrent/cityHeightOriginal ) { 
            isBenVisible && removeClassMobile("visible", benImg) && (isBenVisible = false);
        } else {
            !isBenVisible && addClassMobile("visible", benImg) && (isBenVisible = true);
            document.getElementById('scrollImage') && document.getElementById('container').removeChild(document.getElementById('scrollImage'));
        }
	}
	// End


    if (document.getElementById("thief")) { // checking if Thief is there = not iOS 3 version

        // Animations Horizontal -----------------------------------------------------------------------------------------------
        for (var id in horizAnimCurrent) {
            var element = horizAnimCurrent[id];

            if (position > element.start && position < element.start + element.duration) {
                var distance = (windowWidth + element.hiding) / element.duration * (position - element.start) - element.hiding  / 2 + 'px';
                element.el || (element.el = document.getElementById(id));
                element.el.style[element.side] = distance;
            }
        }
        // End -----------------------------------------------------------------------------------------------

        // Stealing Cell Phone + Thief legs movement -----------------------------------------------------------------------------------------------
        if (position > horizAnimCurrent.thief.start && position < horizAnimCurrent.thief.start + horizAnimCurrent.thief.duration) {
            stolen || (stolen = document.getElementById('stolen'));

            // Thief legs movement
              document.getElementById('thief').style.backgroundPosition = '-' + (Math.ceil(position / thiefLegsSpeedCurrent) - (Math.floor(Math.ceil(position / thiefLegsSpeedCurrent) / 4)) * 4) * 76 + 'px 0';

            // Guy gets stolen?
            if (!iScrollCheck) {
                if ($(horizAnimCurrent.thief.el).position().left > $(stolen).position().left) {
                    $(stolen).addClass('stolen');
                } else {
                    $(stolen).removeClass('stolen');
                }  
            } else {
                if (horizAnimCurrent.thief.el.offsetLeft > stolen.offsetLeft) {
                    addClassMobile('stolen', stolen);
                } else {
                    removeClassMobile('stolen', stolen);
                }

            }
        }
        // End -----------------------------------------------------------------------------------------------
    }

// Ben legs movement animation
    document.getElementById('ben-img').style.backgroundPosition = '-' + (Math.ceil(position / benLegsSpeedCurrent) - (Math.floor(Math.ceil(position / benLegsSpeedCurrent) / 4)) * 4) * 40 + 'px 0';

}

function updatePositions() {
    for (var i in speechStart) {
        speechBubbles[i].start = speechStart[i] * cityHeightCurrent / cityHeightOriginal + adjustmentTop;
    }

    speechBubblesDurationCurrent = cityHeightCurrent / cityHeightOriginal * speechBubblesDurationOriginal;

    for (var i in horizAnimOriginal) {
        horizAnimCurrent[i].start = horizAnimOriginal[i].start * cityHeightCurrent / cityHeightOriginal + adjustmentTop;
        horizAnimCurrent[i].duration = horizAnimOriginal[i].duration * cityHeightCurrent / cityHeightOriginal;
        horizAnimCurrent[i].hiding = horizAnimOriginal[i].hiding * cityHeightCurrent / cityHeightOriginal;
        horizAnimCurrent[i].side = horizAnimOriginal[i].side;
    }
}

function updateBrowserHeight() {

    city = document.getElementById('city');
    ben = document.getElementById('ben');
    benImg = document.getElementById('ben-img');

    if(!iScrollCheck) {
		scrollStreetAmount = $(city).position().top - ($(window).height() * 0.8); //0.8 is the number that decides how much of the street is gonna be shown.
        cityHeightCurrent = $(city).height();
        windowHeight = $(window).height();
        windowWidth = $(window).width();
        benTopCurrent = $('#ben').offset().top - $(window).scrollTop() + $('#ben').height();
        hideBenBeginningTopCurrent = $('#hideBenInBeginning').offset().top;
        adjustmentTop = $(city).position().top - benTopCurrent;
    } else {
		scrollStreetAmount = city.offsetTop - (window.innerHeight * 0.8);

        if (iPhone) {
            scrollStreetAmount = x$("#city")[0].offsetTop - (window.innerHeight);
        }
		cityHeightCurrent = x$("#city")[0].offsetHeight;

        windowHeight = window.innerHeight;
        windowWidth = window.innerWidth;
        benTopCurrent = document.getElementById('ben').offsetTop + document.getElementById('ben').offsetHeight;
        hideBenBeginningTopCurrent = document.getElementById('hideBenInBeginning').offsetTop;
        adjustmentTop = city.offsetTop - benTopCurrent;
    }


    benLegsSpeedCurrent = benLegsSpeedOriginal * cityHeightCurrent / cityHeightOriginal;
    thiefLegsSpeedCurrent = thiefLegsSpeedOriginal * cityHeightCurrent / cityHeightOriginal;


    updatePositions();
}





