var paypalEnabled = true;

function stripHTML(oldString) {

  return oldString.replace(/(<([^>]+)>)/ig,""); 
  
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<1; i++){ // twitters.length
    var username = twitters[i].user.screen_name;
	var userimg = twitters[i].user.profile_image_url;
	
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'" target="_blank">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'" target="_blank">'+reply.substring(1)+'</a>';
    });
	
	var stripStatus = escape(stripHTML(status));
	//alert(stripStatus);
    statusHTML.push('<div id="status"><div id="statuscontent"><div><img src="'+userimg+'" alt="'+username+'" title="'+username+'"/></div><p>&ldquo;'+status+'&rdquo;</p></div><div id="twitterlinks"><div id="tweettime">'+relative_time(twitters[i].created_at)+'</div><div id="tweetlinks"><a href="http://twitter.com/home/?status=RT @'+username+' '+stripStatus+'" class="rt" target="_blank">Retweet</a></div></div></div>');
  }
  
  $('.loading').fadeOut(750, function() {
		 $('#latest_tweet').append($(statusHTML.join('')).hide().fadeIn(750));									
  });
  
  //document.getElementById('latest_tweet').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'about a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

checkExternalClick = function(event)
{
  if ($(event.target).parents('.activedropdown').length === 0)
  {
    $('.activedropdown').removeClass('activedropdown');
    $('.options').hide();
  }
};

$(document).ready(function() {
	
	if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
	
		if ($("#homehead").length) {
			$("#homehead").pngFix();
		}
		
		if ($("#sbplogo").length) {
			$("#sbplogo").pngFix();
		}
		
		if ($("#cyblogo").length) {
			$("#cyblogo").pngFix();
		}
		
		if ($("#social").length) {
			$("#social").pngFix();
		} 
		
		if ($("#comingsoon").length) {
			$("#comingsoon").pngFix();
		}

	}
	
	if ($(".agenda_item").length) {
		$(".agenda_item").each(function(e) {
			if ((e+1)%5 == 0) {
				$(this).append("<span class='agenda_top'>go to top</span>").find(".agenda_top").click(function() {
					$(document).scrollTo($(".introbox"), 900);
				});
				
			}
		});
	}
	
	if ($(".speakerdata").length) {
		
		var transType = 1;
		var speakersArr = new Array(
			["ecarey", 500], 
			["jforrest", 373], 
			
			["gokeeffe", 400], 
			["edervisevic", 440], 
			["mmckeagney", 333],
			
			["ldonnelly", 380], 
			["pleddy", 353],
			
			["sbrennan", 370],
			["mjung", 450],
			["idodson", 400],
			
			["pbrodeur", 330],
			["bmartin", 373],
			["aquigley", 330],
			["rhiggins", 400]
		);
		
		if (transType == 0) {
		
			$(".speakerbox").each(function(){
				
				
				
				$(this).click(function(){
					if (!$(this).hasClass("opened")) {
					
						$(document).scrollTo($("#topbar"), 500);
						$(".speakerbox").each(function(){
							var tH = "25px";
							if ($(this).attr("id") == "ncad") tH = "50px";
							$(this).delay(300).removeClass("opened").delay(100).animate({
								height: tH
							}, 300, function(){
							
							});
						});
						
						var tHeight = 0;
						for (var a = 0; a < speakersArr.length; a++) {
							if ($(this).attr("id") == speakersArr[a][0]) {
								tHeight = speakersArr[a][1];
								break;
							}
						}
						
						$(this).delay(300).animate({
							height: tHeight
						}, 800, function(){
							$(document).scrollTo($(this), 500);
							$(this).addClass("opened");
						});
						
						
					}
				});
			});
		}
		
		if (transType == 1) {
			$(".speakerbox").each(function(){
				
				$(this).append("<span class='boxclose'>close</span>").find(".boxclose").click(function(e) {
					e.preventDefault();
					
					//alert($(this).parent().attr("class"));
					var tH = "25px";
					if ($(this).parent().attr("id") == "ncad") tH = "70px";
					$(this).parent().css("height",tH);
					$(this).parent().removeClass("opened");
					//$(this).parent().removeClass("opened");
				});
				
				
				$(".opened").each(function() {
					var tHeight = 0;
					for (var a = 0; a < speakersArr.length; a++) {
						if ($(this).attr("id") == speakersArr[a][0]) {
							tHeight = speakersArr[a][1];
							break;
						}
					}
					$(this).css("height",tHeight);
				});
				
				$(this).find(".speakerinfo").click(function(){
					if (!$(this).parent().hasClass("opened")) {

						/*$(".speakerbox").each(function(){
							$(this).removeClass("opened");
							$(this).css("height","25px");
						});*/
						
						var tHeight = 0;
						for (var a = 0; a < speakersArr.length; a++) {
							if ($(this).parent().attr("id") == speakersArr[a][0]) {
								tHeight = speakersArr[a][1];
								break;
							}
						}
						
						$(this).parent().css("height",tHeight+"px");
						$(this).parent().addClass("opened");
						$(document).scrollTo($(this).parent(), 500);
						
						
						
					}
				});
			});
		}
		
	}
	  
	 
});

