function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function bookmark(title,url) {
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} else if(document.all) { // ie
		window.external.AddFavorite(url, title);
	} else {
		alert('Please press Control-D (for Windows, Linux) or Command-D (for Apple) to bookmark this page');
	}
}

function emailPage(uid) {
	window.open("/Email-Page?UID="+uid,"pop","width=300,height=250,toolbars=0,scrollbars=0");
}

function printPage() {
	window.print();
}

function showEvents(type) {
	document.getElementById('display').value=type;
	document.getElementById('refineSearch').submit();
}

function buy(i) {
	top.window.location.href = "/Cart/Add?ItemType=TT&ItemID="+i+"&Quantity="+document.getElementById('s'+i).value
}

function buyCustom(i) {
	quantity = document.getElementById('s'+i).value;
	if (!quantity) {
		alert('Please select a quantity');
		return;
	}
	top.window.location.href = "/Cart/Add?ItemType=CT&ItemID="+i+"&Quantity="+quantity;
}

function buyPricedEvent(EventID, EventCatID) {
	quantity = document.getElementById('s'+EventCatID).value;
	if (!quantity) {
		alert('Please select a quantity');
		document.getElementById('s'+EventCatID).focus();
		return;
	}
	top.window.location.href = "/Cart/Add?ItemType=PE&ItemID="+EventCatID+"&Quantity="+quantity+"&Params[EventID]="+EventID;
}

function notes(id) {
	note = document.getElementById('notes'+id);
	if (note.className == 'hide') note.className='show';
	else note.className='hide';
}

function addItemToCart(i) {
	top.location.href = '/Cart/Add/Items/'+i+'/'+document.getElementById('item'+i).value
}

function changeItemQuantity(i) {
	top.location.href = '/Cart/Items/Quantity/'+i+'/'+document.getElementById('item'+i).value
}

function changeTTQuantity(i) {
	top.location.href = '/Cart/Tickets/Quantity/'+i+'/'+document.getElementById('tt'+i).value
}

function colHeight() {
	try {
		var bottomPos = findPosY(document.getElementById('bottomNav1'));
	} catch (e) {}
	try {
		var leftbar = document.getElementById('leftbar');
		if (leftbar) {
			var newHeight = bottomPos - findPosY(leftbar);
			if (newHeight > leftbar.clientHeight) leftbar.style.height = newHeight+'px';
		}
		var rightbar = document.getElementById('rightbar');
		if (rightbar) {
			var newHeight = bottomPos - findPosY(rightbar);
			if (newHeight > rightbar.clientHeight) rightbar.style.height = newHeight+'px';
		}
	} catch (e) {}
}

function findPosY(obj) {
	try {
		var curtop = 0;
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y) {
			curtop += obj.y;
		}
	}
	catch (e) { }
	return curtop;
}

function Float(id, sy, minY, startMoveAt, stopMoveAt, bumper) {
        var objFloat = document.getElementById(id);
        var refObj = document.getElementById(bumper);

        var agt=navigator.userAgent.toLowerCase();
        if (agt.indexOf("msie 6.") != -1) isIE6 = true;
        else isIE6 = false;

        objFloat.cy = objFloat.sy = sy;

        window[id + "_obj"] = objFloat;

        objFloat.doFloat=function() {
                var currentScrollTop = getScroll().top;
                var containingElementTop = getY(refObj);
                var containingElementHeight = refObj.offsetHeight;
                var floatElementHeight = this.offsetHeight;
                var bodyHeight = document.body.clientWidth;
                var fullHeight = document.body.offsetHeight;
                this.newLocation = 0;
                if (currentScrollTop >= startMoveAt && (fullHeight - currentScrollTop) > stopMoveAt) {
                        if (isIE6) {
                                this.style.position = "absolute";
                                this.style.top = currentScrollTop;
                        } else {
                                this.style.position = "fixed";
                                this.style.top = "0px";
                        }
                } else if ((fullHeight - currentScrollTop) <= stopMoveAt) {
                        this.style.position = "absolute";
                        this.style.top = (fullHeight - stopMoveAt-180) + "px";
                } else {
                        this.style.position = "absolute";
                        this.style.top = minY + "px";
                }
        setTimeout(this.id + "_obj.doFloat()", 250);
        }
        objFloat.doFloat();

        return objFloat;
}

