// common.js - Common non sport/site specific js funtions in here please

// global variables:
var loadingAni = "<img src='/Images/livescores/common/ajax-loader.gif' alt='loading' />";

/******************************************************************************************************************************
	
	Replicates the string that the flash produces so we hit the same cached files 
	Allows different options so that we can be more/less specific
	
	(dy) DDMMYYYY_H** 1592008_1* ... H* being the first half or second half of the day (1 - 12 = 0, 12 - 23 = 1)
	(mi) DDMMYYYY_HH24Mi_S* 1592008_1611_1 ... * S being the first half or second half of the minute (0-30 = 0, 30-59 = 1)
	
******************************************************************************************************************************/
function cacheBuster(lim) {
	
	currentTime = new Date();
	cBust = "";
	cBust += currentTime.getDate();	
	// for some reason getMonth returns one less (8 for september, so add 1 on to it).
	cBust += currentTime.getMonth()+1;
	cBust += currentTime.getFullYear();
	cBust += "_";
	
	/*** for a half day option - not required at the mo
	if (currentTime.getHours() <= 12) {	
		halfDay = "0";
	} else {
		halfDay = "1";			
	}
	cBust += "_" + halfDay;	
	***/
	
	if (lim == "sec300") {
		// refresh 5 minutes - will output in the format: YYYYMMDD_HH24_XX
		// XX being 0,5,10,15,20 etc		
		cBust += currentTime.getHours();		
		var currMin = currentTime.getMinutes();
		if (currMin < 5) {
			cBust += "_0";
		} else if (currMin >= 5 && currMin < 10) {
			cBust += "_5";
		} else if (currMin >= 10 && currMin < 15) {
			cBust += "_10";
		} else if (currMin >= 15 && currMin < 20) {
			cBust += "_15";
		} else if (currMin >= 20 && currMin < 25) {
			cBust += "_20";
		} else if (currMin >= 25 && currMin < 30) {
			cBust += "_25";
		} else if (currMin >= 30 && currMin < 35) {
			cBust += "_30";
		} else if (currMin >= 35 && currMin < 40) {
			cBust += "_35";
		} else if (currMin >= 40 && currMin < 45) {
			cBust += "_40";
		} else if (currMin >= 45 && currMin < 50) {
			cBust += "_45";			
		} else if (currMin >= 50 && currMin < 55) {
			cBust += "_50";
		} else {
			cBust += "_55";
		}
	} else if (lim == "sec60") {
		// refresh 1 minute			
		cBust += currentTime.getHours();
		cBust += currentTime.getMinutes();
	} else if (lim == "sec30") {
		// refresh 30 seconds
		cBust += currentTime.getHours();
		cBust += currentTime.getMinutes();
		if (currentTime.getSeconds() <= 30) {
			halfMin = "0";
		} else {
			halfMin = "1";
		}
		cBust += "_" + halfMin;
	} else if (lim == "sec15") {
		// refresh 15 seconds
		cBust += currentTime.getHours();
		cBust += currentTime.getMinutes();
		if (currentTime.getSeconds() <= 15) {
			fifteen = "00";
		} else if (currentTime.getSeconds() > 15 && currentTime.getSeconds() <= 30) {
			fifteen = "15";
		} else if (currentTime.getSeconds() > 30 && currentTime.getSeconds() <= 45) {
			fifteen = "30";
		} else {
			fifteen = "45";
		}
		cBust += "_" + fifteen;
	} else {
		// default	
	}
	
	return cBust;
	
}


