// general functions
function addLoadEvent(func) {	
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function pageLoad(sender, args) {
      if(args.get_isPartialLoad()){   
         //tb_init('a.thickbox');   
    }   
 }
 
function getElementByClass(classname){ 
     var messages=new Array();
     var inc=0; 
     var alltags=document.all? document.all : document.getElementsByTagName("*"); 

     for (i=0; i<alltags.length; i++){
        if (alltags[i].className.match(classname)){ 
         messages[inc++]=alltags[i]; 
         }
     }
     if(messages != null){return messages;}
     else {return null;}
} 

function getAbsX(elt) {return (elt.x) ? elt.x : getAbsPos(elt,"Left");}
function getAbsY(elt) {return (elt.y) ? elt.y : getAbsPos(elt,"Top");}
function getAbsPos(elt,which) {
    var iPos = 0;
    while (elt != null) {
     iPos += elt["offset" + which];
     elt = elt.offsetParent;
    }
    return iPos;
}

function enlargeImageThumb(x) {
    var eleMainImage = document.getElementById('ctl00_cph_content_main_img');  
    var eleMainLnk = document.getElementById('ctl00_cph_content_main_lnk');
    var eleMainZoomLnk = document.getElementById('ctl00_cph_content_main_zoomlnk');
    var eleThumbImage = getElementByClass('thumb'); 
    
    if (eleMainLnk!=null){ 
        var s = x.href.split("?hi-res=");
        //alert(s[1]);
        eleMainZoomLnk.href = s[1];      
        eleMainLnk.href = s[1];
        eleMainImage.src = x.href;        
    }
    return false;    
}

function applyEventsToImages() {
    var eleThumbLnk = getElementByClass('thumblnk');
    if (eleThumbLnk!=null){
            for (var intCounter = 0; intCounter < eleThumbLnk.length; intCounter++) {
            eleThumbLnk[intCounter].onmouseover = function ()
	                {enlargeImageThumb(this);
	                return false;}  
	        eleThumbLnk[intCounter].onclick = function ()
	                {return false;}                  			
                }
            }
} 

function validatePostCode(value, strDefault)
{
    var postcodeFilter=/^[A-Za-z]{1,2}[0-9A-Za-z]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/;
    
    if (!postcodeFilter.test(value) && value == '' || value == strDefault) 
    {
        return true;
    }
    else
    {
        return false;
    }	
}

function checkPostCode(toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}

function ismaxlength(obj) {
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length > mlength)
        obj.value = obj.value.substring(0, mlength)
}


function doOpenMediaBox(evt, width, height, obj) {
    var md = document.getElementById('box-wrap');

    if (md != null) {
        if (md.style.display == '' || md.style.display == 'none') {
            doMedia(evt, width, height, obj)
            obj.className = 'media visible';
            //return false;
        }
        else { obj.className = 'media'; }
    }
}
   
function doMedia(evt,width,height,obj) {
    var df;
    var qt = document.getElementById('quicktime');
    var fm = document.getElementById('flashMediaContent');
    var wm = document.getElementById('mediaworldmap');
    var random = Math.floor(Math.random() * 101)
       
    doResetSelector();
    
    if (qt != null) {
        fm.style.display = '';
        qt.style.display = 'none';
        wm.style.display = 'none';

        var strClass = obj.className;

        if (strClass.indexOf('selected') != -1) {
            strClass = strClass.substring(0, strClass.indexOf('selected'))
            element[intCounter].className = strClass;
        }
        else if (strClass.indexOf('media') >= 0) {
        
            // Reset links
            var links = document.getElementById('media_carousel');
            if (links != null) {
                if (!links.getElementsByTagName) return false;
                var element = links.getElementsByTagName("a");
                var strClass = element[0].className;
                var firstitem = getElementByClass(strClass)
                   
                    if (strClass.indexOf('selected') == -1) {
                        firstitem[0].className = strClass + ' selected';
                    }
                }
            }
         else {    
            obj.className += ' selected';
        }
    }

    if (evt == 'Video1') { df = '/library/flash/videoplayer/xml/listings.aspx?rand=' + random; }
    if (evt == 'Video2') { df = '/library/flash/videoplayer/xml/listings.aspx?rand=' + random; }
    if (evt == 'Panoramic1') { df = '/library/flash/panoplayer/xml/listings.aspx?rand=' + random; }
    if (evt == 'Photo1') { df = '/library/flash/slideshow/xml/slideshow.aspx?rand=' + random; }
    if (evt == 'Photo2') { df = '/library/flash/slideshow/xml/slideshow.aspx?rand=' + random; }
    if (evt == 'Photo4') { df = '/library/flash/slideshow/xml/slideshow.aspx?rand=' + random; }
    if (evt == 'FAQ1') { df = '/library/flash/faqplayer/xml/listings.aspx?type=1&rand=' + random; }
    if (evt == 'FAQ2') { df = '/library/flash/faqplayer/xml/listings.aspx?type=2&rand=' + random; }
    
    var so = new SWFObject("/library/flash/multimediaplayer/MultiMediaAppPre.swf", "indexFile", width, height, "9", "#000000");
    so.addVariable("xmlDataFile", df);
    so.addVariable("xmlConfigFile", "/library/flash/multimediaplayer/xml/config.aspx");
    so.addVariable("strTemplate", evt.toString());
    so.addVariable("swfFile", "/library/flash/multimediaplayer/MultiMediaApp.swf");
    so.addParam("allowFullScreen", "true")
    so.addParam("wmode", "transparent")
    so.write("flashMediaContent");

}

