var xmldata = "";
var poem_id = 1;
var current_chapter = "";
var navigation_index_ul = "";
var last_poem_id;

$(window).bind('load', function() {
    var preload = new Array();
    $(".hover").each(function() {
        s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
        preload.push(s);
    });
    var img = document.createElement('img');
    $(img).bind('load', function() {
        if(preload[0]) {
            this.src = preload.shift();
        }
    }).trigger('load');

});


function isInt(x) { 
   var y=parseInt(x, 10); 
   if (isNaN(y)) return false; 
   return x==y && x.toString()==y.toString(); 
}

function chapter(poem_id) {
	return $(xmldata).find("poem[id=\""+poem_id+"\"]").parent().attr("name");
}

function generate_navigation_index(book) {
   if (book == 'blank') {
   	section_A = $(xmldata).find("section[id=A]");
   	section_B = $(xmldata).find("section[id=B]");

   	chapters = section_A.find("chapter");
   	chapters.each(function(index) {
   		ch_name = $(this).attr("name");
   		ch_first_poem_id = $(this).find("poem").attr("id");
   		ch_link = $.address.baseURL()+"/#/"+ch_first_poem_id+"";
   		navigation_index_ul +=  "<li><a href=\""+ch_link+"\">"+ch_name+"</a></li>";
   	});
   	$("div#section_A").html("A. TIME");
   	$('ul#navigation_list_section_A').html(navigation_index_ul);
   	$('ul#navigation_list_section_A li a').click(function() {
   		$.fancybox.close();
   		return true;
   	});

   	navigation_index_ul = "";
   	chapters = section_B.find("chapter");
   	chapters.each(function(index) {
   		ch_name = $(this).attr("name");
   		ch_first_poem_id = $(this).find("poem").attr("id");
   		ch_link = $.address.baseURL()+"/#/"+ch_first_poem_id+"";
   		navigation_index_ul +=  "<li><a href=\""+ch_link+"\">"+ch_name+"</a></li>";
   	});
   	$("div#section_B").html("B. Living and dying");
   	$('ul#navigation_list_section_B').html(navigation_index_ul);
   	$('ul#navigation_list_section_B li a').click(function() {
   		$.fancybox.close();
   		return true;
   	});
   } else if (book == 'blind') {
   	section_A = $(xmldata).find("section[id=A]");
   	chapters = section_A.find("chapter");
   	chapters.each(function(index) {
   		ch_name = $(this).attr("name");
   		ch_first_poem_id = $(this).find("poem").attr("id");
   		ch_link = $.address.baseURL()+"#/"+ch_first_poem_id+"";
   		navigation_index_ul +=  "<li><a href=\""+ch_link+"\">"+ch_name+"</a></li>";
   	});
      // $("div#section_B").html("B. Living and dying");
      $("div#section_B").hide();
   	$('ul#navigation_list_section_B').html(navigation_index_ul);
   	$('ul#navigation_list_section_B li a').click(function() {
   		$.fancybox.close();
   		return true;
   	});
   }

}


function random_poem_id() {
	return Math.floor((340-2)*Math.random());
}

function show_poem (poem_id) {
	
	if (parseInt(poem_id, 10) > parseInt(last_poem_id, 10)) {
		$.address.path("trilogy_index");
		return;
	}
	if (parseInt(poem_id, 10) < 1) {
		$.address.path("trilogy_index");
		return;
	}
	
	$('div.content_title').hide();
	$('div.content_text').hide();
	
	poem = $(xmldata).find("poem[id="+poem_id+"]");
	poem_text_raw = poem.text();
	poem_text = poem_text_raw.replace(/\n/gi, "<br />");
	poem_text_facebook_description = poem_text_raw.replace(/\n/gi, " ").replace(/,/gi, " ");
	poem_text_tweet = poem_text_raw.replace(/\t/gi, "").replace(/\n/gi, " ").replace(/^ /, "");
	
	poem_title = poem.attr("title");
	poem_sqlid = poem.attr("sqlid");
	$('div.content_title').text(poem_title);
	$('div.content_text').html("");
	$('div.content_text').html(poem_text);
	$('div.content_poem_id').html(poem_id);
	self_url_fb = 'http://'+window.location.host+window.location.pathname+'?poem_id='+poem_sqlid+"/#/"+$.address.pathNames();
	if (window.location.pathname.indexOf('blind') > -1 ) {
  	self_url_twitter = "http://sn.im/blindm"+$.address.pathNames();
	} else {
  	self_url_twitter = "http://sn.im/blankm"+$.address.pathNames();
	}
	
	// facebook share update
	$("a.button_facebook").attr("href", "http://www.facebook.com/sharer.php?u="+encodeURIComponent(self_url_fb));
	$("meta[name=description]").attr("content", poem_text_tweet);
	// twitter share update
	if ((self_url_twitter+poem_text_tweet).length > 140) {
		poem_text_tweet = "I 've just read a poem I like very much "+self_url_twitter;
	} else {
		poem_text_tweet += " "+self_url_twitter; 
	}
	$("a.button_twitter").attr("href", "http://twitter.com/home?status="+encodeURIComponent(poem_text_tweet));
	
	// update chapter
	if ( (current_chapter == "" ) || (chapter(poem_id) != current_chapter)) {
		$('h2#menu_chapter_name a').text(chapter(poem_id));
		// $('h2#menu_chapter_name').fadeIn(1200);
		current_chapter = chapter(poem_id);
	}
	// show poem content
	$('div.content_title').fadeIn("fast");
	$('div.content_text').fadeIn("fast");
	$('div.share_buttons_wrapper_wrapper').fadeIn("fast");
 	$('h2#menu_chapter_name').fadeIn("fast");
	
	// update meta tag
	$("meta[type=description]").attr("content", poem_text_tweet);
	// re cufon poem content
	Cufon.replace('h2', {
		fontWeight: '300'
	});
	Cufon.replace('div.content_text', {
		letterSpacing: '1px'
	});
	
} // end function show_poem