/**********************************************************************************
	Cookie Stuff
***********************************************************************************/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/********************************************************************************
	Init Tabs
	p = ID of the surrounding div including # e.g. tabs("#tabs-1") 
*********************************************************************************/
function tabs(p) {
		
	   $(p+" .ms-tabs-tablinks li:first").addClass('ms-tabs-on');
	   // add an onClick function to all links in the ul
	   $(p+" .ms-tabs-tablinks li").click(function(){	
		
			// un select all of the tabs
			$(this).parents('.ms-tabs-tablinks').find('li').removeClass('ms-tabs-on');
			// select the clicked tab
			$(this).addClass('ms-tabs-on');
			// get the div we want to show by referencing the href
			var tablink=$(this).find('a').attr('href');
			tablink=tablink.split('#')[1];	
			// hide all divs below "p"
			$(p + " div").hide();
			// now show the clicked tabs content
			$(this).parents('.ms-tabs').find("#"+tablink).show();
			
			// if it's the #tabs-1 that we're doing (live today/my matches/betting) through then add hbx calls
			if (p == "#tabs-1") {				
				myPN  = hbx.pn + " - " + $(this).text();
				myMLC = hbx.mlc + "/" + $(this).text();
				//_hbPageView(myPN, myMLC);				
				//alert("myPN: " + myPN + "\nmyMLC: " + myMLC);
			}
			
			return false;
			
	   });

}

	
/**********************************************************************************
	GALLERY FUNCTIONS:
	
	initGallery - Called in the loadGallery call back function.	
	+ Adds onClicks to the "more galleries" boxes
	+ Takes the first gallery (or match gallery if it can find it in listing 
	  and matchID is set) to be the top gallery.

	loadTopGallery - called from initGallery or onClick
	+ Pulls the gallery xml
	+ creates and array of images/captions 
	+ loads top image and next/prev navigation
	+ drops in html before the "more galleries" area.
	
	naviGallery - called on click of the next/prev buttons
	+ loads in the next/prev image in the array and rewrites caption, x of x text.
	+ uses global variable galleryArr and galleryIndx
***********************************************************************************/
var galleryArr = new Array();
var galleryIndx = 0;