function doWorldMap(obj) {
    var qt = document.getElementById('quicktime');
    var fm = document.getElementById('flashMediaContent');
    var wm = document.getElementById('mediaworldmap');

    doResetSelector();
    
    if (wm != null) {
        fm.style.display = 'none';
        qt.style.display = 'none';
        wm.style.display = '';
        obj.className = 'world-map selected';
    }
}

function do360Player(width, height, obj) {
    var qt = document.getElementById('quicktime');
    var fm = document.getElementById('flashMediaContent');
    var wm = document.getElementById('mediaworldmap');
    
    doResetSelector();

    if (qt != null) {
        fm.style.display = 'none';
        wm.style.display = 'none';
        qt.style.display = '';
        obj.className = 'images-360 selected';
    }
}

function doResetSelector() {
    var links = document.getElementById('media_carousel');

    // Reset links
    if (links != null) {
        if (!links.getElementsByTagName) return false;
        var element = links.getElementsByTagName("a");
        for (var intCounter = 0; intCounter < element.length; intCounter++) {
            var strClass = element[intCounter].className;

            if (strClass.indexOf('selected') != -1) {
                strClass = strClass.substring(0, strClass.indexOf('selected'))
                element[intCounter].className = strClass;                
            }
        }
    }

}


function doShowQT(id,obj) {
    var ele = document.getElementById(id);
    doHideAllQT();

    if (ele != null) {
        ele.style.display = '';
        obj.className = 'selected';
     }
}

function doHideAllQT() {
    var qmenu = document.getElementById('qmenu');
    var qmovie = document.getElementById('qmovie');

    // Reset links
    if (qmenu != null) {
        if (!qmenu.getElementsByTagName) return false;
        var element = qmenu.getElementsByTagName("a");
        for (var intCounter = 0; intCounter < element.length; intCounter++) {
            element[intCounter].className = 'norm';
        }
    }

    // Hide All Movies
    if (qmovie != null) {
        if (!qmovie.getElementsByTagName) return false;
        var element = qmovie.getElementsByTagName("div");
        for (var intCounter = 0; intCounter < element.length; intCounter++) {
            element[intCounter].style.display = 'none';
        }
    }
}


// Countdown timer
var SetTimeOutPeriod

function calcage(secs, num1, num2) {
    s = ((Math.floor(secs / num1)) % num2).toString();
    if (LeadingZero && s.length < 2)
        s = "0" + s;
    return "<b>" + s + "</b>";
}

function CountBack(secs) {
    if (isNaN(secs)) {
        document.getElementById('days').innerHTML = 'TBC';
        document.getElementById('hours').innerHTML = '';
        document.getElementById('mins').innerHTML = '';
        Cufon.replace('#content-wrap .top-container .event-wrap .countdown', { fontFamily: 'HelveticaNeue-CondensedBold' });
        return;
    }
          
        DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs, 86400, 100000));
        DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs, 3600, 24));
        DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs, 60, 60));
        DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs, 1, 60));

        // Display Countdown
        document.getElementById('days').innerHTML = calcage(secs, 86400, 100000);
        document.getElementById('hours').innerHTML = calcage(secs, 3600, 24);
        document.getElementById('mins').innerHTML = calcage(secs, 60, 60);
        //document.getElementById('test').innerHTML = DisplayStr;

        Cufon.replace('#content-wrap .top-container .event-wrap .countdown', { fontFamily: 'HelveticaNeue-CondensedBold' });

        if (CountActive)
            {setTimeout("CountBack(" + (secs + CountStepper) + ")", SetTimeOutPeriod);}
}

