var plot;
var gridLoc;


// temp - fix hover out of plot, not highlighting "all"
function resetToAll(){
		if ($('#plotMenu>ul>li>a.selected').length == 0) {
			$("#plotMenu>ul>li>a:first").addClass('selected');
			Cufon.replace('#plotMenu>ul>li>a.selected');
		}
}


$(document).ready(function() {


// scroll itemsBrowser links to items via window scroller
$.localScroll({axis: 'y', offset:-100,lazy:true,duration: 250});

// ** YOUCRACK click
$("#YouCrack").click(function(){
	resetTopSelected();
	var obj= $("#plotMenu li.last>a").click();
	Cufon.replace(obj);
	$("#plotMenu a[title='YouCrack']").click();  // click menu item iself
});


// ** PLOT MENU: START **
	// Cufon (font replacement) for plot menu
	Cufon.replace('#plotMenu a', {hover: true});
	
	// HOVER (out) of plot menu
	$('#plotMenu').hover(function(){},function(){
		$('#plotMenu ul li ul:visible').each(function(){
			if ($('a.selected',this).length == 0) {
				$(this).slideUp(100,function(){
					$('#plotMenu ul li ul a.selected').parent().parent().show(100);
					resetTopSelected();
					$('#plotMenu ul li ul a.selected').parent().parent().prev().addClass("selected");
					Cufon.replace('#plotMenu>ul>li>a.selected');
				});
			}
		});
		setTimeout('resetToAll();',300);

	});


$("#plotMenu > ul > li > a:not(:first)").click(function() {
		var ul = $(this).next('ul');
		if ($(this).next('ul:hidden')) {
			resetTopSelected();
			$(this).addClass("selected");
			$('#plotMenu ul li ul:visible').slideUp(50);
			$(ul).slideDown(200);
		}
		return false;
});

$("#plotMenu > ul > li > a:first").click(function() {
			resetTopSelected();
			$(this).addClass("selected");	
});


/*
	// Hover (over) top menu item
	$('#plotMenu > ul > li > a').hover(function(){
		var ul = $(this).next('ul');
		if ($(this).next('ul:hidden')) {
			$('#plotMenu ul li ul:visible').slideUp(50);
			$(ul).slideDown(200);
		}
	},function(){
		// $(this).next('ul').slideUp(200);
	});
*/
	// ** plot menu click filter click **
	$('#plotMenu > ul > li > a:first, #plotMenu li ul li a:not(.disabled)').click( function(){
		$("#plotMenu a").removeClass("selected");  // clear selected
		$(this).parent().parent().parent().children("a:first").addClass("selected");  // add to catagory
		$(this).addClass("selected");
		
		var href = $(this).attr("href");
		// filter variable:  is the js variable name of the plot's data.
		var fVar = href.slice(href.lastIndexOf("/")+1);
		plot_init(fVar);   // draw plot

		// ** START - load ajax **
		$("#items").fadeTo(100,0.01,function() {
			$("#loading").show();
			$.get(href, function(data){  // ** AJAX GET MENU INTO TEXT (plot menu folder)
				$("#loading").hide();
				$("#items").html(data).fadeTo(250,1);
				Cufon.replace("#plotMenu li ul li a");  //refresh plot menu Cufon
			});
		});


/*   // OLD METHOD (keep it for later..) - show ALL ITEMS of the filter
		if (fVar == "all") {return false;}   // bypass for "ALL" item
		var idList="";	var sep="";
		$(eval(fVar)).each(function(i,val){ idList += sep+val[3]; sep=","; }); // Build idList
		
		$("#items").fadeOut(150,function() {
			$("#loading").show();
			$.get("index.php?q=crackingItemsList&idList="+idList, function(data){  // ** AJAX GET q=crackingItemsList **
				$("#loading").hide();
				$("#items").fadeIn(500);
				document.getElementById("items").innerHTML = data;  // old school - because of unknown IE bug...
				crackingItems_init();
			});
		});
*/
		// ** END - load ajax **
		
		return false;  // don't follow href
	});

	$('#plotMenu a.disabled').click( function(){return false;});   // don't follow href
	
	// ** PLOT MENU END **

	// ** Load first item by default **
	$("#plotMenu a:first").click();   // onload





	// ** Mouse exit graph -> return to selected item's tick label
	$("#placeholder").hover(function(){},function() {
		if (gridLoc) showTick(gridLoc[0],gridLoc[1]);
	});

	// ** PLOT HOVER **
    var previousPoint = null;
	var prevX,prevY;
    $("#placeholder").bind("plothover", function (event, pos, item) {
		
		// ** show tickLabel **
		var xX = Math.round(pos.x);
		var yY = Math.round(pos.y);

		if ((prevX != xX) || (prevY != yY)) {
			showTick(xX,yY);
			prevX= xX; prevY = yY;
		}
		// ** over an item? **
		if (item) {
			if (previousPoint != item.datapoint) {
				previousPoint = item.datapoint;

				// hover tooltip
				$("#tooltip").remove();
				var x = item.datapoint[0].toFixed(2),
					y = item.datapoint[1].toFixed(2);
				var cnt = item.datapoint[2];
				showTooltip(item.pageX, item.pageY+15,"Crackings: <b>"+ cnt + "</b><hr/>" 
					+ "<div>Outcome: <b>"+ getAxisTitle("y",Math.round(y))+ "</b></div><div>Type: <b>"+ getAxisTitle("x",Math.round(x)) +"</b></div>" );
			}
		}
		else {
			$("#tooltip").remove();
			previousPoint = null;            
		}
    });

	// ** PLOT CLICK **
	var previousClickPoint = null;
    $("#placeholder").bind("plotclick", function (event, pos, item) {
        if (item) {
            
			if (previousClickPoint) plot.unhighlight(item.series,previousClickPoint);
			if (previousClickPoint == item.datapoint) {
				// clean display
				previousClickPoint = null;
			}
			else {
				previousClickPoint = item.datapoint;
				plot.highlight(item.series, item.datapoint);
				gridLoc = item.datapoint;
				
				// load ajax here
				var idList = item.datapoint[3].toString();
				$("#items").fadeOut(300,function() {
					$("#loading").show();
					
					$.get("index.php?q=crackingItems&idList="+idList, function(data){  // ** AJAX GET q=crackingItems **
						$("#loading").hide();
						$("#items").html(data).show();
						crackingItems_init();
//						document.getElementById("items").innerHTML = data;  // old school - because of unknown IE bug...
					});
					
				});
			}
        }
    });
});