function initGallery() {

	// Add onClicks to "more galleries"
	$(".more-galleries div a").click(function() {
		var gFile = $(this).attr("href").split("#")[1];		
		loadTopGallery(gFile);
		return false;
	});
	
	// the xsl should have a hidden div with the top gallery xml path in it, use it!
	var topGalFile = $("#firstGal").text();	

	if (typeof matchID != "undefined") {		
		// we have a matchID - see if we have a gallery to go with it - can just reference the href to check	
		if ( $(".more-galleries div a[href*='#gallery_match_" + matchID + ".xml']").length > 0) {
		 	// the match exists
			var topGalFile = "gallery_match_" + matchID + ".xml"
		}
	}
	
	// now we've decided which gallery to feature, set it up.
	loadTopGallery(topGalFile);
	
	// HBX Call - for page load
	myPN = hbx.pn + " - Photos";
	myMLC= hbx.mlc + "/Photos";
	_hbPageView(myPN, myMLC);
	
}
function loadTopGallery(gFile) {

	var theURL = xmlPathPrefix + "Editorial/" + gFile + "?cacheBuster=" + cacheBuster("sec300");
	$.get(theURL, {}, function(xmlData) {

		// reset variables/arrays
		galleryIndx = 0;
		galleryArr = new Array();
		
		var gLength = $(xmlData).find('ARTICLE').length;			   
		
		// loop through the xml and create a gallery multi dim array containing path and caption		
		$('ARTICLE',xmlData).each(function(i) {
			
			var imgPath = "http://img.skysports.com" + $(this).find("IMAGE").attr("imgPrefix") + "402x210/" + $(this).find("IMAGE").text();
			var imgCapt = $(this).find("LLSNIPPET").text();	
			if (imgCapt == "") {
				// no caption, just use the title
				imgCapt = $(this).parent().attr("title");
			}
						
			galleryArr[i] = new Array(imgPath,imgCapt);
								 
		});		
		
		// now we have our array, load in the main image...
		gHTML  = '';
		gHTML  = '<h3>' + $(xmlData).find('root').attr("galTitle") + '</h3>';
		gHTML += '<img id="main-img" src="' + galleryArr[0][0] +'" />';
		gHTML += '<div><p class="caption"><span>' + galleryArr[0][1] + '</span></p></div>';
		
		$(".featured-gallery").html(gHTML);
	
		// only setup the navigation etc if we have more than one image...
		var gNav = '<ul id="gallery-nav">';
		if (gLength > 1) {
			gNav += '<li><a href="#prev"><img src="/Images/livescores/common/gallery-prev.gif" alt="Previous" /></a></li>';
			gNav += '<li><span> 1 of ' + gLength + '</span></li>';
			gNav += '<li><a href="#next"><img src="/Images/livescores/common/gallery-next.gif" alt="Next" /></a></li>';			
		} else {
			// only one image - don't need any navigation	
			gNav += '<li>&nbsp;</li><li><span> 1 of ' + gLength + '</span></li><li>&nbsp;</li>';
		}
		gNav += '</ul>';			
			
		// drop in the navigation after the caption span tag
		$(".featured-gallery .caption span").after(gNav);
		
		// add click functions to next/prev links
		$("#gallery-nav a").click(function() {
			var gAction = $(this).attr("href").split("#")[1];
			naviGallery(gAction);
			return false;
		});
		
		// HBX Call - for indiviual gallery
		if (gFile.match("_match_")) {
			// it's a match gallery
			myPN = hbx.pn + " - Live Photos - " + $(xmlData).find("root").attr("galTitle");
			myMLC= hbx.mlc + "/Live Photos";
		} else {
			//  its a story gallery
			myPN = hbx.pn + " - Featured - " + $(xmlData).find("root").attr("galTitle");
			myMLC= hbx.mlc + "/Featured Photos";
		}
		_hbPageView(myPN, myMLC);
		
	}, "xml");						   
	
}
function naviGallery(gAction) {
	if (gAction == "prev") {
		// go back one
		if (galleryIndx == 0) {
			newIndx = $(galleryArr).length - 1;
		} else {
			newIndx = galleryIndx-1;
		}
	} else {
		if (galleryIndx == ($(galleryArr).length - 1)) {
			newIndx = 0;	
		} else {
			newIndx = galleryIndx+1;
		}
	}	
	// update the page with image, caption and navigation
	$(".featured-gallery #main-img").attr("src", galleryArr[newIndx][0]);
	$(".featured-gallery p.caption span").html(galleryArr[newIndx][1]);
	// galleryIndx starts at 0, so need to add 1 to it to make it sensible for the user.
	$("#gallery-nav li span").html((newIndx +1) + " of " + $(galleryArr).length);
	// reset galleryIndx
	galleryIndx = newIndx;
}

/*********************************************************************************************
	A series of load functions used to populate the middle column.
	Uses the jquery.transform.js to render the xsl/xml together.
**********************************************************************************************/

function loadCommentary(f, callHBX) {
	
	// clear the timer in case it's running
	clearInterval(timerMiddle);
	
	// drop in a loading animation
	$("#middle-content").html(loadingAni);
	// deselect all tabs then highlight commentary tab
	$("#tabs-2 li").removeClass("ms-tabs-on");
	$("#tabLive").parents("li").addClass("ms-tabs-on");
	
	if (f) {
		
		var theXML = xmlPathPrefix + f +"?cacheBuster=" + cacheBuster("sec60");
		var theXSL = "xsl/render-commentary.xsl";	
		$("#middle-content").transform({xml: theXML, xsl:theXSL, cache:true, error:xslOnError});
	
		// HBX CALL
		if (callHBX != "undefined" && callHBX != "N") {
			myPN = hbx.pn + " - Commentary";
			myMLC= hbx.mlc + "/Commentary";
			if (callHBX == "AUTO") {
				myPN += " - AUTO RELOAD";	
				myMLC += "/AUTO RELOAD";	
			}
			_hbPageView(myPN, myMLC);		
		}
		
		// set the timer running	
		timerMiddle = setInterval( "loadCommentary('" + f + "','AUTO')" , 60000);
		
	}
	
	
	
}