function initCountDown() { 

    if (typeof (TargetDate) == "undefined")
        TargetDate = document.getElementById("EventDate").value;
    if (typeof (DisplayFormat) == "undefined")
        DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
    if (typeof (CountActive) == "undefined")
        CountActive = true;
    if (typeof (FinishMessage) == "undefined")
        FinishMessage = "";
    if (typeof (CountStepper) != "number")
        CountStepper = -1;
    if (typeof (LeadingZero) == "undefined")
        LeadingZero = true;

    CountStepper = Math.ceil(CountStepper);
    if (CountStepper == 0)
        CountActive = false;
    SetTimeOutPeriod = (Math.abs(CountStepper) - 1) * 1000 + 990;
    var dthen = new Date(TargetDate);
    var dnow = new Date();
    if (CountStepper > 0)
        ddiff = new Date(dnow - dthen);
    else
        ddiff = new Date(dthen - dnow);
    gsecs = Math.floor(ddiff.valueOf() / 1000);
    CountBack(gsecs);
}


function doSelectBG(obj) {
    var ath = document.getElementById('athletes');

    // update styles athletes
    if (ath != null) {
        var elementLI = ath.getElementsByTagName("li");

        for (var intCounter = 0; intCounter < elementLI.length; intCounter++) {
            var c = elementLI[intCounter].className;
            //alert(c);
            if (c.indexOf("AltRow AspNet-TreeView-Selected") >= 0) {
                elementLI[intCounter].className = 'AspNet-TreeView-Root AltRow';                
            }
            else if (c.indexOf("AspNet-TreeView-Selected") >= 0) {
                elementLI[intCounter].className = 'AspNet-TreeView-Root';                
            }
        }
    }
    
    if (obj != null) {
        var elementLI = obj.parentNode.parentNode;
        var s = elementLI.className

        Cufon.replace('.ProfileTreeAdvanced .AspNet-TreeView .AspNet-TreeView-ClickableNonLink', { fontFamily: 'HelveticaNeue-CondensedBold', color: '#363636' });
        Cufon.replace('.ProfileTreeAdvanced .AspNet-TreeView .AltRow .AspNet-TreeView-ClickableNonLink', { fontFamily: 'HelveticaNeue-CondensedBold', color: '#ffffff' });
     
        if (s.indexOf("AltRow AspNet-TreeView-Selected") >= 0) {
            elementLI.className = 'AspNet-TreeView-Root AltRow';
                   }
        else if (s.indexOf("AspNet-TreeView-Selected") >= 0) {
            elementLI.className = 'AspNet-TreeView-Root';
          }
          else {
              //Cufon.refresh();
              elementLI.className += ' AspNet-TreeView-Selected';
              Cufon.replace('.ProfileTreeAdvanced .AspNet-TreeView li.AspNet-TreeView-Root.AspNet-TreeView-Selected .AspNet-TreeView-ClickableNonLink', { fontFamily: 'HelveticaNeue-CondensedBold', color: '#ffffff' });
        }

        $("#content-left").css("height", "auto");
        $("#content-right").css("height", "auto");
        $("#content-wrap").css("height", "auto");
        $('#content-wrap').equalHeights();
    }
}

var Tools = function () {
    return {
    createElementCallback: function (tagName) {
        return function (node) {
        return isElement(node, tagName);
    };
    },
    getFirstChild: function (parent, test) {
        var node = parent.firstChild;

        if (node) return test(node) ? node : this.getNextSibling(node, test);
        return null;
    },
    getLastChild: function (parent, test) {
        var node = parent.lastChild;

        if (node) return test(node) ? node : this.getPreviousSibling(node, test);
        return null;
    },
    getNextSibling: function (node, test) {
        while ((node = node.nextSibling))
        if (test(node)) return node;
        return null;
    },
    getPreviousSibling: function (node, test) {
        while ((node = node.previousSibling))
        if (test(node)) return node;
        return null;
    },
    isElement: isElement
};

function isElement(node, tagName) {
    return (node.nodeType == 1)
    && (tagName ? (node.nodeName == tagName) : (node.nodeName != '!'));
}
} ();