getScroll = function () {
  var top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  var left = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
  return { 
    top: top, 
    left: left, 
    offset:{ x: left, y: top }  //  note the change, NOT an Array with added properties. 
  };  //  object
}

function getY(oElement) {
        var iReturnValue = 0;
        while( oElement != null ) {
                iReturnValue += oElement.offsetTop;
                oElement = oElement.offsetParent;
        }
        return iReturnValue;
}

getBorderBox = function (node) {
  return { width: node.offsetWidth, height: node.offsetHeight };  //  object
}

function togglePassword() {
	if (document.getElementById('CheckReturning').checked) {
		document.getElementById('PasswordDiv').style.display = '';
		document.getElementById('Password').disabled = false;
	} else {
		document.getElementById('PasswordDiv').style.display = 'none';
		document.getElementById('Password').disabled = true;
	}
}

spotlightId = 0;
spotlightTags = Array();
function startSpotlight(json) {
	var list = eval(json);
	for (i = 0; i < list.length; i++) {
		image = new Image();
		image.src=list[i]['Image'];
		image.alt=list[i]['Name'];
		image.border=0;
		spotlightTags[i] = document.createElement('a');
		spotlightTags[i].setAttribute('href', list[i]['URL']);
		spotlightTags[i].setAttribute('title', list[i]['Name']);
		spotlightTags[i].appendChild(image);
	}
	spotlight();
}

function spotlight() {
	if (!document.getElementById('spotlightImage')) document.write('<div id="spotlightImage"></div>');
	div = document.getElementById('spotlightImage');
	if (!spotlightTags[spotlightId]) spotlightId = 0;
	try {id=spotlightId-1;if (id < 0) id = spotlightTags.length-1;div.removeChild(spotlightTags[id]);}catch(e){}
	div.innerHTML = '';
	div.appendChild(spotlightTags[spotlightId++]);
	setTimeout("spotlight()",7000);
}


// whitespace characters
var whitespace = " \t\n\r";

// Email address must be of form a@b.c ... in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
function isValidEmail(s) {   
	if (isEmpty(s)) return false;
   
	// is s whitespace?
	if (isWhitespace(s)) return false;
	    
	// there must be >= 1 character before @, so we
	// start looking at character position 1 
	// (i.e. second character)
	var i = 1;
	var sLength = s.length;

	// look for @
	while ((i < sLength) && (s.charAt(i) != "@")) {
		i++;
	}

	if ((i >= sLength) || (s.charAt(i) != "@")) {
		return false;
	} else {
		i += 2;
	}

	// look for .
	while ((i < sLength) && (s.charAt(i) != ".")) {
		i++;
	}

	// there must be at least one character after the .
	if ((i >= sLength - 1) || (s.charAt(i) != ".")) {
		return false;
	} else {
		return true;
	}
}

// Check whether string s is empty.
function isEmpty(s) {   
	return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace(s) {   
	var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++) {   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);

		if (whitespace.indexOf(c) == -1) return false;
    }
    // All characters are whitespace.
    return true;
}

