/* Standard Javascript functions library for IMG projects
written (unless otherwise stated) and compiled by Niall King */


// library to replace window.onload
// addLoadEvent waits till the whole page has loaded, inluding images, video and so forth.
// addDOMLoadEvent only waits for the DOM to load. 
// Where your script does not need to wait for the layout to complete you can use this to speed things up
// http://simonwillison.net/2004/May/26/addLoadEvent/

function addLoadEvent(func) { 
	var o = window.onload; 
		if (typeof window.onload != 'function') { 
			window.onload = func; 
		} else { 
			window.onload = function() { 
				if (o) { 
				o(); 
			} 
			func(); 
		} 
	} 
} 
 
addDOMLoadEvent=(function(){var e=[],t,s,n,i,o,d=document,w=window,r='readyState',c='onreadystatechange',x=function(){n=1;clearInterval(t);while(i=e.shift())i();if(s)s[c]=''};return function(f){if(n)return f();if(!e[0]){d.addEventListener&&d.addEventListener("DOMContentLoaded",x,false);
/*@cc_on@*/
/*@if(@_win32)
var proto = "src='javascript:void(0)'";
		if (location.protocol == "https:") proto = "src=//0";
		d.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
s=d.getElementById("__ie_onload");
s[c]=function(){
    s[r]=="complete"&&x()
};
/*@end@*/
if(/WebKit/i.test(navigator.userAgent))t=setInterval(function(){/loaded|complete/.test(d[r])&&x()},10);o=w.onload;w.onload=function(){x();o&&o()}}e.push(f)}})();


/* Cookie functions */
function getCookie(cookieName){
	var cookieJar=document.cookie.split("; ");
	for(var x=0;x<cookieJar.length;x++){
		var oneCookie=cookieJar[x].split("=");
		if(oneCookie[0]==escape(cookieName)){
			return unescape(oneCookie[1]);
		}
	}
	return null;
}

// general add event function
function add(event, body, d) {
	if (event.addEventListener) { return event.addEventListener(body, d,false); }
	if (event.attachEvent) { return event.attachEvent('on'+body, d); }
}


function setCookie(cookieName,cookieValue,lifeTime,path,domain,isSecure){
	if(!cookieName){
		return false;
	}
	if(lifeTime=="delete"){
		lifeTime=-10;
	}
	document.cookie=escape(cookieName)+"="+escape(cookieValue)+(lifeTime?";expires="+(new Date((new Date()).getTime()+(1000*lifeTime))).toGMTString():"")+(path?";path="+path:"")+(domain?";domain="+domain:"")+(isSecure?";secure":"");
	if(lifeTime<0){
		if(typeof(getCookie(cookieName))=="string"){
			return false;
		}return true;
	}
	if(typeof(getCookie(cookieName))=="string"){
		return true;
	}
	return false;
}

function deleteCookie(cookieName) {
	setCookie(cookieName, "", "delete");
}

/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}

