/*
*	BBC Language Development
*	AllofUs
*	Written by Nic Mulvaney (nic@allofus.com)
*
*/


/* Settings
*************************/

var debugMode = false; // allows manual positioning of overlays which output x/y coordinates into console. Also allows debug messages in console
var onlineMode = true; // Set to false will use yahoo pipes to load RSS for testing purposes
var waitBeforeIdleState = 1000; // 0 Seconds before the idle state kicks in when entering the page.
var idleStatePause = 3000; // 2 Seconds in between showing heatmaps in idle state
var idleStateReKickIn = 0; // 20 Seconds - Will kick back in if hovering away from the menu (set 0 to ignore);
var defaultMessage = ""; // Default message when there is no image (individual messages can be added: see overlayData below)
var randomIdleState = true; // if false, shows heatmaps in order
var testFeed = false; // set this to an rss reference to load a local testFeed e.g. var testFeed = "rss/burmese.xml";
var allowStickyPanels = true; // Do not change (dormant)
var animateVertical = 0; // Do not change (dormant)
var closePanelAfter = 7000; // Close the panel after 7 seconds on not interacting
var reInstateIdleState = false;
var rolloverSpeed = 400; // speed of rollover in milliseconds
var preLoadMaps = true; // Preload Maps
var preLoadBrands = true; // Preload Brands

var overlayData = 	[ 

		// x, y = coordinates of panel
		// r = right to left languages
		// sp = special formatting for the "hello" section (now replaced with images but left here in case we need it)
		// message = a message when there is no image
		
		{ref:'albanian',x:367,y:122, message:""},
		{ref:'arabic',x:36,y:126,r:1},
		{ref:'azeri',x:99,y:119},
		{ref:'bangla',x:182,y:136,sp:1},
		{ref:'burmese',x:201,y:154},
		{ref:'caribbean',x:219,y:130},
		{ref:'chinese',x:182,y:132,sp:1},
		{ref:'french',x:365,y:19},
		{ref:'hausa',x:366,y:130},
		{ref:'hindi',x:158,y:134},
		{ref:'indonesian',x:232,y:124},
		{ref:'kinyarwanda',x:65,y:159},
		{ref:'kirundi',x:80,y:58},
		{ref:'kyrgyz',x:136,y:89},
		{ref:'macedonian',x:64,y:150},
		{ref:'nepali',x:163,y:130},
		{ref:'pashto',x:124,y:81,r:1,sp:1},
		{ref:'persian',x:118,y:120,r:1},
		{ref:'portuguese',x:289,y:166},
		{ref:'portugueseafrica',x:357,y:14},
		{ref:'russian',x:106,y:164},
		{ref:'serbian',x:335,y:163},
		{ref:'sinhala',x:174,y:152},
		{ref:'somali',x:95,y:160},
		{ref:'spanish',x:245,y:172},
		{ref:'swahili',x:83,y:160},
		{ref:'tamil',x:159,y:144},
		{ref:'turkish',x:84,y:169},
		{ref:'ukrainian',x:253,y:154},
		{ref:'urdu',x:145,y:159,r:1},
		{ref:'uzbek',x:306,y:170},
		{ref:'vietnamese',x:234,y:121},
	];