function resetTopSelected(obj) {
	$("#plotMenu > ul > li > a.selected").each(function(i){
		$(this).removeClass("selected");  // clean sisters
		Cufon.replace(this);
	});
}


// ** initialize plot with layer (hLayer) - to be changed in phase 2 **
function plot_init(hLayer) {
	var ds = { 
		"all": { data: all, clickable: true, hoverable: true,
			points: { show: true, radius: 8, fillColor: "rgb(255, 117, 71)"},lines: { show: false }
		} ,
		"all-bg": { data: all, clickable: false, hoverable: false,
			points: { show: true, radius: 8, fillColor: "rgba(255, 117, 71, 0.2)"},lines: { show: false }
		} ,
		"berlin": { data: berlin, clickable: true, hoverable: true,
			points: { show: true, radius: 8 },lines: { show: false }
		} ,
		"seoul": { data: seoul, clickable: true, hoverable: true,
			points: { show: true, radius: 8 },lines: { show: false }
		} ,
		"platoon": { data: platoon, clickable: true, hoverable: true,
			points: { show: true, radius:5 },lines: { show: true }
		} ,
		"puf": { data: puf, clickable: true, hoverable: true,
			points: { show: true, radius: 8},lines: { show: true }
		} ,
		"oori": { data: oori, clickable: true, hoverable: true,
			points: { show: true, radius: 8},lines: { show: true }
		} ,
		"YouCrack": { data: YouCrack, clickable: true, hoverable: true,
			points: { show: true, radius: 8},lines: { show: false }
		} ,
		"LiveCrack": { data: LiveCrack, clickable: true, hoverable: true,
			points: { show: true, radius: 8},lines: { show: false }
		} ,
		"anonymous": { data: anonymous, clickable: true, hoverable: true,
			points: { show: true, radius: 8},lines: { show: false }
		}
	};
			
	var data = [];
	if (hLayer && ds[hLayer]) {
		if (hLayer != "all") data.push(ds["all-bg"]);   // "all layer" as background
		data.push(ds[hLayer]);
	}
	flot(data);  // do it..
	$(".tickTitleX, .tickTitleY").show();
}




// ** PLOT THE PLOT **
function flot(dataSets) {
	plot = $.plot($("#placeholder"),
           dataSets,
           { /* selection: { mode: "x" }, */
             grid: { color: "rgb(255,255,255)",borderWidth: 0,tickColor: "rgba(127, 185, 135,0.3)" ,
			 hoverable: true, clickable: true },
             yaxis: { min: 0.5, max: 5.5, tickSize: 1, tickFormatter: formatTickY }, 
             xaxis: { min: 0.5, max: 12.5, tickFormatter: formatTickX },
			 colors: ["rgba(125, 125, 125, 0.8)","rgba(255, 117, 71, 0.9)"],
			 crosshair: { mode: "xy", color: "rgba(248, 128, 23,0.4)" }
             });
}




// ********* Tick functions : START ********

// ** hover actions for tickLabel **