function loadPhotos() {
	
	// clear the timer in case it's running
	clearInterval(timerMiddle);
	
	// drop in a loading animation
	$("#middle-content").html(loadingAni);
	
	// deselect all tabs then highlight photos tab
	$("#tabs-2 li").removeClass("ms-tabs-on");
	$("#tabPhotos").parent().addClass("ms-tabs-on");
	
	var theXML = xmlPathPrefix + "Editorial/gallery.xml?cacheBuster=" + cacheBuster("sec300");	
	var theXSL = "xsl/render-gallery-list.xsl?v=081009";	
	// with a call back option to apply links to "more galleries".  function is in ../common.js
	$("#middle-content").transform({xml: theXML, xsl:theXSL, cache:true, error:xslOnError, complete:initGallery});
	
}

function loadStory(sPath, callHBX) {
	
	// clear the timer in case it's running
	clearInterval(timerMiddle);
	
	// drop in a loading animation
	$("#middle-content").html(loadingAni);
	
	var theURL = xmlPathPrefix + sPath + "?cacheBuster=" + cacheBuster("sec300");
	$.ajax({
		type: "GET",
		url: theURL,
		dataType: "xml",
		complete: function(response) {
			var xmlDetailData = response.responseXML;
			
			if ($('story',xmlDetailData).length == 0) {
				// no data in the story
				$("#middle-content").html('<div class="tab-content article">Sorry, unable to find story</div>');
				
			} else {
				
				var storyData = '<div class="tab-content article">';
				storyData += '<h2>' + $(xmlDetailData).find("title").text() + '</h2>';
				
				if ($(xmlDetailData).find("image").text()) {
				
					storyData += '<div class="article-pic">';
					storyData += '<img src="http://img.skysports.com' + $(xmlDetailData).find("image").attr("imgPrefix") + '402x210/' + $(xmlDetailData).find("image").text() + '" alt="story image" />';
				
					if ($(xmlDetailData).find("imageCaption").text()) {
						storyData += '<div><p class="caption">' + $(xmlDetailData).find("imageCaption").text() + '</p></div>';
					}
					
					storyData += '</div>';
				}
				
				storyData += '<p><b>' + $(xmlDetailData).find("abstract").text() + '</b></p>';	
				storyData += $(xmlDetailData).find("body").text();
				storyData += '</div>';
				
				$("#middle-content").html(storyData);

				// take the tab name and the title of the story i.e. Reports - United 'embarrassed' by Hoops
				myPN  = hbx.pn + " - " + $("#tabs-2 .ms-tabs-tablinks .ms-tabs-on a").html() + " - Story - " + $("#middle-content .tab-content h2").html();
				myMLC = hbx.mlc +"/" + $("#tabs-2 .ms-tabs-tablinks .ms-tabs-on a").html() + "/Story";
				_hbPageView(myPN, myMLC);
				
			}//end story check
		}// end complete function
			
	});// end .ajax	
	
}


/********************************************************************************
	XSL Transform error handeling functions
*********************************************************************************/
function xslOnError(html,xsl,xml,obj,ex) {
	
	//alert("Error: " + ex.message);	
	// clear the timer - there's been and error
	clearInterval(timerMiddle);
	
}

function xslOnSuccess(callHBX) {
	// on successful rendering of xsl - call a hbx page view
}