function checkForm() { 
	// z = 0;
	// celements = document.getElementsByName('lid');
	// for (c=0; c < celements.length; c++) {
		// if (celements[c].checked) {
			// z = z + 1;
		// }
	// }
	
	// if (z < 1) {
		// alert("Please select at least one newsletter subscription.");
		// return false;
	// }
	
	document.subscribeform.elements['Full Name'].style.backgroundColor = '#FFFFFF';
	document.subscribeform.elements['Email Address'].style.backgroundColor = '#FFFFFF';
	document.subscribeform.elements['Zip Code'].style.backgroundColor = '#FFFFFF';
	
	if (isEmpty(document.subscribeform.elements['Full Name'].value)) {
		document.subscribeform.elements['Full Name'].style.backgroundColor = '#F0D16F';
		alert("Please enter your full name");
		document.subscribeform.elements['Full Name'].focus();
		return false;
	}
	
	if (!isValidEmail(document.subscribeform.elements['Email Address'].value)) {
		document.subscribeform.elements['Email Address'].style.backgroundColor = '#F0D16F';
		alert("Please enter a valid Email:  user@domain.com");
		document.subscribeform.elements['Email Address'].focus();
		return false;
	}
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (
			anchor.getAttribute("href") && ( 
			anchor.getAttribute("rel") == "external" || 
			anchor.getAttribute("rel") == "external nofollow" || 
			anchor.getAttribute("rel") == "nofollow external" )
			)
		anchor.target = "_blank";
	}
}

function naturalSort (a, b) {
	var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
		sre = /(^[ ]*|[ ]*$)/g,
		dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
		hre = /^0x[0-9a-f]+$/i,
		ore = /^0/,
		// convert all to strings and trim()
		x = a.toString().replace(sre, '') || '',
		y = b.toString().replace(sre, '') || '',
		// chunk/tokenize
		xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
		yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
		// numeric, hex or date detection
		xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
		yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null;
	// first try and sort Hex codes or Dates
	if (yD)
		if ( xD < yD ) return -1;
		else if ( xD > yD )	return 1;
	// natural sorting through split numeric strings and default strings
	for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
		// find floats not starting with '0', string or 0 if not defined (Clint Priest)
		oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
		oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
		// handle numeric vs string comparison - number < string - (Kyle Adams)
		if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1; 
		// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
		else if (typeof oFxNcL !== typeof oFyNcL) {
			oFxNcL += ''; 
			oFyNcL += ''; 
		}
		if (oFxNcL < oFyNcL) return -1;
		if (oFxNcL > oFyNcL) return 1;
	}
	return 0;
}

jQuery.fn.dataTableExt.oSort['natural-asc']  = function(a,b) {
	return naturalSort(a,b);
};

jQuery.fn.dataTableExt.oSort['natural-desc'] = function(a,b) {
	return naturalSort(a,b) * -1;
};

jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
	/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
	var x = a == "-" ? 0 : a.replace( /,/g, "" );
	var y = b == "-" ? 0 : b.replace( /,/g, "" );
	
	/* Remove the currency sign */
	x = x.substring( 1 );
	y = y.substring( 1 );
	
	/* Parse and return */
	x = parseFloat( x );
	y = parseFloat( y );
	return x - y;
};

jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
	/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
	var x = a == "-" ? 0 : a.replace( /,/g, "" );
	var y = b == "-" ? 0 : b.replace( /,/g, "" );
	
	/* Remove the currency sign */
	x = x.substring( 1 );
	y = y.substring( 1 );
	
	/* Parse and return */
	x = parseFloat( x );
	y = parseFloat( y );
	return y - x;
};

jQuery.fn.dataTableExt.aTypes.unshift(  
    function ( sData )  
    {  
        var sValidChars = "0123456789.-,";  
        var Char;  
          
        /* Check the numeric part */  
        for ( i=1 ; i<sData.length ; i++ )   
        {   
            Char = sData.charAt(i);   
            if (sValidChars.indexOf(Char) == -1)   
            {  
                return null;  
            }  
        }  
          
        /* Check prefixed by currency */  
        if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )  
        {  
            return 'currency';  
        }  
        return null;  
    }  
);

