// fade characters in/out
function fadeCharacter(character,delay,fade_speed,direction){
	setTimeout(function(){
		if(direction == 'in') $('#'+character).fadeIn(fade_speed);
		else $('#'+character).fadeOut(fade_speed);
	},delay);
}

// reset characters
function resetCharacters(characters,lefts,bottoms,fade_start,fade_delay,fade_speed,direction,delay){
	
	var new_html;
	
	setTimeout(function(){
		// hide all characters
		$('.character').hide();
		$('#batman').hide();
		// show small dialogue boxes
		$('.dialogue_text').show();
		$('.dialogue_arrow').show();
		// hiding extended dialogue box
		$('.extended').hide();
	    
		// slide in all characters in a sequence
		for (i=0; i<characters.length; i++) {
			// resetting top css
			$('#'+characters[i]).css('left',lefts[i]);
			// resetting bottom css
			//$('#'+characters[i]).css('bottom',bottoms[i]);
			// fading/sliding characters in
			if(characters[i]=="batman"){
				moveBatman('#'+characters[i],0,500);
				$('#batman').show();
			}
			else {
				// making characters visible
				$('#'+characters[i]).show();
				// replacing KeyPublisher strong tags with span
				new_html = $('#'+characters[i]+' .dialogue_text').html();
				new_html = new_html.replace('<strong>','<span>');
				new_html = new_html.replace('</strong>','</span>');
				$('#'+characters[i]+' .dialogue_text.intro').html(new_html)
				// moving character in
				moveCharacter('#'+characters[i],fade_start+(fade_delay*i),fade_speed,bottoms[i],'easeOutExpo');
			}
		}
	},delay);

	// removing yellow marker
	$('.yellow-marker').animate({ width: '0px' },{ duration: 200, easing: 'easeOutExpo' });

}

// write text to dialogue
function appendText(destination,text,splitter,delay,type){

	setTimeout(function(){
		if(type=="p") $(destination+" p:last").append(text+splitter);
		else destination.append(text+splitter);
	},delay);

}

// mouths
function moveMouth(mouth,delay){

	setTimeout(function(){
		mouth.toggle();
	},delay);

}

// close mouth after section if open
function closeMouth(mouth,delay){

	setTimeout(function(){
		if(mouth.is(":visible")) mouth.toggle();
	},delay);

}

// mouth talk
function mouthTalk(character,total_time,mouth_delay,delay_base){

	// amount of times to open/close mouth
	mouth_count = Math.round(total_time/mouth_delay,0);
	// adding one open/close if only one (short sentence)
	if(mouth_count == 1) mouth_count = 2;
	
	// opening/closing mouth
	for(i=0; i<=mouth_count; i++){
		// hide/show mouth to open/close
		moveMouth($('#'+character+' .mouth'),delay_base+(i*mouth_delay));
		// hiding mouth to close it at the last word
		if(i==mouth_count) closeMouth($('#'+character+' .mouth'),delay_base+(i*mouth_delay)+mouth_delay);
	}
	
}

// check for odd or even number to make sure mouth is closed
function isEven(value) {

	if (value%2 == 0)
		return true;
	else
		return false;
		
}

