$(document).ready(function(){
	var tracker = eConduit.createEventTracker();

	$("#whatyougeek").validate();
	$("#contact-form").validate();

	// Initialize gallery
	$('ul.gallery').galleria({
		history : false,
		insert : '#stage',
		onImage : function(image,caption,thumb) {

			// fade in the image & caption
			if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
				image.css('display','none').fadeIn(1000);
			}
			caption.css('display','none').fadeIn(1000);

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500,0.3);

			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');

			// add a title for the clickable image
			image.attr('title','Next image >>');
		},
		onThumb : function(thumb) { // thumbnail effects goes here

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';

			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);

			// hover effects
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}

	});


	$('ul.gallery').everyTime(11000, function(e) {
		$.galleria.next();
	});

	// Event handlers for the trackers
	$("#nav-geekon a").click(function(e) {
		tracker.trackEvent("nav-geekon");
		return true;
	});

	$("#nav-library a").click(function(e) {
		tracker.trackEvent("nav-library");
		return true;
	});

	$("#nav-support a").click(function(e) {
		tracker.trackEvent("nav-support");
		return true;
	});

	$("div#footer #footer_about").click(function(e) {
		tracker.trackEvent("footer_about");
		return true;
	});

	$("div#footer #footer_librarians").click(function(e) {
		tracker.trackEvent("footer_librarians");
		return true;
	});

	$("div#footer #footer_press").click(function(e) {
		tracker.trackEvent("footer_press");
		return true;
	});

	$("div#footer #footer_contact").click(function(e) {
		tracker.trackEvent("footer_contact");
		return true;
	});

	$("div#footer #footer_terms").click(function(e) {
		tracker.trackEvent("footer_terms");
		return true;

	});




	// See The Latest - Open and close Share This
	$('a.get-local').click(function() {
		$('ul#local-filter').toggle("fast");
		$('div#at15s').hide();
	});
	$('a.share-this').click(function() {
		$('ul#local-filter').hide();
	});
	// See The Latest - Close box on mouse out
	$('ul#local-filter').mouseleave(function(){
		$(this).toggle("fast");
	});

	// Animate main interior navigation
	$('ul#main-nav-int li#nav-geekon').hover(
		function(){
			$('li#nav-geekon strong').animate({
				marginTop: "0px"
			});
			$('li#nav-geekon span').fadeIn();
		},
		function(){
			$('li#nav-geekon span').fadeOut();
			$('li#nav-geekon strong').animate({
				marginTop: "18px"
			});
		}
	);
	$('ul#main-nav-int li#nav-library').hover(
		function(){
			$('li#nav-library strong').animate({
				marginTop: "0px"
			});
			$('li#nav-library span').fadeIn();
		},
		function(){
			$('li#nav-library span').fadeOut();
			$('li#nav-library strong').animate({
				marginTop: "18px"
			});
		}
	);
	$('ul#main-nav-int li#nav-support').hover(
		function(){
			$('li#nav-support strong').animate({
				marginTop: "0px"
			});
			$('li#nav-support span').fadeIn();
		},
		function(){
			$('li#nav-support span').fadeOut();
			$('li#nav-support strong').animate({
				marginTop: "18px"
			});
		}
	);

	// Myth or Reality cards
			$('div.myth').toggle(
				function(){
					$(this).css({'background' : 'url(/geekthelibrary-static/themes/geek-the-library/reality.png) no-repeat #cb0c32'});
					$(this).find("h2").hide();
					$(this).find("p").show();
				},
				function(){
					$(this).css({'background' : 'url(/geekthelibrary-static/themes/geek-the-library/myth.png) no-repeat #000'});
					$(this).find("p").hide();
					$(this).find("h2").show();
				}
			);

			// Standard Gear list views
			$('#see-wdyg').click(function(){
				$('#gygo-gear').hide();
				$('#posters').hide();
				$('#wdyg-gear').show();
				$(this).addClass("view");
				$('#see-gygo').removeClass("view");
				$('#see-posters').removeClass("view");
			});

			$('#see-gygo').click(function(){
				$('#wdyg-gear').hide();
				$('#posters').hide();
				$('#gygo-gear').show();
				$(this).addClass("view");
				$('#see-wdyg').removeClass("view");
				$('#see-posters').removeClass("view");
			});
			$('#see-posters').click(function(){
				$('#wdyg-gear').hide();
				$('#gygo-gear').hide();
				$('#posters').show();
				$(this).addClass("view");
				$('#see-wdyg').removeClass("view");
				$('#see-gygo').removeClass("view");
			});

			// Wallpapers display download options
			$('.wp').click(function(){
				$(this).find("ul").show();
			});
			$('.wp').mouseleave(function(){
				$(this).find("ul").hide();
			});

			// Geek the library cards
			$('.value-holder').toggle(
				function(){
				$(this).next().find("div").animate({
					marginLeft: "-9999px"
				}, "slow");
				$(this).css("background-position","0 0");
			},
				function(){
				$(this).next().find("div").animate({
					marginLeft: "0"
				}, 1000);
				$(this).css("background-position","0 -238px");
});

	//
	// Wallpapers display download options
	//
	$('.wp').click(function(){
		$(this).find("ul").show();
	});
	$('.wp').mouseleave(function(){
		$(this).find("ul").hide();
	});

	//
	// Web Banner displays
	//
	$('#select-square').click(function(){
		$('#horizontal-banners').hide();
		$('#select-horizontal').removeClass("banner-on");
		$('#vertical-banners').hide();
		$('#select-vertical').removeClass("banner-on");
		$(this).addClass('banner-on');
		$('#square-banners').fadeIn();
	});
	$('#select-vertical').click(function(){
		$('#horizontal-banners').hide();
		$('#select-horizontal').removeClass("banner-on");
		$('#square-banners').hide();
		$('#select-square').removeClass("banner-on");
		$(this).addClass('banner-on');
		$('#vertical-banners').fadeIn();
	});
	$('#select-horizontal').click(function(){
		$('#square-banners').hide();
		$('#select-square').removeClass("banner-on");
		$('#vertical-banners').hide();
		$('#select-vertical').removeClass("banner-on");
		$(this).addClass('banner-on');
		$('#horizontal-banners').fadeIn();
	});
	
	//
	// Scrolling for events page
	//
	$('a#georgia-l').click(function(){
		$.scrollTo('#georgia', 1000);
	})
	$('a#illinois-l').click(function(){
		$.scrollTo('#illinois', 1000);
	})
	$('a#indiana-l').click(function(){
		$.scrollTo('#indiana', 1000);
	})
	$('a#iowa-l').click(function(){
		$.scrollTo('#iowa', 1000);
	})
	$('a#wisconsin-l').click(function(){
		$.scrollTo('#wisconsin', 1000);
	})



	//
	// Focus events for signup form
	//
	$('#giq-email').focus(function (e) {
		 if ($('#giq-email').val().toLowerCase()=="e-mail address")
			$('#giq-email').val("");

	});
	$('#giq-email').blur(function(){
			 if ($('#giq-email').val()=="")
				$('#giq-email').val("E-mail Address");

	});

	$('#giq-zip').focus(function (e) {
		 if ($('#giq-zip').val().toLowerCase()=="zip code")
			$('#giq-zip').val("");

	});
	$('#giq-zip').blur(function(){
			 if ($('#giq-zip').val()=="")
				$('#giq-zip').val("ZIP Code");

	});



	//
	// Survey modal function
	//
	$('a.takesurvey').click(function (e) {
		tracker.trackEvent("survey_link");
		e.preventDefault();
		// load the form using ajax
		tb_show('','http://survey.geekthelibrary.org/index2/?TB_iframe=true&width=536&height=500&modal=false');
	});
	$('#giq-submit').click(function (e) {
	        tracker.trackEvent("nav_signup");
		e.preventDefault();
		// load the form using ajax
		var email = $('input#giq-email').val();
		var zip = $('input#giq-zip').val();
		// Only go to the page if we have an email or zip
		if(email == "E-mail Address" || zip == "Zip Code")
			return false;

		var params = "email=" + email + "&zip=" + zip;
		tb_show('','http://survey.geekthelibrary.org/signup_process?' + params + '&TB_iframe=true&width=536&height=500&modal=false');

	});
	
	// Home page email signup function
	$('a#email-home').click(function (e) {
		tracker.trackEvent("email_link");
		e.preventDefault();
		// load the form using ajax
		tb_show('','http://survey.geekthelibrary.org/signup_process/?TB_iframe=true&width=536&height=500&modal=false');
	});

	// Letter modal function
	$('a#letter').click(function (e) {
	        tracker.trackEvent("sample_letter");
		e.preventDefault();
		// load the form using ajax
		tb_show('','/geekthelibrary-static/themes/geek-the-library/sample-letter.html?TB_iframe=true&width=536&height=500&modal=false');

	});

	//
	// Letter modal function
	//
	$('a#libgeek').click(function (e) {
		tracker.trackEvent("submit_story_librarian");
		e.preventDefault();
		// load the form using ajax
		tb_show('','/geekthelibrary-static/themes/geek-the-library/librarian-form.html?TB_iframe=true&width=536&height=500&modal=false');

	});

	//
	// Process the igeek form
	//
	$('div#geekbook-form-overlay').click(function(e) {
		$('input#name').val("");
		$('input#email').val("");
		$('input#geek').val("");
		$('textarea#story').val("");
	});

	$('form#contact-form input.btn-submit').click(function (e) {
		tracker.trackEvent("submit_story");

		// Get the form parameters
		var contact_type = str = $("input[name='contact-type']:checked").val();
		var name = $('input#name').val();
		var email = $('input#email').val();
		var phone = $('input#phone').val();
		var comments = $('#comments').val();

		// Clean out JS
		name = sanitizeJS(name);
		phone = sanitizeJS(phone);


		// Dont bother if we dont have data
		if (name == undefined ||
		    name.length == 0)
		    {
			return false;
		    }
		if(phone == undefined ||
		    phone.length == 0 )
		    {

			return false;
		    }
		if(comments == undefined  ||
		    comments.length == 0)
		    {
			return false;
		    }


		// Conver html characters.
		name = htmlspecialchars(name,'ENT_NOQUOTES');
		name = name.replace(/\n/g,"");
		phone = htmlspecialchars(phone,'ENT_NOQUOTES');
		comments = comments.replace(/\n/g,"<br/>");
		comments = comments.replace(/'/g,"\\'");

		var request = "{name:'"+name+"',phone:'"+ phone + "',email:'"+ email + "',comments:'"+ comments + "',contact_type:'"+contact_type+"'}";
		$.ajax({
		   type: "POST",
		   url: "/geekthelibrary_config/plugins/IGeek/contact.cgi",
		   contentType: "application/json",
		   processData: false,
		   data: request,
		   success: function(msg){
		     var s = 'Thank you!, We have received your comment. Check back soon to see if your story is featured on our site.';
		     if(msg.indexOf("{") == -1 || $.evalJSON(msg).success != "true")
		     {
			s = 'Error!,We experienced and error while processing your request please, try again at a later time.';
		     }
		     alert(s);
		   },
		   error: function(msg){
		   	alert(msg);
		   }
		});
		$('input#name').val("");
		$('input#phone').val("");
		$('textarea#comments').val("");
		$('input#email').val("");

		return false;
	});
	$('form#whatyougeek input.btn-submit').click(function (e) {

		// Get the form parameters
		var name = $('input#name').val();
		var email = $('input#email').val();
		var geek = $('input#geek').val();
		var story = $('#story').val();

		// Clean out JS
		name = sanitizeJS(name);
		geek = sanitizeJS(geek);


		// Dont bother if we dont have data

		if(name == undefined ||
		    name.length == 0 )
		    {

			return false;
		    }

		if(geek == undefined  ||
		    geek.length == 0)
		    {
			return false;
		    }
		if (story == undefined ||
		    story.length == 0)
		    {
			return false;
		    }



		// Conver html characters.
		name = htmlspecialchars(name,'ENT_QUOTES');
		geek = geek.replace(/ /g,"");
		geek = geek.replace(/'/g,"\\'");
		story = story.replace(/\n/g,"<br/>");
		story = story.replace(/'/g,"\\'");

		// Show a panel showing the progress
		$('div#geekbook-form-overlay').html("<h3>Processing.......</h3>");
		$('div#geekbook-form-overlay').show();

		var request = "{name:'"+name+"',geek:'"+geek+"',email:'"+email+"',story:'"+story+"',state:'',librarian:'0'}";
		// Submit to the entry
		$.ajax({
		   type: "POST",
		   url: "/geekthelibrary_config/plugins/IGeek/igeek.cgi",
		    contentType: "application/json",
		    processData: false,
		    data: request,
		   success: function(msg){
		     var s = '<h1 id="success">Thank you!</h1><p>We have received your story and it will be reviewed by our editors.</p><p>Check back soon to see if your story is featured on our site.</p>';
		     if($.evalJSON(msg).success != "true")
		     {
			s = '<h1 id="error">Error!</h1><p>We experienced and error while processing your request please, try again at a later time.</p>';
		     }

		     $('div#geekbook-form-overlay').html(s);
		   },
		   error: function(msg){
		   }
		});
		// Close the frame after n seconds
		$('div#geekbook-form-overlay').oneTime(4500, function() {
			$(this).hide();
			$('input#name').val("");
			$('input#email').val("");
			$('input#geek').val("");
			$('textarea#story').val("");
		});

		return false;

	});

	//
	// Librarian form
	//
	$("#libgeek-form").validate();
	$('#libgeek-form input.btn-submit').click(function (e) {
		// Get the form parameters
		var name = $('input#name').val();
		var email = $('input#email').val();
		var geek = $('input#igeek').val();
		var story = $('#comments').val();
		var state = $('#state').val();


		// Clean out JS
		name = sanitizeJS(name);
		geek = sanitizeJS(geek);
		story = sanitizeJS(story);
		state = sanitizeJS(state);


		// Dont bother if we dont have data
		if (story == undefined ||
			story.length == 0)
			{
			alert("Your are required to provide a story");
			return false;
			}
		if(name == undefined ||
			name.length == 0 )
			{
			alert("Please provide your name.");
			return false;
			}
		if(geek == undefined  ||
			geek.length == 0)
			{
			alert("Please tell us what you geek.");
			return false;
			}


		// Conver html characters.
		name = htmlspecialchars(name,'ENT_QUOTES');
		state = htmlspecialchars(state,'ENT_QUOTES');

		geek = geek.replace(/ /g,"");
		geek = geek.replace(/'/g,"\\'");
		story = story.replace(/\n/g,"<br/>");
		story = story.replace(/'/g,"\\'");


		var request = "{name:'"+name+"',geek:'"+geek+"',email:'"+email+"',story:'"+story+"',state:'',librarian:'1'}";
		// Submit to the entry
		$.ajax({
		   type: "POST",
		   url: "/geekthelibrary_config/plugins/IGeek/igeek.cgi",
		    contentType: "application/json",
		    processData: false,
		    data: request,
 		    success: function(msg){
			 var s = 'Thank you!, We have received your story and it will be reviewed by our editors. Check back soon to see if your story is featured on our site.';
			 if($.evalJSON(msg).success != "true")
			 {
			 	s = 'Error!, We experienced and error while processing your request please, try again at a later time.';
			 }
			 alert(s);
		     }
		   });

		$('input#name').val("");
		$('input#email').val("");
		$('input#igeek').val("");
		$('#comments').val("");
		$('#state').val("");
		return false;
	});




	// Survey
	var survey = {
		open : function (dialog) {
			dialog.overlay.fadeIn('slow', function () {
				dialog.container.fadeIn('fast', function () {
					dialog.data.fadeIn('fast');
				});
			});
		},
		close : function (dialog) {
			dialog.data.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.overlay.fadeOut('slow', function () {
						$.modal.close();
					});
				});
			});
		},
		die : function (dialog) {
			$("iframe").unload( function () {
				alert("Bye now!");
			});
		}

	}
});