/* DATATABLES - sorting and filtering table data functions */
function dataTablesInitialization() {
	//Our Tickets
	$("#featuredTicketsTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bJQueryUI: true, //enable jQuery UI ThemeRoller
		aaSorting: [[3,'asc']], //intitial sort order
		aoColumnDefs: [ //define column functionality based on column order array
			{ bSortable: false, aTargets: [6,7] }, //disable column sorting
			{ bVisible: false, aTargets: [2,5] }, //disable column visibility
			{ iDataSort: 2, aTargets: [0] }, //use column[2] to sort column[0]
			{ iDataSort: 5, aTargets: [4] }, //use column[5] to sort column[4]
			{ sType: 'currency', aTargets: [3] }, //set column data type to currency
			{ sType: 'natural', aTargets: [0,1,2] }, //set column data type to natural
			{ sType: 'numeric', aTargets: [5] } //set column data type to numeric
		]
	});
	//Other Broker Tickets
	$("#ticketsTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bJQueryUI: true, //enable jQuery UI ThemeRoller
		aaSorting: [[3,'asc']], //intitial sort order
		aoColumnDefs: [ //define column functionality based on column order array
			{ bSortable: false, aTargets: [6,7] }, //disable column sorting
			{ bVisible: false, aTargets: [2,5] }, //disable column visibility
			{ iDataSort: 2, aTargets: [0] }, //use column[2] to sort column[0]
			{ iDataSort: 5, aTargets: [4] }, //use column[5] to sort column[4]
			{ sType: 'currency', aTargets: [3] }, //set column data type to currency
			{ sType: 'natural', aTargets: [0,1,2] }, //set column data type to natural
			{ sType: 'numeric', aTargets: [5] } //set column data type to numeric
		]
	});
	//Speculative Tickets
	$("#specTicketsTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bJQueryUI: true, //enable jQuery UI ThemeRoller
		aaSorting: [[2,'asc']], //intitial sort order
		aoColumnDefs: [ //define column functionality based on column order array
			{ bSortable: false, aTargets: [5] }, //disable column sorting
			{ bVisible: false, aTargets: [4] }, //disable column visibility
			{ iDataSort: 4, aTargets: [3] }, //use column[4] to sort column[3]
			{ sType: 'currency', aTargets: [2] }, //set column data type to currency
			{ sType: 'natural', aTargets: [0,1] }, //set column data type to natural
			{ sType: 'numeric', aTargets: [4] } //set column data type to numeric
		]
	});
	//Headliner Tickets
	$("#headlinerTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bSort: false, //disable sorting
		bJQueryUI: true //enable jQuery UI ThemeRoller
	});
	//Venue Tickets
	$("#venueTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bSort: false, //disable sorting
		bJQueryUI: true //enable jQuery UI ThemeRoller
	});
	//Venue Tickets
	$("#venueSelectTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bSort: false, //disable sorting
		bJQueryUI: true //enable jQuery UI ThemeRoller
	});
	//City Tickets
	$("#cityTable").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bSort: false, //disable sorting
		bJQueryUI: true //enable jQuery UI ThemeRoller
	});
	//Popular Listings
	$("#popularlistings").dataTable({
		bInfo: false, //disable display of table information
		bPaginate: false, //disable pagination
		bFilter: false, //disable filter search
		bSort: false, //disable sorting
		bJQueryUI: true, //enable jQuery UI ThemeRoller
		aoColumnDefs: [ //define column functionality based on column order array
			{ sWidth: "33%", aTargets: [0,1] }, //disable column sorting
		]
	});
	//Buy Tickets Link buttons
	$(".buyLink").button();
}

function accordionInitialization() {
	$("#accordion").accordion({
		active: false,
		clearStyle: true,
		collapsible: true,
		animated: false,
		header: 'h3'
	});	
	
	$("#accordion h3 a.backToTop").click(function() {
		window.location = $(this).attr('href');
		return true;
	});
	
	$(".toTop").button();
}