// show extended dialogue
function extendDialogue(character,delay,explorer){
    
	// delay between words
	var word_delay = 30;
	var delay_base;
	
	// delay between sections (h2, h3, div)
	var first_section = 150;
	var section_delay = 500;
	
	// text holders
	var div_title = $('#'+character+' .extended .dialogue_text h2');
	var div_intro = $('#'+character+' .extended .dialogue_text h3');
	var div_text = $('#'+character+' .extended .dialogue_text div.dialogue_content');
	var div_text_id = '#'+character+' .extended .dialogue_text div.dialogue_content';
	
	// getting text content from title/intro/text
	var org_title = div_title.html();
	var org_intro = div_intro.html();
	var org_text = div_text.html();
	
	// mouth movement when text is appearing
	var total_time;
	var mouth_count;
	var mouth_delay = 70;
	
	// hiding small dialogue box
	$('.dialogue_text').hide();
	$('.dialogue_arrow').hide();
	
	setTimeout(function(){
		
		// revealing content divs
		$('#'+character+' .extended .dialogue_text').show();
		$('#'+character+' .extended .dialogue_arrow').show();
		if(!explorer) {
			$('#'+character+' .extended').show();
			$('#'+character+' .extended').animate({ opacity: 1 }, 200);
		}
		else $('#'+character+' .extended').show();
		
		// removing original content
		div_title.html('');
		div_intro.html('');
		//if(explorer) div_text.html('');
		//else div_text.html('<p></p>');
		div_text.html('<p></p>');
		
		// holding off <a href... to be able to write out a link
		var link = 0;
		var link_html = '';

		// title - writing out content word by word
		var titleSplit = org_title.split(' ');
		delay_base = first_section;
		for(i=0; i<titleSplit.length; i++) {
			appendText(div_title,titleSplit[i],' ',delay_base+(i*word_delay),'');
		}
		// mouth moving
		total_time = titleSplit.length*word_delay;
		mouthTalk(character,total_time,mouth_delay,delay_base);
		
		// intro - writing out content word by word
		var introSplit = org_intro.split(' ');
		delay_base = first_section+(section_delay*1)+(titleSplit.length*word_delay);
		for(i=0; i<introSplit.length; i++) {
			appendText(div_intro,introSplit[i],' ',delay_base+(i*word_delay),'');
		}
		// mouth moving
		total_time = (titleSplit.length+introSplit.length)*word_delay;
		mouthTalk(character,total_time,mouth_delay,delay_base);
		
		// text - preparing content
			// removing first and last <p> </p>
			// if(org_text.substring(0,3) == '<p>') org_text = org_text.substring(3,org_text.length-4);
			// replacing paragraphs with line breaks
			// org_text = org_text.replace('<p>','');
			// org_text = org_text.replace('</p>','<br><br>');
			// remove html comments and clean code
			org_text = org_text.replace(/<!--[\s\S]*?-->/g, ""); // removing <!-- comments -->
			org_text = $.htmlClean(org_text); // jQuery clean html plugin removes classes and more
			// replacing strong with span
			org_text = org_text.replace('strong>','span>');
			org_text = org_text.replace('/strong','/span');
			// ie: changing all tags to lowercase from <BR> to <br> etc
			org_text = org_text.replace(/<\/?[A-Z]+.*?>/g, function (m) { return m.toLowerCase(); });
		
		// text - writing out content word by word
		var textSplit = org_text.split(' ');
		delay_base = first_section+(section_delay*2)+(introSplit.length*word_delay)+(titleSplit.length*word_delay);
		for(i=0; i<textSplit.length; i++) {
			if(textSplit[i] == '<a') link = 1;
			if(link == 1) link_html += textSplit[i]+' ';
			if(textSplit[i].match(/(<\/a>)/)){
				appendText(div_text_id,link_html,' ',delay_base+(i*word_delay),'p');
				link = 0;
				link_html = '';
			}
			else if(i==0 && explorer) appendText(div_text,textSplit[i]+' ','',delay_base+(i*word_delay),''); // Internet Explorer inserts a <p></p> around the first word
			else if(link == 0) appendText(div_text_id,textSplit[i],' ',delay_base+(i*word_delay),'p');
		}
		
		// mouth moving
		total_time = ((titleSplit.length+introSplit.length+textSplit.length)*word_delay)-section_delay;
		mouthTalk(character,total_time,mouth_delay,delay_base);
		
	},delay);
}

// move characters down/out
function moveCharacter(character,delay,move_speed,position,ease){
	setTimeout(function(){
        if(character=="#batman") moveBatman(character,-150,0);
		else $(character).animate({ bottom: position },{ duration: move_speed, easing: ease });
	},delay);
}

// move selected character in
function mainCharacter(character,delay,explorer){
	setTimeout(function(){
		// hiding all other characters in case of hovering while animating out
		$('.character').hide();
		$('#'+character).show();
        // animating in
		$('#'+character).animate({ left: 0 },{ duration: 0 });
		$('#'+character).animate({ bottom: 0 },{ duration: 500, easing: 'easeOutExpo' });
		// allow mouths to animate (make visible after potential hiding when closing an earlier dialogue)
		$('.mouth').css('visibility','');
		// opening extended dialogue
		extendDialogue(character,200,explorer);
		// drawing in yellow marker on main menu
		$('#ym-'+character).animate({ width: '106px' },{ duration: 300, easing: 'easeOutExpo' });
	},delay);
}

// move batman
function moveBatman(element,y,delay) {
	var element = $(element);
	setTimeout(function(){
		element.animate({ top: y },{ duration: 600, easing: 'easeOutExpo' });
	},delay);
}