$(".tickTitleX, .tickTitleY ").live("mouseover",function() {
	showTooltip(($(this).offset()).left+20,($(this).offset()).top+20,$(this).siblings(".tickDescription").html());
});
$(".tickTitleX, .tickTitleY").live("mouseout",function() {	$("#tooltip").remove();});


// method to show tick by X,Y
function showTick(x, y){
	$(".titleHighlight").removeClass("titleHighlight"); //reset
	$("#axis_x_"+x+",#axis_y_"+y).next().addClass("titleHighlight");
}


// ** format ticks **
function formatTickX(val,axis) {
	return "<span class='tickDisplay' id='axis_x_"+val+"'>"+val+"</span><span class='tickTitleX'>"+getAxisTitle("x",val)+"</span><span class='tickDescription'>"+getAxisDescription("x",val)+"</span>"; }
function formatTickY(val,axis) {
	return "<span class='tickDisplay' id='axis_y_"+val+"'>"+val+"</span><span class='tickTitleY'>"+getAxisTitle("y",val)+"</span><span class='tickDescription'>"+getAxisDescription("y",val)+"</span>"; }

//ticks: [[0, ""], [1, "A"], [2, "B"], [3, "C"], [4, "D"], [5, "E"]]

// ** manage tick title and descriptions **  (this section to be fixed in phase2)
var xTitle=new Array("Naive","Subversive","Informal","Statement","Action","Intervention","Collective <br/>intelligence","Urban <br/>pioneers","Culturpreneurs","&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Manifesto","Lifestyle","Web 3.0");  // PHASE2 FEATURE FIX
var yTitle=new Array("Urban <br/>Screens","Event","Structure","Product","Non-material"); // PHASE2 FEATURE FIX
function getAxisTitle(ax,i) {
	if (ax=="x"){ return xTitle[i-1]; }
	if (ax=="y"){ return yTitle[i-1]; }	
}
var xDescription=new Array(   // PHASE2 FEATURE FIX
	"<b>Naive</b>: unintentional , teen-subculture, crappy ",
	"<b>Subversive</b>: vandalism, confusion, anarchism, squat...",
	"<b>Informal</b>: survival, informal creativity, informal markets, informal education...",
	"<b>Statement</b>: semiotic, claim for public, individualistic...",
	"<b>Action</b>: civil society initiatives, political & environmental, grouping...",
	"<b>Intervention</b>: performing, result-based, educational capacity, solo...",
	"<b>Collective intelligence</b>: smart-flesh mobs, critical mass, reclaim the streets...",
	"<b>Urban pioneers</b>: residual as source, theoretical background, moderation...",
	"<b>Culturpreneurs</b>: established in formal sphere, gentrifies...",
	"<b>Manifesto</b>: political claim, institutionalization, investors without capital...",
	"<b>Lifestyle</b>: self-branding, trendsetters, myth, influencing brands...",
	"<b>Web 3.0</b>: post social-networking, jobs creation, operative web-platforms..."
	); 
var yDescription=new Array(   // PHASE2 FEATURE FIX
	"<b>Urban Screens</b>: surface based cracks / 2D; graffiti, stencils, hacked billboards, informal communication boards...",
	"<b>Event</b>: space reprogramming / ephemeral ; public art, performing arts, sport",
	"<b>Structure</b>: built / 3D; temporary architecture, mobile (infra)structure, parasites, micro public space...",
	"<b>Product</b>: manufactured / repetition; gadget, fashion, furniture, movie, monument...",
	"<b>Non-material</b>: new media; IT solutions, hacking, sound-light, web, communication strategy, behavioral tactics..."
	); 
function getAxisDescription(ax,i) {
	if (ax=="x"){ return xDescription[i-1]; }
	if (ax=="y"){ return yDescription[i-1]; }	
}

// ********* Tick functions : END ********


// ** hover tooltip **
function showTooltip(x, y, contents) {
// can be replaced later with a cooler plugin..
	$('<div id="tooltip">' + contents + '</div>').css( {
		position: 'absolute',
		display: 'none',
		top: y + 2,
		left: x - 20,
		//border: '1px solid #666',
		padding: '3px',
		'font-size': '14px',
		//'text-transform': 'uppercase',
		color: '#000',
		'background-color': '#666',
		opacity: 0.9,
		'z-index': '11'
	}).appendTo("body").slideDown(150);
}






// ************************************************************************ 
// *******************            ITEMS LIST            *******************
// ************************************************************************ 