var rssData = [
		{ref:'albanian',url:'http://www.bbc.co.uk/albanian/index.xml'},
		{ref:'arabic',url:'http://www.bbc.co.uk/arabic/index.xml'},
		{ref:'azeri',url:'http://www.bbc.co.uk/azeri/index.xml'},
		{ref:'bangla',url:'http://www.bbc.co.uk/bengali/index.xml'},
		{ref:'burmese',url:'http://www.bbc.co.uk/myanmar/index.xml'},
		{ref:'caribbean',url:'http://www.bbc.co.uk/caribbean/index.xml'},
		{ref:'chinese',url:'http://www.bbc.co.uk/zhongwen/simp/index.xml'},
		{ref:'french',url:'http://www.bbc.co.uk/french/index.xml'},
		{ref:'hausa',url:'http://www.bbc.co.uk/hausa/index.xml'},
		{ref:'hindi',url:'http://www.bbc.co.uk/hindi/index.xml'},
		{ref:'indonesian',url:'http://www.bbc.co.uk/indonesian/index.xml'},
		{ref:'kinyarwanda',url:'http://www.bbc.co.uk/greatlakes/index.xml'},
		{ref:'kirundi',url:'http://www.bbc.co.uk/greatlakes/index.xml'},
		{ref:'kyrgyz',url:'http://www.bbc.co.uk/kyrgyz/index.xml'},
		{ref:'macedonian',url:'http://www.bbc.co.uk/macedonian/index.xml'},
		{ref:'nepali',url:'http://www.bbc.co.uk/nepali/index.xml'},
		{ref:'pashto',url:'http://www.bbc.co.uk/pashto/index.xml'},
		{ref:'persian',url:'http://www.bbc.co.uk/persian/index.xml'},
		{ref:'portuguese',url:'http://www.bbc.co.uk/portuguese/index.xml'},
		{ref:'portugueseafrica',url:'http://www.bbc.co.uk/portugueseafrica/index.xml'},
		{ref:'russian',url:'http://www.bbc.co.uk/russian/index.xml'},
		{ref:'serbian',url:'http://www.bbc.co.uk/serbian/index.xml'},
		{ref:'sinhala',url:'http://www.bbc.co.uk/sinhala/index.xml'},
		{ref:'somali',url:'http://www.bbc.co.uk/somali/index.xml'},
		{ref:'spanish',url:'http://www.bbc.co.uk/mundo/index.xml'},
		{ref:'swahili',url:'http://www.bbc.co.uk/swahili/index.xml'},
		{ref:'tamil',url:'http://www.bbc.co.uk/tamil/index.xml'},
		{ref:'turkish',url:'http://www.bbc.co.uk/turkce/index.xml'},
		{ref:'ukrainian',url:'http://www.bbc.co.uk/ukrainian/index.xml'},
		{ref:'urdu',url:'http://www.bbc.co.uk/urdu/index.xml'},
		{ref:'uzbek',url:'http://www.bbc.co.uk/uzbek/index.xml'},
		{ref:'vietnamese',url:'http://www.bbc.co.uk/vietnamese/index.xml'}
	];



/* END OF SETTINGS (DO NOT EDIT BELOW )*************************/





var preloadImageArr = ['images/panel/panel_1.png','images/panel/panel_2.png','images/panel/panel_3.png','images/panel/panel_4.png','images/panel/panel_inner.gif'];

// Defaults

var idleTime;
var firstIdleWait;
var delay;
var link;
var activeButton = {id:new Object(),obj:null};
var idleStateIndex = 0;
var idleRunning = false;
var uniqueRnd = [];
var realHover = false;

function getRandom(){
	if(uniqueRnd.length==0){
		for(var i = 0 ; i < overlayData.length ; i++){
			uniqueRnd.push(i);
		}
	}
	var rnd =  Math.round(Math.random()*uniqueRnd.length-1);
	var num = uniqueRnd[rnd];
	uniqueRnd.splice(rnd,1);
	return num;
	
}
/* Jquery Setup
*************************/

$(document).ready(function(){
	init();
});


function browserCheck(){
	ie = false;
	if ($.browser.msie){
		ie = Math.round($.browser.version);
	} 
	
}

function preloadImages(){
	if(preLoadMaps){
		for(var i in overlayData){
			var img = "images/heatmaps/"+overlayData[i].ref+".gif";
			preloadImageArr.push(img);
		}
	}
	if(preLoadBrands){
		for(var i in overlayData){
			var img = "images/brands/"+overlayData[i].ref+".png";
			preloadImageArr.push(img);
		}
	}
	$.preloadImages(preloadImageArr);
}

function idleState(begin){	
	$.log("idlestate:"+begin);
	if(begin){
			idleRunning = true;
			if(randomIdleState){
				idleStateIndex = getRandom();//Math.round(Math.random()*overlayData.length);
			}
			
			link = $("#language-picker li a:eq("+idleStateIndex+")");
			link.trigger('mouseenter');
			
	}else{
		if(idleRunning){
			clearTimeout(delay);
			link.removeClass("hit");
			activeButton = {id:new Object(),obj:null};
			$("#heatmap").stop().fadeTo(100,0);
			idleRunning = false;
		}
		// CLEAR IDLE STATE
	}
}