// delay animation
function batmanBack(batCount){
	setTimeout(function(){
		moveBatman('#batman',0,0);
	},2000);
	setTimeout(function(){
		if(batCount == 3) alert('Nå må du nesten slutte å plage Batman. Han blir så gretten om mårran når dere drar han i ørene når han henger opp ned og sover. Zzzzzz...');
		if(batCount == 5) alert('Hehehehe ikke gi opp!! Nå skjer det snart noe spennende her!! Eller gjør det det?');
		if(batCount == 7) alert('ZZzzzz....smatt smatt...nei Robin, ikke der...');
		if(batCount == 8) alert('...zzzz...BØ!!!');
		if(batCount == 10) alert('Alle gode ting er 10...små sauer hopper i havet plask plask så var ullen flat.');
	},1000);
}


// Interactive showcase
function SHOWCASEinit(){

	// detect internet explorer 7 and 8 to fix fade issue
	var browser = $.browser.browser();
	var version = $.browser.version.number();
	var explorer = false;
	if(browser=='Internet Explorer' && version<9) explorer = true;
	
	// fade duration
	var fade_speed = 800; 
	// move duration when moving characters out of frame
	var move_speed = 400; 
	// time until the showcase starts
	var fade_start = 200; 
	// delay between characters
	var fade_delay = 100; 
	// characters
	var characters = Array('rambo','wonder-woman','morgan-kane','scarface','batman');
	// characters top css
	var characters_left_css = Array(455,165,665,20,810);
	// characters bottom css
	var characters_bottom_css = Array(0,0,50,65,161);
	// individual delay set in loop
	var delay = 0;
	// holds the character for later
	var current_character = 0;
	// mouseover speed
	var hover_in = 200;
	// mouseout speed
	var hover_out = 0;
	// batman counter
	var batCount = 0;
	// currently selected character
	var current_character;

	// sliding in all characters in a sequence
	resetCharacters(characters,characters_left_css,characters_bottom_css,fade_start,fade_delay,fade_speed,'in',0);

	// character click
	$('.character img,.character .dialogue').click(function() {
		current_character = $(this).parents('div').attr('id');
		if(current_character == "scarface") {
			window.location = $(this).parents('div').find('a').attr('href');
		}
		else {
	 		// move all characters down/out in a sequence
	 		for (i=characters.length; i>=0; i--) {
	 			moveCharacter('#'+characters[i],fade_start+(fade_delay*i),move_speed,-230,'easeInExpo');
	 		}
	 		// set up main character to animate in
	 		mainCharacter(current_character,1500,explorer);
		}
	});

	// detecting iDevice
	var deviceAgent = navigator.userAgent.toLowerCase();
	var iDevice = deviceAgent.match(/(iphone|ipod|ipad)/);
	
	// hover functions (disabled on iOS)
	if(!iDevice){
		// character hover
		$('.character').hover(function(){
			// the character being hovered
			current_character = $(this).attr('id');
			// dimming down all others
			if(!explorer) for (i=0; i<characters.length; i++) if(characters[i] != current_character) $('#'+characters[i]).fadeTo(hover_in, 0.3);
			// adding yellow marker
			$('#ym-'+current_character).stop().animate({ width: '106px' },{ duration: 500, easing: 'easeOutExpo' });
		
		},function(){
			//current_character = $(this).parents('div').attr('id');
			// fading all characters in
			if(!explorer) for (i=0; i<characters.length; i++) $('#'+characters[i]).fadeTo(hover_out, 1);
			// removing yellow-marker
			if($('#'+current_character+' .dialogue .dialogue_text.intro').is(':visible')) $('#ym-'+current_character).stop().animate({ width: '0px' },{ duration: 300, easing: 'easeOutExpo' });
		});
	
		// batman hover
		$('#batman').hover(function(){
			moveBatman('#batman',-150,0);
		},function(){
			batCount++;
			batmanBack(batCount);
		});
	}
	
	// batman hover
	$('.dialogue_close').hover(function(){
		$(this).css('background-position','17px -31px');
	},function(){
		$(this).css('background-position','17px 9px');
	});

	// batman click (iPhone or speedy fingers)
	$('#batman').click(function() {
		moveBatman('#batman',-150,0);
		batCount++;
		batmanBack(batCount);
	});

	// character/dialogue close button
	$('.dialogue_close').click(function() {
		// animate character out
		if(!explorer) $('#'+current_character+' .extended').animate({ opacity: 0 }, 200);
		moveCharacter('#'+current_character,0,move_speed,-230,'easeInExpo');
		resetCharacters(characters,characters_left_css,characters_bottom_css,fade_start,fade_delay,fade_speed,'in',1000);
		// hiding talking mouth
		$('.mouth').css('visibility','hidden');
	});

}
