// A fast trim
function trim(str) {
    var str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
    while (ws.test(str.charAt(--i)));
    return str.slice(0, i + 1);
}

// Get object function. Handle multiple browsers
// [Obsolete] Use Prototype $()
function getObj(name) {
    if (document.getElementById) {
        return document.getElementById(name)
    } else if (document.all) {
        return document.all[name]
    } else if (document.layers) {
        return document.layers[name]
    }
}

// [Obsolete] Use Prototype Element.select()
function returnElements(obj, elName) {
    if (obj.getElementsByTagName) {
        return obj.getElementsByTagName(elName)
    } else if (obj.tags[elName]) {
        return obj.tags[elName]
    } else alert("Can not find tag " + elName)
}

function centerElementOnScreen(element) {
    element = $(element); // So we can be passed an element or an ID

    var scrollTop = document.body.scrollTop;
    var scrollLeft = document.body.scrollLeft;

    var viewPortHeight = document.body.clientHeight;
    var viewPortWidth = document.body.clientWidth;

    if (document.compatMode == "CSS1Compat") {
        viewPortHeight = document.documentElement.clientHeight;
        viewPortWidth = document.documentElement.clientWidth;

        scrollTop = document.documentElement.scrollTop;
        scrollLeft = document.documentElement.scrollLeft;
    }

    var topOffset = Math.ceil(viewPortHeight / 2 - element.offsetHeight / 2);
    var leftOffset = Math.ceil(viewPortWidth / 2 - element.offsetWidth / 2);

    var top = scrollTop + topOffset - 40;
    var left = scrollLeft + leftOffset - 70;

    element.setStyle({
        position: "absolute",
        top: top + "px",
        left: left + "px"
    });
}

function clearInput(inp, defaultText) {
    if (inp && inp.value == defaultText) {
        inp.value = '';
        inp.className = inp.className.replace("defaultValue", "");
    }
    return false;
}

function resetInput(inp, defaultText) {
    if (inp && trim(inp.value) == '') {
        inp.value = defaultText;
        inp.className = inp.className.replace("defaultValue", "") + " defaultValue";
    }
}

function navigateFromDropDownMenu(clientID) {
    dropDownMenu = getObj(clientID);
    document.location.href = dropDownMenu.options[dropDownMenu.selectedIndex].value;
}

var transparentImage = "images/transparent.gif";
function fixTrans() {
    if (typeof document.body.style.maxHeight == 'undefined') {

        var imgs = document.getElementsByTagName("img");

        for (i = 0; i < imgs.length; i++) {
            if (imgs[i].src.indexOf(transparentImage) != -1) {
                return;
            }

            if (imgs[i].src.indexOf(".png") != -1) {
                var src = imgs[i].src;
                imgs[i].src = transparentImage;
                imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
            }
        }
    }
}
if (document.all && !window.opera)
    attachEvent("onload", fixTrans);


// opens new window
function NewWin(url) {
	var newWindow = window.open(url);
	newWindow.focus();
}

// opens new window of specified size
function NewWinSized(url, x, y) {
	var newWindow = window.open(url, 'popupwindow', 'width='+x+',height='+y+',toolbar=0,location=0,menubar=0,scrollbars=0,status=0');
	newWindow.focus();
}

// opens new window of specified size, with scrollbars
function NewWinSizedScroll(url, x, y) {
	var newWindow = window.open(url, 'popupwindow', 'width='+x+',height='+y+',toolbar=0,location=0,menubar=0,scrollbars=1,status=0');
	newWindow.focus();
}

// opens new window for england tv feed
function EnglandTV(url, speed) {
	var idIx = url.indexOf('=');
	if (idIx != -1) {
		var identifier = url.substring(idIx+1, url.length);
		var construct = '/templates/video/englandtv.aspx?id='+identifier+'&speed='+speed;
		var newWindow = window.open(construct, 'englandtv','width=332,height=430,toolbars=no,status=no,scrollbars=no');
		newWindow.focus();
	}
}

// opens new window for FATV with supplied video id
function FATV(vid) {
	NewWinSized("/fatv/microsite.aspx?i=" + vid,760,507);
}

// opens new window for FATV with supplied posting
function ShowPostingVideos(posting) {
	NewWinSized("/fatv/microsite.aspx?p=" + posting,760,507);
}

// opens new window for england tv feed
function EnglandTVRM(url, speed) {
	var idIx = url.indexOf('=');
	if (idIx != -1) {
		//var identifier = url.substring(idIx+1, url.length);
		var construct = '/templates/video/englandtvrm.aspx?url='+url+'&speed='+speed;
		var newWindow = window.open(construct, 'englandtv','width=332,height=430,toolbars=no,status=no,scrollbars=no');
		newWindow.focus();
	}
}
// opens new window for FA Cup tv feed
function FACupTV(url, speed) {
	var idIx = url.indexOf('=');
	if (idIx != -1) {
		var identifier = url.substring(idIx+1, url.length);
		var construct = 'http://www.thefa.com/templates/video/facuptv.aspx?id='+identifier+'&speed='+speed;
		var newWindow = window.open(construct, 'facuptv','width=332,height=430,toolbars=no,status=no,scrollbars=no');
		newWindow.focus();
	}
}

// opens new window for FA Cup audio feed
function FACupAudio(feedUrl) {
	var baseUrl = "http://www.thefa.com/static/audiopopup/?src=";
	var construct = baseUrl + escape(feedUrl)
	var newWindow = window.open(construct, 'facupaudio','width=332,height=100,toolbars=no,status=no,scrollbars=no');
	newWindow.focus();
}

//Registration POPUP for FAN
function popupFAN() {
	window.open('https://secure.thefa.com/FAN/Register.aspx','winFAN','width=479,height=548,scrollbars=no,statusbar=no')
}