function activateAccordion(indexValue) {
	$("#accordion").accordion("activate", indexValue);
}

function tabsInitialization() {
	$("#tabs").tabs();
	$(".buyPackage").button();
}

function nivoSliderInitialization() {
	$('#slider').nivoSlider({
		effect: 'sliceDown',
		pauseTime: 5000, // How long each slide will show
		directionNavHide: false // Only show on hover
	});
	$('#slider2').nivoSlider({
		effect: 'sliceDown',
		pauseTime: 4000, // How long each slide will show
		directionNavHide: false, // Only show on hover
		controlNavThumbs: true, // Use thumbnails for Control Nav
        controlNavThumbsSearch: '.jpg', // Replace this with...
        controlNavThumbsReplace: '-thumb.jpg' // ...this in thumb Image src
	});
}

function playSound(soundfile) {
	document.getElementById("dummy").innerHTML="<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}

function testimonialRotatorInitialization() {
	setInterval (rotateTestimonials, 8000);
}

// Establish arrays and an index for use in rotateTestimonials()
//var testimonialsTailgate = ['/content/images/testimonials/tailgate-larry-b.png'];
//var testimonialsMLBAllStar = ['/content/images/testimonials/baseball-allstar-bruce-noah-z.png'];
//var testimonialsOlympics = ['/content/images/testimonials/olympics-beth-m.png'];
var testimonialsSuperBowl = ['/content/images/testimonials/super-bowl-kelly-f.png', '/content/images/testimonials/super-bowl-debbie-kevin-k.png', '/content/images/testimonials/super-bowl-bruce-r.png'];
var testimonialsMasters = ['/content/images/testimonials/masters-sara-g.png', '/content/images/testimonials/masters-nicole-s.png', '/content/images/testimonials/masters-diane-s.png', '/content/images/testimonials/masters-bryan-f.png'];
var testimonialsHome = ['/content/images/testimonials/super-bowl-kelly-f.png', '/content/images/testimonials/masters-sara-g.png', '/content/images/testimonials/super-bowl-debbie-kevin-k.png', '/content/images/testimonials/masters-nicole-s.png', '/content/images/testimonials/baseball-allstar-bruce-noah-z.png', '/content/images/testimonials/super-bowl-bruce-r.png', '/content/images/testimonials/masters-diane-s.png', '/content/images/testimonials/olympics-beth-m.png'];
var testimonialsIndex = 1;

function rotateTestimonials() {
	if ($('#testSB').length) {
		$('#testSB').fadeOut('slow', function() {
			$(this).attr('src', testimonialsSuperBowl[testimonialsIndex]);
			$(this).fadeIn('slow', function() {
				if (testimonialsIndex == testimonialsSuperBowl.length-1) {
					testimonialsIndex = 0;
				} else {
					testimonialsIndex++;
				}
			});
		});
	} else if ($('#testMasters').length) {
		$('#testMasters').fadeOut('slow', function() {
			$(this).attr('src', testimonialsMasters[testimonialsIndex]);
			$(this).fadeIn('slow', function() {
				if (testimonialsIndex == testimonialsMasters.length-1) {
					testimonialsIndex = 0;
				} else {
					testimonialsIndex++;
				}
			});
		});
	} else if ($('#testHome').length) {
		$('#testHome').fadeOut('slow', function() {
			$(this).attr('src', testimonialsHome[testimonialsIndex]);
			$(this).fadeIn('slow', function() {
				if (testimonialsIndex == testimonialsHome.length-1) {
					testimonialsIndex = 0;
				} else {
					testimonialsIndex++;
				}
			});
		});
	}
}

//When document is ready, trigger these events
addLoadEvent(externalLinks);
addLoadEvent(dataTablesInitialization);
addLoadEvent(accordionInitialization);
addLoadEvent(tabsInitialization);
addLoadEvent(nivoSliderInitialization);
addLoadEvent(testimonialRotatorInitialization);