function doKeyDown()
{

	document.getElementById('igeek-btn').click();
}

function setIGeek(f)
{
	// Get the form parameters
	var geek_text = "something";
	geek_text = f.parentNode.elements[0].value;

	// Clean out JS
	geek_text = sanitizeJS(geek_text);

	// Conver html characters.
	geek_text = htmlspecialchars(geek_text,'ENT_QUOTES');

	if (geek_text == '')
		geek_text="something";
	$.cookie('igeek', null);
	$.cookie('igeek', geek_text, { path: '/', expires: 1 });
	 return true;

}

function sanitizeJS(input) {

	var result = '';
	var rj = new RegExp(/javascript/i);
  	var m = rj.exec(input);
        if (m == null) {
		result = input;

	}
	else
	{
		return result;
	}

	var rs = new RegExp(/jscript/i);
	m = rs.exec(input);
	if (m == null) {
		result = input;
	}
	else
	{
		return result;
	}

	var rv = new RegExp(/vbscript/i);
	if (m == null) {
		result = input;
	}
	else
	{
		return result;
	}

	return result;

}
function get_html_translation_table(table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities
    //
    // version: 906.401
    // discuss at: http://phpjs.org/functions/get_html_translation_table

    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};

    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';

    // ascii decimals for better compatibility
    entities['38'] = '&amp;';

    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }

    return histogram;
}

function htmlspecialchars (string, quote_style) {
    // Convert special characters to HTML entities
    //
    // version: 906.401
    // discuss at: http://phpjs.org/functions/htmlspecialchars
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();

    if (false === (histogram = this.get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }

    histogram["'"] = '&#039;';
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }

    return tmp_str;
}