// Header functions
function navigateToDropDownListSelection(ddlID, openNewWindow) {
    ddl = getObj(ddlID);
    url = ddl.options[ddl.selectedIndex].value;

    if (url == "n/a") {
        if (ddl.id.indexOf("CountySites") > 0) {
            alert("Please choose a County to visit");
        }
        else
            if (ddl.id.indexOf("FASites") > 0) {
            alert("Please choose an FA site to visit");
        }
        else {
            alert("Please make a selection");
        }
        return false;
    }
    if (openNewWindow == 'true') {
        window.open(url, "newWin");
    }
    else {
        window.location = url;
    }

    return false;

}

function clearSearch(txtSearchID) {
    txtSearch = getObj(txtSearchID);
    return clearInput(txtSearch, 'Enter search');
}

function doSearch(txtSearchID, searchURI) {
    txtSearch = getObj(txtSearchID);
    if (txtSearch.value.length == 0 || txtSearch.value == 'Enter search') {
        alert('Please enter a search term');
        txtSearch.focus();
        return false;
    }
    else {
        document.location.href = (searchURI || "/TheFA/Search.aspx?s=") + txtSearch.value;
        return false;
    }
}



var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, {
    initialize: function(id) {
        this.createOverlay();

        this.dialog_box = $(id);
        this.dialog_box.show = this.show.bind(this);
        this.dialog_box.persistent_show = this.persistent_show.bind(this);
        this.dialog_box.hide = this.hide.bind(this);

        this.parent_element = this.dialog_box.parentNode;

        this.dialog_box.style.position = "absolute";

        var e_dims = Element.getDimensions(this.dialog_box);
        var b_dims = Element.getDimensions(this.overlay);

        this.dialog_box.style.left = ((b_dims.width / 2) - (e_dims.width / 2)) + 'px';
        this.dialog_box.style.top = this.getScrollTop() + ((this.winHeight() - (e_dims.width / 2)) / 2) + 'px';
        this.dialog_box.style.zIndex = this.overlay.style.zIndex + 1;
    },

    createOverlay: function() {
        if ($('dialog_overlay')) {
            this.overlay = $('dialog_overlay');
        } else {
            this.overlay = document.createElement('div');
            this.overlay.id = 'dialog_overlay';
            Object.extend(this.overlay.style, {
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 90,
                width: '100%',
                backgroundColor: '#000',
                display: 'none'
            });
            document.body.appendChild(this.overlay, document.body.childNodes[0]);
        }
    },

    moveDialogBox: function(where) {
//        Element.remove(this.dialog_box);
//        if (where == 'back')
//            this.dialog_box = this.parent_element.appendChild(this.dialog_box);
//        else
//            this.dialog_box = this.overlay.parentNode.insertBefore(this.dialog_box, this.overlay);
    },

    show: function() {
        this.overlay.style.height = this.bodyHeight() + 'px';
        this.moveDialogBox('out');

        this.overlay.onclick = this.hide.bind(this);

        this.selectBoxes('hide');
        new Effect.Appear(this.overlay, { duration: 0.1, from: 0.0, to: 0.3 });
        this.dialog_box.style.display = '';

        this.dialog_box.style.left = '0px';

        var e_dims = Element.getDimensions(this.dialog_box);

        this.dialog_box.style.left = ((this.winWidth() / 2) - (e_dims.width) / 2) + 'px';

        this.dialog_box.style.top = this.getScrollTop() + ((this.winHeight() - (e_dims.width / 2)) / 2) + 'px';

        return false;
    },

    getScrollTop: function() {
        return (window.pageYOffset) ? window.pageYOffset : (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
    },

    persistent_show: function() {
        this.overlay.style.height = this.bodyHeight() + 'px';
        this.moveDialogBox('out');

        this.selectBoxes('hide');
        new Effect.Appear(this.overlay, { duration: 0.1, from: 0.0, to: 0.3 });

        this.dialog_box.style.display = '';
        this.dialog_box.style.left = '0px';
        var e_dims = Element.getDimensions(this.dialog_box);
        this.dialog_box.style.left = ((this.winWidth() / 2) - (e_dims.width) / 2) + 'px';

    },

    hide: function() {
        this.selectBoxes('show');
        new Effect.Fade(this.overlay, { duration: 0.1 });
        this.dialog_box.style.display = 'none';
        this.moveDialogBox('back');
        $A(this.dialog_box.getElementsByTagName('input')).each(function(e) { if (e.type != 'submit') e.value = '' });

        return false;
    },

    selectBoxes: function(what) {
        $A(document.getElementsByTagName('select')).each(function(select) {
            Element[what](select);
        });

        if (what == 'hide')
            $A(this.dialog_box.getElementsByTagName('select')).each(function(select) { Element.show(select) })
    },

    bodyWidth: function() { return document.body.offsetWidth || window.innerWidth || document.documentElement.clientWidth || 0; },
    bodyHeight: function() { return document.body.offsetHeight || window.innerHeight || document.documentElement.clientHeight || 0; },

    winWidth: function() {
        var viewportwidth;

        // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
        if (typeof window.innerWidth != 'undefined') {
            viewportwidth = window.innerWidth;
        }

        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
        else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
            viewportwidth = document.documentElement.clientWidth;
        }

        // older versions of IE
        else {
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth
        }
        return viewportwidth;

    },
    winHeight: function() {
        var viewportheight;

        // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
        if (typeof window.innerHeight != 'undefined') {
            viewportheight = window.innerHeight
        }

        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
        else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0) {
            viewportheight = document.documentElement.clientHeight;
        }

        // older versions of IE
        else {
            viewportheight = document.getElementsByTagName('body')[0].clientHeight;
        }
        return viewportheight;
    }
});