// ** ITEMS BROWSER ***
//$(document).ready(function () {
// called after ajax request
function crackingItems_init() {

	//$.scrollTo(0);   // reset window scroll

	// build right-side ItemBrowser UL
	$("div.crackingItem").each( function() {
		var mini = $(this).children(".itemBrowserPiece").html();
		$("#itemsBrowser .appNavigation").append(mini);
	});

	/* cufon */
	Cufon.replace('.crackingItem span.title, #itemsBrowser span.title, .crackingItem span.info, #itemsBrowser span.info, .crackingItem span.crackingTags, .crackingItem span.moreInfo, .crackingItem a.projectLink, .crackingItem a.whoLink', {hover: true});


/*   [[ DISABLED ]]
	// sync grid ticks with selected item
	$('#itemsBrowser .appNavigation a').live("click",function(){
		var gridLoc = $(".gridLoc",this).text().split(',');;
		showTick(gridLoc[0],gridLoc[1]);
//		plot.highlight();
	});
*/
	
	// *** Large image view ***
	$("a[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'fast', /* fast/slow/normal */
		padding: 30, /* padding for each side of the picture */
		opacity: 0.35, /* Value betwee 0 and 1 */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'dark_rounded' /* light_rounded / dark_rounded / light_square / dark_square */
		// callback: function(){}
	});
	
	$("a.cracking_image").hover(
	function(){
		$(this).parent().addClass("watermark");
		$("img",this).addClass("watermark");
	},
	function(){
		$(this).parent().removeClass("watermark");
		$("img",this).removeClass("watermark");	
	});



	
	// ****** Left side - ITEMS SLIDER *****
	
	/*
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (!badBrowser) {
	*/

	/*  OORI - DISABLE SLIDER ** START 

	var $panels = $('#slider div.crackingItem');
	var $container = $('#slider .scrollContainer');
	var horizontal = true; // if false, we'll float all the panels left and fix the width of the container
	if (horizontal) {
	  $panels.css({
		'float' : 'left',
		'position' : 'relative' // IE fix to ensure overflow is hidden
	  });
	  $container.css('width', $panels[0].offsetWidth * $panels.length);   // calculate a new width for the container (so it holds all panels)
	}

	// collect the scroll object, at the same time apply the hidden overflow
	// to remove the default scrollbars that will appear
	var $scroll = $('#slider .scroll').css('overflow', 'hidden');

	// handle nav selection
	function selectNav() {
	  $(this)
		.parents('ul:first')
		  .find('a')
			.removeClass('selected')
		  .end()
		.end()
		.addClass('selected');

		showSelectedTickLabel();  // show selected tick label
	}

	$('#itemsBrowser .appNavigation').find('a').click(selectNav);


	// go find the navigation link that has this target and select the nav
	function triggerBefore(event, targetEl, scrolledEl, itemsColl, pos) {
		var el = $('#itemsBrowser .appNavigation').find('a[href$="#' + targetEl.id + '"]').get(0);
		$('#itemsBrowser').scrollTo(el,500);
		selectNav.call(el);
	}


	// by default: click on first item, after short delay
	setTimeout("$('#itemsBrowser .appNavigation a:first').click()",400);


	// offset is used to move to *exactly* the right place, since I'm using
	// padding on my example, I need to subtract the amount of padding to
	// the offset.  Try removing this to get a good idea of the effect
	var offset = parseInt((horizontal ? 
	  $container.css('paddingTop') : 
	  $container.css('paddingLeft')) 
	  || 0) * -1;


	var scrollOptions = {
	  target: $scroll, // the element that has the overflow
	  items: $panels,
	  navigation: '#itemsBrowser .appNavigation a',
	  //prev: 'img.left',
	  //next: 'img.right',
	  axis: 'xy', // allow the scroll effect to run both directions
	  //onAfter: trigger, // our final callback
	  onBefore: triggerBefore,
	  offset: offset,
	  duration: 500,
	  easing: 'swing'
	};

	// apply serialScroll to the slider - we chose this plugin because it 
	// supports// the indexed next and previous scroll along with hooking 
	// in to our navigation.
	$('#slider').serialScroll(scrollOptions);

	// now apply localScroll to hook any other arbitrary links to trigger 
	// the effect
	$.localScroll(scrollOptions);

	// finally, if the URL has a hash, move the slider in to position, 
	// setting the duration to 1 because I don't want it to scroll in the
	// very first page load.  We don't always need this, but it ensures
	// the positioning is absolutely spot on when the pages loads.
	
	scrollOptions.duration = 1;
	$.localScroll.hash(scrollOptions);

	// scroll buttons trigger event 
	$(".scrollButtons.left").click(function() {
		$("#slider .scrollContainer").trigger( 'prev' );
	});
	$(".scrollButtons.right").click(function() {
		$("#slider .scrollContainer").trigger( 'next' );
	});

	$(".scrollButtons").hover(function() {$(this).animate({opacity:1},200)},function() {$(this).animate({opacity:0.6},500)});
	
	
	// ******** END: SLIDER ****
	

  OORI - DISABLE SLIDER ** END */ 
	
	
	
// }  //close badBrowser

}   // close function

// });  // close document.ready