function idlePause(){
	$.log("Begin idlePause for "+idleStatePause+" milliseconds");
	$("#heatmap").fadeTo(idleStatePause, 1, function(){
		idleStateIndex++;
		idleState(true);
	});
	
}

/* Load the service matrix
*************************/
function loadServices(){
	$.log("Loading: lib/app/services.xml");
	$.ajax({
	  type: "GET",
	  url: "lib/app/services.xml",
	  dataType: "xml",
	  success: function(xml){
	  		$(xml).find('RECORD').each(function(){
	  			var data = getOverlayData($(this).find('language').text());
	  			if(data){
		  			$(this).children().each(function(){
		  				var t = $(this)[0].tagName.toLowerCase();
		  				data[t] = $(this).text();
		  			});
	  			}
	  		});	
   	  },
   	  error: function (XMLHttpRequest, textStatus, errorThrown){
	  		return _obj.each(function() {
				 $.error(XMLHttpRequest.statusText+" : "+textStatus);
			});
   	  }

	});
	// Add urls to data set
	$("#language-picker li a").each(function(){
		var url = $(this).attr("href").split("http://www.")[1];
		overlayData[$("#language-picker li a").index($(this))].url = url;
	});
	
	// Add feeds into data set
	for(var i in rssData){
		for(var a in overlayData){
			if(overlayData[a].ref == rssData[i].ref){
				overlayData[a].rssref = rssData[i].url;
				break;
			}
		}
	}
	
}
function getOverlayData(value){
	for(var a in overlayData){
		if(overlayData[a].ref==value){
			return overlayData[a];
		}
	}
}


/* Jquery Main Functions
*************************/


function init(){

	browserCheck();
	preloadImages();
	loadServices();

	
	$("#language-picker li a").mouseover(function(event){
		idleState(false);
		//var realHover = true;
	});	
	
	
	$("#language-picker li a").hover(function(){
	
		$.log("hover");
		clearTimeout(firstIdleWait);
		
		activeButton_temp = {id:$("#language-picker li a").index(this), obj:$(this)};

		if(allowStickyPanels && (activeButton_temp.id != activeButton.id || idleRunning)){
			delay = setTimeout("doRollOver(activeButton_temp);",rolloverSpeed);
		}
		
	},function(){

		$("#language-picker li a").removeClass("hit");
		
		if(activeButton.obj!=null){
			activeButton.obj.addClass("hit");
		}
		
		if(allowStickyPanels){
			clearTimeout(delay);
		}
		clearTimeout(idleTime);
		if(idleStateReKickIn){
		idleTime = setTimeout("idleState(true);",idleStateReKickIn);
		}
		
	});
	
	
	
	$("#language-picker li a").mousedown(function(event){
		if(event.preventDefault)
		{
		event.preventDefault();
		}
	});
	
	if(debugMode){
		$("#panels").mousedown(function(){
			$(this).mousemove(function(e){ 
				var x = e.pageX - $(this).offset().left;
				var y = e.pageY - $(this).offset().top;
				$("#overlayBox").css({ top:y, left:x});
				$("#panel-content").css({ top:y+18, left:x+18});
			});
		});
		$("#panels").mouseup(function(e){
				var x = e.pageX - $(this).offset().left;
				var y = e.pageY - $(this).offset().top;
				$.log("{x:"+x+","+"y:"+y+"},");
				$(this).unbind("mousemove");
		});
	}
	
	$('#language-picker').disableTextSelect();
	firstIdleWait = setTimeout("idleState(true);",waitBeforeIdleState);
			
}


startTimeout = false;