NDownloadUrl = function(url, func) {
/*
	This function replicates the google map GDownloadURL functionality for ajax file download.
	url    : Call url
	func   : custom function which is used to process returned data
*/
	var httpObj=null;     
	if (window.XMLHttpRequest) { // proper browser
		httpObj=new XMLHttpRequest();
	}
	else if (window.ActiveXObject) { // IE6 and older
		httpObj=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (httpObj!=null){
		httpObj.open('GET', url, true);
		httpObj.onreadystatechange = function() {
			if(httpObj.readyState == 4){ // 'loaded'
				if (httpObj.status == 200) { // 'OK'
					var contenttype = httpObj.getResponseHeader('Content-Type');
					if (contenttype.indexOf('xml')>-1) {
						func(httpObj.responseXML);
					} else {
						func(httpObj.responseText);
					}
				} else {
					func('Error: '+httpObj.status);
			   }
			}
		};
		httpObj.send(null);
	} else {
		// browser cannot do ajax.
	}
}

/* Simple and horrible JS popup window */

function popup(url,height,width) {
	window.open(url,'videowindow', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no,width='+width+',height='+height);
	return false;
}
function OpenPopup(options) {
    options = {
        url: options.url || "",
        width: options.width || 480,
        height: options.height || 315,
        title: options.title || '',        
        menubar: options.menubar || 'no',
        location: options.location || 'no',
        resizable: options.resizable || 'yes',
        scrollbars: options.scrollbars || 'no',
        status: options.status || 'yes'
        
        
    };
    if (options.url != '') {
        var left = (screen.width / 2) - (options.width / 2);
        var top = (screen.height / 2) - (options.height / 2);
        window.open(options.url, options.title, 'menubar=' + options.menubar + ',location=' + options.location + ',resizable=' + options.resizable + ',scrollbars=' + options.scrollbars + ',status=' + options.status + ',width=' + options.width + ',height=' + options.height + ',left=' + left + ',top=' + top);
    }
}

// quick and dirty match console popup taken from .com site
var popupWin;
function openMatchConsole()
{
  popupWin = window.open("http://www.manutd.com/default.sps?pagegid=%7B3303A5DB%2D9D19%2D4467%2DBD9A%2DCA384AD15F6D%7D","MatchConsole","toolbar=no,leftmargin=0,topmargin=0,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=866,height=700");
  popupWin.focus();
}

function getNumbers(idstr) { // extracts only numbers from a string.
    return parseInt(idstr.replace(/[^0-9]/g, ''));
}

// get Elements By class name. returns an array of objects
// params are class name, an optional node to search (default is document), an optional tag name to restrict it further
function getElementsByClass(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null) node = document;
	if (tag == null) tag = '*';
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    var pattern = new RegExp("\\b"+searchClass+"\\b");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

// a Prototype-style dollar function
// can take in a string or an object
// you can pass it as many params as you like.
// it returns either an object or an array of objects
//function $() {
//	var elements = new Array();
//	for (var i = 0; i < arguments.length; i++) {
//		var element = arguments[i];
//		if (typeof element == 'string')
//			element = document.getElementById(element);
//		if (arguments.length == 1)
//			return element;
//		elements.push(element);
//	}
//	return elements;
//}

//for united match reports
function swapteams() {
try
{
    var tt=$('#matchcard')[0];
    if (tt) {
        var as = tt.getElementsByTagName('A');
        if (as) {
            for (var x=0; x<as.length; x++){
                as[x].onclick = function(){
                    var ts = $('#matchcard')[0];
                    var ls = ts.getElementsByTagName('H3');
                    var ts = ts.getElementsByTagName('TABLE');
                    
                    if ((this.id == ts[0].id && ts[0].className.indexOf('off') > -1) ||
                        (this.id == ts[1].id && ts[1].className.indexOf('off') > -1))
                        {
                            for (var x=0; x<ls.length; x++){
                                if (ls[x].className.indexOf('titletaboff') > -1) {
                                    ls[x].className = ls[x].className.replace('titletaboff','titletab');
                                } else {
                                    ls[x].className = ls[x].className.replace('titletab','titletaboff');
                                }
                            }
                            for (var x=0; x<ts.length; x++){
                                if (ts[x].className.indexOf('off') > -1) {
                                    ts[x].className = ts[x].className='';
                                } else {
                                    ts[x].className = ts[x].className='off';
                                }
                            }
                    }
                    return false;
                };
            }
        }
    }
    }
    catch (err)
    { }
}

//shows hint for players & staff keyword search
function HideHint(input, hint) {
    hint = TrimText(hint);
    input.value = TrimText(input.value);

    if (input.value == hint)
        input.value = '';
}
function ShowHint(input, hint) {
    hint = TrimText(hint);
    input.value = TrimText(input.value);

    if (input.value == '')
        input.value = hint;
}

function TrimText(text) {
    text = text.replace(/\r\n/g, '');
    //text = text.replace(/\s+$/, '');
    return text.trim();
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

//LightBox start
function clickLightBox()
{  
    if(!(typeof image_set_report_gallery === 'undefined'))
    {
	    GB_showImageSet(image_set_report_gallery, 1);
	}
	return false;
}

//MPU Video cookie

function playMpuVideo(playerKey, mediaId) {
    
    var key = playerKey+'_'+mediaId;
    var mpuCookie = getCookie(key);

    if (mpuCookie == null) {
        setCookie(key, '1', null, '', '', false);
        return 'true';
    }
    else
        return 'false';
}

function browserIsIE6() {
    return (/MSIE (6)/.test(navigator.userAgent) && navigator.platform == "Win32");
}

function browserIsIE7() {
    return (/MSIE (7)/.test(navigator.userAgent) && navigator.platform == "Win32");
}

function makeScrollableElementOnIE6(parentId, childId) {
    var parent = document.getElementById(parentId);
    var child = document.getElementById(childId);
    if (parent != null && child != null) {
        if (browserIsIE6()) {
            if (child.clientHeight > parent.clientHeight)
                child.style.width = 646 + 'px';
        }
    }
}

function playMpuVideo(playerKey, mediaId) {

    var key = playerKey + '_' + mediaId;
    var mpuCookie = getCookie(key);

    if (mpuCookie == null) {
        setCookie(key, '1', null, '', '', false);
        return 'true';
    }
    else
        return 'false';
}