/*
 * jQuery jclock - Clock plugin - v 0.2.1
 * http://plugins.jquery.com/project/jclock
 *
 * Copyright (c) 2007-2008 Doug Sparling <http://www.dougsparling.com>
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */
(function($) {

  $.fn.jclock = function(options) {
    var version = '0.2.1';

    // options
    var opts = $.extend({}, $.fn.jclock.defaults, options);
         
    return this.each(function() {
      $this = $(this);
      $this.timerID = null;
      $this.running = false;

      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

      $this.timeNotation = o.timeNotation;
      $this.am_pm = o.am_pm;
      $this.utc = o.utc;
      $this.utc_offset = o.utc_offset;

      $this.css({
        fontFamily: o.fontFamily,
        fontSize: o.fontSize,
        backgroundColor: o.background,
        color: o.foreground
      });

      $.fn.jclock.startClock($this);

    });
  };
       
  $.fn.jclock.startClock = function(el) {
    $.fn.jclock.stopClock(el);
    $.fn.jclock.displayTime(el);
  }
  $.fn.jclock.stopClock = function(el) {
    if(el.running) {
      clearTimeout(el.timerID);
    }
    el.running = false;
  }
  $.fn.jclock.displayTime = function(el) {
    var time = $.fn.jclock.getTime(el);
    el.html(time);
    el.timerID = setTimeout(function(){$.fn.jclock.displayTime(el)},1000);
  }
  $.fn.jclock.getTime = function(el) {
    var now = new Date();
    var hours, minutes, seconds;

    if(el.utc == true) {
      if(el.utc_offset != 0) {
        now.setUTCHours(now.getUTCHours()+el.utc_offset);
      }
      hours = now.getUTCHours();
      minutes = now.getUTCMinutes();
      seconds = now.getUTCSeconds();
    } else {
      hours = now.getHours();
      minutes = now.getMinutes();
      seconds = now.getSeconds();
    }

    var am_pm_text = '';
    (hours >= 12) ? am_pm_text = " P.M." : am_pm_text = " A.M.";

    if (el.timeNotation == '12h') {
      hours = ((hours > 12) ? hours - 12 : hours);
    } else {
      hours   = ((hours <  10) ? "0" : "") + hours;
    }

    minutes = ((minutes <  10) ? "0" : "") + minutes;
    seconds = ((seconds <  10) ? "0" : "") + seconds;

    var timeNow = hours + ":" + minutes + ":" + seconds;
    if ( (el.timeNotation == '12h') && (el.am_pm == true) ) {
     timeNow += am_pm_text;
    }

    return timeNow;
  };
       
  // plugin defaults
  $.fn.jclock.defaults = {
    timeNotation: '24h',
    am_pm: false,
    utc: false,
    fontFamily: '',
    fontSize: '',
    foreground: '',
    background: '',
    utc_offset: 0
  };

})(jQuery);

    $(function($) {
	  var options = {utc: true}
      $('.jclock').jclock();
    });
	
/*
 *
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
$.fn.ToolTip = function(bgcolour, fgcolour)
{
	this.mouseover(
		function(e)
		{
			if((!this.title && !this.alt) && !this.tooltipset) return;
			// get mouse coordinates
			// based on code from http://www.quirksmode.org/js/events_properties.html
			var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
			var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
			mouseX += 10;
			mouseY += 10;
			bgcolour = bgcolour || "#eee";
			fgcolour = fgcolour || "#ddd";
			// if there is no div containing the tooltip
			if(!this.tooltipdiv)
			{
				// create a div and style it
				var div = document.createElement("div");
				this.tooltipdiv = div;
				$(div).css(
				{
					border: "1px outset #ddd",
					padding: "5px 8px",
					backgroundColor: bgcolour,
					color: fgcolour,
					position: "absolute"
				})
				// add the title/alt attribute to it
				.html((this.title || this.alt));
				this.title = "";
				this.alt = "";
				$("body").append(div);
				this.tooltipset = true;
			}
			$(this.tooltipdiv).show().css({left: mouseX + "px", top: mouseY + 3 + "px"});
		}
	).mouseout(
		function()
		{
			if(this.tooltipdiv)
			{
				$(this.tooltipdiv).hide();
			}
		}
	);
	return this;
}

$(".formation a").ToolTip("#000", "#fff");