function doRollOver(obj,close){
	sLoad = false;
	
	$("#panel-content, #menu").unbind("mouseenter").unbind("mouseleave");
	$("#panel-content, #menu").bind("mouseenter",function(){
		startTimeout = false;
	}).bind("mouseleave",function(){
		startTimeout = true;
	});
	
	$.log("doRollOver()");
	
	if(isSet("req")){
		req.abort();
	}

	
	var positions = getPositions();

	if(activeButton.obj){
		activeButton.obj.removeClass("hit");
	}

	activeButton = getLink(obj.id);
	
	if(idleRunning){
		activeButton.obj.addClass("hit");
	}
	$("#overlay_expand").stop();
	$("#panel-content").stop().empty();
	$("#panel-headline").stop();
	$("#panel-headline img").stop();
	
	$.log("start overlay animation... out");
	
	$("#overlayBox").stop().fadeTo(200, 0, function(){
			$("#panels").empty();
	});
	$.log("start heatmap animation... in");
	$.log( "heatmap:" + $("#heatmap").css("opacity") );
	//$("#heatmap").css("opacity","0").show();
	
	if(close){
		$("#heatmap").stop().fadeTo(200,0);
		activeButton = {id:new Object(),obj:null};
		if(reInstateIdleState){
			firstIdleWait = setTimeout("idleState(true);",2000);
		}
	}else{
		$("#heatmap").stop().fadeTo(200,0,triggerOverlay);
	}
}


function getPositions(){
	var id = activeButton.id;
	if(overlayData[id]){
		return overlayData[id];
	}else{
		$.error("No coordinates for this panel ("+id+")");
		return {x:0,y:0};
	}
}


function triggerOverlay(){
	$.log("triggerOverlay()");
	
	// LOAD THE HEATMAP...

	var imgref = "images/heatmaps/"+overlayData[activeButton.id].ref+".gif";
	sLoad = true;
	$("#heatmap").image(imgref,function(){
		if(idleRunning){
			var func = idlePause;
		}else{
			var func = createOverlayBox;
		}
		if(sLoad){
			$.log("Show heatmap...");
			$("#heatmap").show().fadeTo(300,1,func);
			sLoad = false;
		}
		
	},function(){$.error("Problem loading brand image")});
}

function getLink(id){
	return  {id:id, obj:$("#language-picker li a:eq("+id+")")};
}



function createIEImg(srcs, sty){
	if(!sty){
	var sty='';
	}
	var str = '<img src="' + srcs + '" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"/' +srcs+ '\",sizingMethod=\"scale\");" class="' +sty+ '" />';
	return str;
}


function createOverlayBox(){

	var positions = getPositions();
	
	// FIX FOR IE PNG LOADER
	// IF IE7 USE AplhaImageLoader on an img tag, if not, just use a background image
	$("#panels").hide();
	
	if(ie>=7){
	
	
		$("#panels").append('<div id="overlayBox">'+createIEImg("images/panel/panel_1.png")+'<div id="overlay_expand">'+createIEImg("images/panel/panel_2.png", "tall")+'<img src="images/panel/panel_inner.gif" class="tall" style="width:240px !important;"/>'+createIEImg("images/panel/panel_3.png","tall")+'</div>'+createIEImg("images/panel/panel_4.png")+'</div>');

	}else if(ie==6){
	
		$("#panels").append('<div id="overlayBox"><img src="images/panel/panel_1.png"/><div id="overlay_expand"><img src="images/panel/panel_2.png"  class="tall"/><img src="images/panel/panel_inner.gif" class="tall" style="width:240px !important;"/><img src="images/panel/panel_3.png" class="tall"/></div><img src="images/panel/panel_4.png"/></div>');
		// But pngs with alpha don't work on IE6, so fix that...
		
		$('#overlayBox img').css("opacity","1");
		DD_belatedPNG.fix('#overlayBox img');
		
	}else{
	
		$("#panels").append('<div id="overlayBox"><img src="images/panel/panel_1.png"/><div id="overlay_expand"><img src="images/panel/panel_2.png"  class="tall"/><img src="images/panel/panel_inner.gif" class="tall" style="width:240px !important;"/><img src="images/panel/panel_3.png" class="tall"/></div><img src="images/panel/panel_4.png"/></div>');
			
	}


	$("#panels").append("<div id='panel-content'><div id='panel-title'></div><div id='panel-hello'></div><div id='panel-headline'></div><div id='panel-icons'></div></div>");

	// Add unique font stylings
	$("#panel-headline").addClass(positions.ref);
	
	// Position the overlay
	var overlayCSS = {
        'position':'absolute',
        'top':positions.y+animateVertical,
        'left':positions.x
    }
    
    $("#overlayBox").hide().css(overlayCSS);
    $("#panels").show();
    
	var overlayCSS = {
        'position':'absolute',
        'top': positions.y+animateVertical+18, //100+18,//
        'left': positions.x+18 //100+17//
    }
    $("#panel-content").css(overlayCSS);
    //$("#panel-content").css("height","178px");
    
	var imgref = "images/brands/"+positions.ref+".png";
	
	sLoad = true;
	$.log("---- Load brand image");
	
	$("#panel-title").image(imgref,function(){
	
		if(sLoad){
			sLoad = false;
			$.log("Show panel content");
			$("#panel-title").wrapInner("<a href='http://www."+positions.url+"'></a>");
			
			var ht = $("#panel-title").height();
			var expandHeight = 30+(ht-106)+40;
			$("#overlay_expand").css("height",expandHeight);
			
			var add = 0;
			if(ie==6){
				add = -10;
			}
			$("#panel-content").css("height",$("#overlayBox").height()-36+add);
			
			// GIVE AREAS ACTIONS TO CLOSE THE PANELS
			$("#panel-content, #menu").unbind("mouseenter").unbind("mouseleave");
			$("#panel-content, #menu").bind("mouseenter",function(){
				$.log("clear");
				startTimeout = false;
				if(isSet("closeIdleWait")){
					clearTimeout(closeIdleWait);
				}
			}).bind("mouseleave",function(){
				startTimeout = true;
				initiateListen();
			});
			
			// Animate the overlay...
			$.log("---- Start fade");
			$("#overlayBox").stop().fadeTo(0,0,function(){
				$("#overlayBox").show().fadeTo(300, 1, function(){
	
				    $("#panel-title").fadeIn("fast");
				    $("#panel-icons").hide().html("<a class='site-link' href='http://www."+positions.url+"'></a><div class='linebreak'></div>"+getServiceIcons(positions)).show();
				    
				    // Right align required text
				    if(positions.r){
				    	$("#panel-icons").addClass('righty');
				    	$("#panel-headline").addClass('righty');
				    }
					
					var url = positions.rssref;
					if(testFeed){
						url = testFeed;
					}
					$("#panel-headline").BBCHeadline({url:url,intro:positions.message});
		
				});
			});
		};
	
	
		
	},function(){$.error("Problem loading brand image")});
	
	
}