$(window).load(function() {

	$(document).mousedown(checkExternalClick);
	
	if ($(".speakers").length) {
		$(".speakers").show();
	}
	
	var z = 999;
	var minItemsForScroll = 12;
	
	function positionElements() {
		
		var winH = $(window).height();
		var docH = $(document).height();
		
		var footendH = winH-$(".footend").offset().top;
		if (footendH > 50) {
			$(".footend").css("height", footendH);
		} else {
			$(".footend").css("height", "");
		}
			
		if ($("#videoplayer").length) {
	
			var vidpos = ($(window).height()-388)/2;
			$("#videoplayer").css("margin-top",vidpos);
		
	
		}	
		
	}
	
	$(window).resize(positionElements);
	positionElements();
	
	if ($("#videoplayer").length) {
		
		$("#teaser_video").click(function() {
		
			$("#overlay").show();
			$("#videoplayer").append("<div id='vid'></div>");
			var flashvars = {};
			flashvars.allowScriptAccess = "always";
			flashvars.allowFullScreen = true;
			
			var params = {};
			params.menu = "false";
			params.quality = "high";
			var attributes = {};
			
			swfobject.embedSWF("video/vidplayer.swf", "vid", "640", "360", "9.0.0", false, flashvars, params, attributes);
			
		});
		
		$("#vidclose").click(function() {
			swfobject.removeSWF("vid");
			$("#overlay").hide();
		});
		
		
	}
	
	if ($("#map").length) {
		initialize();
		
		$(".switcher").each(function() {
			var locType = $(this).parent().attr("class");
			$(this).click(function() {
				if ($(this).hasClass("selected")) {
					
					$(this).removeClass("selected");
					//alert(locType);
					if (locType == "restaurants") {
						showRestaurants = false;
					} else if (locType == "bars") {
						showBars = false;
					} else if (locType == "hotels") {
						showHotels = false;
					}
					
					refreshMap();
					
				} else {
					
					$(this).addClass("selected");
					
					if (locType == "restaurants") {
						showRestaurants = true;
					} else if (locType == "bars") {
						showBars = true;
					} else if (locType == "hotels") {
						showHotels = true;
					}
					
					refreshMap();
					
				}
			});
		});
	}
	
	if ($("#latest_tweet").length) {
		var username = 'digital_summit';
		$.getScript('http://twitter.com/statuses/user_timeline/' + username + '.json?callback=twitterCallback2&count=5');
	}
	
	function rebuildSelects(selectid){
	
		$('select').each(function(){
			var selectclass = $(this).attr("class");
			var selectident = $(this).attr("id");
			
			if (selectid == "") {
				selectident = "";
			}
			
			if (selectclass != "" && selectident == selectid) {
				
				$(this).parent().removeClass('enhanced');
				$(this).parent().find("dl").remove();
				if (!$(this).parent().hasClass('enhanced')) {
					targetselect = $(this);
					targetselect.hide();
					
					// set our target as the parent and mark as such
					var target = targetselect.parent();
					target.addClass('enhanced');
					
					// prep the target for our new markup
					target.append('<dl class="dropdown ' + selectclass + '"><dt><a class="dropdown_toggle" href="#"></a></dt><dd><div class="options ' + selectclass + '"><ul></ul></div></dd></dl>');
					target.find('.dropdown').css('zIndex', z);
					z--;
					
					// we don't want to see it yet
					target.find('.options').hide();
					
					// parse all options within the select and set indices
					var i = 0;
					targetselect.find('option').each(function(){
						// add the option
						target.find('.options ul').append('<li><a href="#"><span class="value">' + $(this).text() + '</span><span class="hidden index">' + $(this).val() + '</span></a></li>');
						
						// check to see if this is what the default should be
						if ($(this).attr('selected') == true) {
							targetselect.parent().find('a.dropdown_toggle').append('<span></span>').find('span').text($(this).text());
							targetselect.parent().find('a.dropdown_toggle').append('<span class="hidden selindex"></span>').find('span.selindex').text($(this).val());
						}
						
						i++;
						
						if (i == minItemsForScroll) 
							target.find('.options').addClass("biggie");
					});
					if (i == 1) 
						target.find('.options').css("top", "25px");
				}
			}
		});
		
		$('a.dropdown_toggle').die('click');
		$('a.dropdown_toggle').live('click', function(){
			var theseOptions = $(this).parent().parent().find('.options');
			if (theseOptions.css('display') == 'block') {
				$('.activedropdown').removeClass('activedropdown');
				theseOptions.hide();
			}
			else {
				theseOptions.parent().parent().addClass('activedropdown');
				theseOptions.show();
			}
			
			return false;
		});
		
		$('.options a').die('click');
		$('.options a').live('click', function(e){
			$('.options').hide();
			
			var enhanced = $(this).parent().parent().parent().parent().parent().parent();
			var realselect = enhanced.find('select');
			
			// set the proper index
			realselect[0].selectedIndex = $(this).find('span.index').text();
			
			// update the pseudo selected element
			enhanced.find('.dropdown_toggle').empty().append('<span></span>').find('span').text($(this).find('span.value').text());
			enhanced.find('.dropdown_toggle').append('<span class="hidden selindex"></span>').find('span.selindex').text($(this).find('span.index').text());
			
			if (realselect.attr("id") == "adultq" || realselect.attr("id") == "earlyq") updateCart();
			
			return false;
		});
		
		
		// end of rebuildSelects
	}
	
	
	//rebuildSelects("province");
	
	if (paypalEnabled) {
		
		var formhtml = "";
		formhtml += "<div class='ticketboxhead'>";
		formhtml += " 	<h4 class='helv'>BUY TICKETS</h4>";
		formhtml += " </div>";
		formhtml += " <div class='ticketboxrow clf gap'>";
		formhtml += " 	<div class='ticketboxtype'>Adult</div>";
		formhtml += " 	<div class='ticketboxprice'>&euro; 199.00 + VAT</div>";
		formhtml += " 	<div class='ticketboxquantity'>";
		formhtml += " 		<div><select name='' id='adultq' class='shortx'><option value='0'></option></select></div>";
		formhtml += " 	</div>";
		formhtml += " </div>";
		formhtml += " <div class='ticketboxrow clf'>";
		formhtml += " 	<div class='ticketboxtype'>Early Bird</div>";
		formhtml += " 	<div class='ticketboxprice'>&euro; 149.00 + VAT</div>";
		formhtml += " 	<div class='ticketboxprice' style='font-size:10px'>(Available until 7th March 2012)</div>";
		formhtml += " 	<div class='ticketboxquantity'>";
		formhtml += " 		<div><select name='' id='earlyq' class='shortx'><option value='0'></option></select></div>";
		formhtml += " 	</div>";
		formhtml += " </div>";
		formhtml += " <div class='ticketboxtotal divider clf'>";
		formhtml += " <span>Digital Summit Full Price &euro; 244.77 (incl VAT)</span><br /><br />";
		formhtml += " <span>Digital Summit Early Bird Price &euro; 183.27 (incl VAT)</span>";
		formhtml += " </div>";
		formhtml += " <div class='ticketboxtotal divider clf'>";
		formhtml += " 	<div class='ticketboxdesc'>Total Cost<br/><span>(including VAT)</span></div>";
		formhtml += " 	<div class='ticketboxtotalfield'><div class='mid'><input type='text' id='totalcost'/></div></div>";
		formhtml += " </div>";
		formhtml += " <div class='ticketboxtotal clf' id='totalbox'>";
		formhtml += " 	<div class='ticketboxtotalfield'><img src='img/buttons/checkout.png' alt='CHECKOUT' title='CHECKOUT' id='checkouotBt'/></div>";
		formhtml += " </div>";
		
		$("#colleft").find(".buytickets").empty().html(formhtml);
		
	} else {
		
		//$("#colleft").find(".buytickets").empty().html("<img src='img/tickets_soon.jpg' alt='BUY TICKETS - Tickets on sale soon!' title='BUY TICKETS - Tickets on sale soon!'/>");
		$("#colleft").find(".buytickets").addClass("presentations");
		$("#colleft").find(".buytickets").empty().html(
			"<h3 class='helv'>Download presentations from the National Digital Media & Marketing Summit 2011</h3>"+
			"<a href='files/MorningPresentations.zip'>Morning Presentations</a>"+
			"<a href='files/MorningCoffee.zip'>Morning Coffee Presentations</a>"+
			"<a href='files/Lunch.zip'>Lunch Presentations</a>"+
			"<a href='files/AfternoonTea.zip'>Afternoon Tea Presentations</a>"
		);
							
	}
	
	
	if ($("#checkouotBt").length) {
		
		$("#colleft").find(".buytickets").append("<form target='paypal' action='cart.php' method='post' id='introform'></form>");
		
		var appendSel = "";
		for (var b = 0; b < 51; b++) {
			appendSel += "<option value='"+b+"'>"+b+"</option>";
		}
		$("#adultq").empty();
		$("#earlyq").empty();
		$("#adultq").append(appendSel);
		$("#earlyq").append(appendSel);
		
		
		$("#checkouotBt").click(function() {
			checkout();
		});
	}
	
	var adultPrice = 244.77;
	var earlyPrice = 183.27;
	
	function checkout() {
		
		var totaladult = parseInt($("#adultq").val());
		var totalearly = parseInt($("#earlyq").val());
		
		$("#introform").append("<input type='hidden' name='adultprice' value='244.77'/>");
		$("#introform").append("<input type='hidden' name='earlyprice' value='183.27'/>");
		$("#introform").append("<input type='hidden' name='adultq' value='"+totaladult+"'/>");
		$("#introform").append("<input type='hidden' name='earlyq' value='"+totalearly+"'/>");
		
		if (totaladult == 0 && totalearly == 0) {
			alert("Please select at least one item.");
		} else {
			var pageTracker=_gat._getTracker("UA-12980667-1");
			pageTracker._trackEvent("Outbound Links", "Paypal/Register");
			//alert("X");
			$("#introform").submit();
		}
		
		
	}
	
	// paypal scripting 
	
	function updateCart() {
		
		
		var totalPrice = adultPrice*$("#adultq").val();
		totalPrice += earlyPrice*$("#earlyq").val();
		totalPrice = parseFloat(totalPrice).toFixed(2);
		$("#totalcost").val(totalPrice);
		
		
	}
	
	if ($(".speaker").length) {
		$(".speaker").each(function() {
			
			var itemClass = $(this).attr("class").replace("speaker ","");
			
			$(this).click(function() {
				if (itemClass == "ecarey") window.location = "speakers.php?id=1";
				if (itemClass == "jforrest") window.location = "speakers.php?id=2";
				if (itemClass == "gokeeffe") window.location = "speakers.php?id=3";
				if (itemClass == "edervisevic") window.location = "speakers.php?id=4";
				if (itemClass == "mmckeagney") window.location = "speakers.php?id=5";
				if (itemClass == "ldonnelly") window.location = "speakers.php?id=6";
				if (itemClass == "pleddy") window.location = "speakers.php?id=7";
				if (itemClass == "sbrennan") window.location = "speakers.php?id=10";
				if (itemClass == "mjung") window.location = "speakers.php?id=11";
				if (itemClass == "idodson") window.location = "speakers.php?id=12";
				if (itemClass == "pbrodeur") window.location = "speakers.php?id=13";
				if (itemClass == "bmartin") window.location = "speakers.php?id=14";
				if (itemClass == "aquigley") window.location = "speakers.php?id=15";
				if (itemClass == "rhiggins") window.location = "speakers.php?id=16";
			});
			
			$(this).hover(
  				function () {
    				$(this).find(".speakername").animate({
						left: '0'
					}, 500, function() {
					
					});
					$(this).find(".speakertitle").animate({
						left: '0'
					}, 600, function() {
					
					});
  				}, 
  				function () {
    				$(this).find(".speakername").animate({
						left: '-240'
					}, 150, function() {
					
					});
					$(this).find(".speakertitle").animate({
						left: '-240'
					}, 300, function() {
					
					});
  				}
			);

		});
	}
	

	
	
	rebuildSelects("");
	
});