$(document).ready(function() {
	
   // trilogy books page
   $('div.trilogy_index_wrapper img').fadeTo('fast', '0.5');
	$('div.trilogy_index_wrapper a').hover(function() {
	   $(this).find('img').fadeTo('fast', '1');
	}, function() {
	   $(this).find('img').fadeTo('fast', '0.5');
	});
	
	$('a[rel=deeplink]').click(function() {
       $.address.value($(this).attr('href'));
		return false;
   });

   $('a[rel=deeplink]').address(function() {
   });
	
		
	// history
	// main EVENT - changing address
	
	
	// BUTTONS funcitonality
	$('a.button_next').click(function() {
		poem_id++;
		$.address.path(poem_id);
		return false;
	});

	$('a.button_prev').click(function() {
		poem_id--;
		$.address.path(poem_id);
		return false;
	});

	$('a.button_random').click(function() {
		poem_id = random_poem_id();
		$.address.path(poem_id);
		return false;
	});
	
	$("a.menu_poems_link").click(function() {
		$("div.content_wrapper").children().hide();
		poem_id = 1;
		show_poem(poem_id);
		$("div.poem_wrapper").fadeIn();
		return false;
	});
	
	
	$('ul#navigation_list_section_B li a').click(function() {
		$.fancybox.close();
		return true;
	});
	
	$('ul#navigation_list_section_A li a').click(function() {
		$.fancybox.close();
		return true;
	});
	
	
	
	
	// tooltips - tipsy
	$("div.content_buttons a").tipsy({
		delayIn: 0,
      delayOut: 0,
      fade: false,
      fallback: '',
      gravity: 'n',
      html: false,
      opacity: 1.0
	});
	
	$("a.button_facebook, a.button_twitter").tipsy({
		delayIn: 0,
      delayOut: 0,
      fade: false,
      fallback: '',
      gravity: 'w',
      html: false,
      opacity: 1.0	
	});
	
	$("a#trilogy_index_link").tipsy({
	    delayIn: 0,
      delayOut: 0,
      fade: false,
      fallback: '',
      gravity: 's',
      html: false,
      opacity: 1.0	
	}); 
	
	
	// navigation - index - fancybox
	$("a#navigation_link, a#menu_navigation_link").fancybox({
		'hideOnContentClick': false,
		'hideOnOverlayClick' : true,
		'scrolling': 'yes',
		'autoDimensions' : false,
		'width' : 400,
		'height' : 450,
		'overlayOpacity' : 0.8,
		'centerOnScroll' : false
	});
	
	
	// preloading hover image
	$(".hover").each(function() {
	    if ($(this).attr("src").match(/_on\.(.+)$/i)) {
	        $(this).removeClass("hover");
	    }
	});
	$(".hover").hover(function() {
	    s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
	    $(this).attr("src", s);
	}, function() {
	    s = $(this).attr("src").replace(/_on\.(.+)$/i, ".$1");
	    $(this).attr("src", s);
	});
	
	
	Cufon.now();	
});


Cufon.replace('h1 a', {
	fontWeight: '500',
	hover: {
		color: '#333'
	}
});
Cufon.replace('h2', {
	fontWeight: '300'
	
});
Cufon.replace('h3', {
	fontWeight: '100',
	letterSpacing : '1px'
});
Cufon.replace('h4 a', {
	hover: {
		color: '#333',
		fontWeight: '900'
	}
});
Cufon.replace('h5');
Cufon.replace('div.content_text', {
	letterSpacing: '1px'
});



// parseXml
function parseXml (xml) {
	$("div.loading_wrapper").fadeOut("slow");

	xmldata = xml;
	last_poem = $(xmldata).find("poem[title=END]");
	last_poem_id = last_poem.attr("id");
	$.address.change(function(event) {
		content = event.pathNames[0];

		// set content
		if (!isInt(content)) {
			$("div.content_wrapper").children().hide();
			$("div.share_buttons_wrapper_wrapper").hide();
			$('h2#menu_chapter_name').hide();
			$("div."+content+"_wrapper").fadeIn();
			// set meta tags and staff
		} else {
			// else it is a poem!
			$("div.content_wrapper").children().hide();
			$("div.poem_wrapper").show();
			poem_id = content;
			show_poem(poem_id);
		}

	});
	
	if (isInt($.address.pathNames())) {
		// comes from external link with poem_id
		poem_id = $.address.pathNames()[0];
		show_poem($.address.pathNames()[0]);
	} else {
		// $.address.path("about_the_book");
		$.address.path(1);
	}
	
	
   // generate_navigation_index('blind');
}