function expandPanel(){
	if(sLoad){
		var title_ht = $("#panel-title").height();
		var ht = $("#panel-headline").height()+1;
		
		// Fix the underline and retain the hidden overflow
		$("#panel-headline").height(ht);
		
		var newheight = ht+(title_ht-106)+30;
		
		var panelht = $("#overlayBox").height();
		var exh = $("#overlay_expand").height();
		
		$("#overlay_expand").animate({"height":newheight},300);
		$("#panel-content").animate({"height":panelht-36-exh+newheight},300,function(){
		

			
			if(ie==6){
				$("#panel-headline").show();
				$("#panel-headline img").hide().fadeIn("fast",initiateListen);
			}else{
				$("#panel-headline").fadeIn("fast",initiateListen);
			}
		});
		sLoad = false;
	}
}

function initiateListen(){
	$.log("initiateListen");
	if(isSet("closeIdleWait")){
		clearTimeout(closeIdleWait);
	}
	if(startTimeout){
		$.log("GO FOR IT");
		closeIdleWait = setTimeout("doRollOver(activeButton, true);",closePanelAfter);
	}
}


/* Format the icons for the panel
*************************/

function getServiceIcons(data){
	var str = "";
	var types = ["email","mobile","rss","podcast","radio","tv","video"];
	for(var i in types){
		if(data[types[i]]==1){
			str+="<div class='icon' style='background-position:"+(-30*i)+"px 0px;'></div>";
		}
	}
	return str;
}


/* Jquery Functions
*************************/



jQuery.preloadImages = function(arr)
{
  for(var i = 0; i<arr.length; i++)
  {
    jQuery("<img>").attr("src", arr[i]);
  }
}

// Debugging

jQuery.log = function(message) {
  if(isSet("console") && debugMode) {
     console.log(""+message);
  }
};

// Debugging Error
jQuery.error = function(message) {
  if(isSet("console") && debugMode) {
     console.log(""+message);
  }
};



function isSet(variable_name)
{
try
{
if (typeof(eval(variable_name)) != "undefined")
if (eval(variable_name) != null)
return true;
} catch(e) { }
return false;
}