function setDefaultCookieValue(cookie_name, value) {
    var cookie = $.cookie(cookie_name);
    // if not set, set to value
    if (cookie == null) {
        $.cookie(cookie_name, value);
    }
}
function hideTip() {
    $("#isp-tip").toggle();
}
this.tooltipSetup = function() {
    var timer = null;
    $(".tooltip").hover(
		function(e) {
		    if (timer) {
		        clearTimeout(timer);
		        timer = null;
		    }
		},
		function() {
		    timer = setTimeout('hideTip()', 1000);
		}
	);
    $("a[rel=tooltip]").hover(
		function(e) {
		    if (timer) {
		        clearTimeout(timer);
		        timer = null;
		    }
		    this.tip_id = this.title;
		    this.title = "";
		    $("#isp-tip").appendTo("isp_wrap");
		    $("#isp-tip").addClass("current").fadeIn("fast");
		},
		function() {
		    timer = setTimeout('hideTip()', 1000);
		}
	);
};

function cookieSetup() {
    setDefaultCookieValue('footer_show', 'collapsed');
    var footer_show = $.cookie('footer_show');

    // set up initial state
    if (footer_show == 'collapsed') {
        $('#footer-bar', '#footer').removeClass('hider');
        $('#footer-sections', '#footer').toggle();
        $('#footer-bar a.show', '#footer').html('Show Footer Quick Links');
        Cufon.replace('#footer-bar a', { fontFamily: 'HelveticaNeue-CondensedBold' });

    } else {
        $('#footer-bar', '#footer').addClass('hider');
    }

    $('#footer-bar a.show', '#footer').click(
		function() {
		    footer_show = $.cookie('footer_show');
		    footer_link = $('#footer-bar a.show', '#footer');
		    footer_link.blur();
		    if (footer_show == 'collapsed') {
		        $('#footer-sections', '#footer').slideToggle();
		        $('#footer-bar a.show', '#footer').html('Hide Footer Quick Links');
		        Cufon.replace('#footer-bar a', { fontFamily: 'HelveticaNeue-CondensedBold' });
		        $('#footer-bar', '#footer').addClass('hider');
		        $.cookie('footer_show', 'expanded');
		    }
		    if (footer_show == 'expanded') {
		        $('#footer-bar', '#footer').removeClass('hider');
		        $('#footer-sections', '#footer').slideToggle();
		        $('#footer-bar a.show', '#footer').html('Show Footer Quick Links');
		        Cufon.replace('#footer-bar a', { fontFamily: 'HelveticaNeue-CondensedBold' });
		        $.cookie('footer_show', 'collapsed');
		    }
		    return false;
		}
	);
}
function mediaHide(box) {
    var list = box.children('ul');
    box.slideUp("fast");
    list.hide();
    $('span.media', '#nav-media').toggleClass('visible');
}
function mediaShow(box) {
    var list = box.children('ul');
    $('span.media', '#nav-media').toggleClass('visible');
    box.slideDown("slow");
    list.fadeIn("slow");
}

function mediaSetup() {
    // setup the drop-down media selector
    var link = $('#nav-media a.media');
    link.click(function() {
        var box = $(this).siblings('.box');
        if (!(box.is(':visible'))) {
            mediaShow(box);
        } else {
            mediaHide(box);
        };
        return false;
    });

    $('ul#media_carousel').jcarousel({
        scroll: 1,
        vertical: true,
        elementSize: 78
        //initCallback: media_carousel_initCallback
    });
}

function intuitionPopup() {

    $(function() {
        $('.bubbleInfo').each(function() {
            var distance = 10;
            var time = 250;
            var hideDelay = 500;
            var hideDelayTimer = null;
            var beingShown = false;
            var shown = false;
            var trigger = $('.trigger', this);
            var info = $('.popup', this); //.css('opacity', 0);

            $([trigger.get(0), info.get(0)]).mouseover(function() {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (beingShown || shown) {
                    // don't trigger the animation again
                    return;
                } else {
                    // reset position of info box
                    beingShown = true;

                    info.css({
                        top: -152,
                        left: -15,
                        display: 'block'
                    }).animate({
                        top: '-=' + distance + 'px' //,
                        //opacity: 1
                    }, time, 'swing', function() {
                        beingShown = false;
                        shown = true;
                    });
                }

                return false;
            }).mouseout(function() {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                hideDelayTimer = setTimeout(function() {
                    hideDelayTimer = null;
                    info.animate({
                        top: '-=' + distance + 'px' //,
                        //opacity: 1
                    }, time, 'swing', function() {
                        shown = false;
                        info.css('display', 'none');
                    });

                }, hideDelay);

                return false;
            });
        });
    });

}

function siteInit() {
    cookieSetup()
    intuitionPopup();
    //mediaSetup();
    // setup the footer tooltip
    //tooltipSetup();

    // Bind to image links only
    $(document).bind('cbox_complete', function() {
        var link = $('#cboxPhoto');
        link.css({cursor: 'pointer'});
        link.click(function() {
            $.fn.colorbox.close();
        });
    });
}



