var d = document;

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

launchGlobeSkater = function () {
	modalWindow.windowId = "myModal";
	modalWindow.width = 590;
	modalWindow.height = 430;
	modalWindow.content = "<iframe width='590' height='430' frameborder='0' scrolling='no' marginwidth='0' marginheight='0' allowtransparency='true' src='globeskater/ridetheworld.shtml'></iframe>";
	modalWindow.open();
}

var modalWindow = {
	parent:"body",
	windowId:null,
	content:null,
	width:null,
	height:null,
	close: function() {
		$(".modal-window").remove();
		$(".modal-overlay").remove();
	},
	open: function() {
		var modal = "";
		modal += "<div class=\"modal-overlay\"></div>";
		modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
		modal += this.content;
		modal += "</div>";	

		$(this.parent).append(modal);

		$(".modal-window").append("<a class=\"close-window\">Close</a>");
		$(".close-window").click(function(){modalWindow.close();});
		$(".modal-overlay").click(function(){modalWindow.close();});
	}
};


init = function() {
	var b = d.getElementsByTagName("body")[0];
	if(b.id == "home") {
		preloadImages(["arrow_rainbow_on.gif","arrow_grahams_on.gif","arrow_chipsdeluxe_on.gif","arrow_cheezit_on.gif"]);
	} else {
		switch(b.className) {
			case "interior rainbow":
				preloadImages(["arrow_rainbow_small_on.gif", "arrow_grahams_small_on.gif","arrow_chipsdeluxe_small_on.gif","arrow_cheezit_small_on.gif","bt_rb_spreadtheword_on.gif","bt_rb_product_on.gif","bt_rb_nutrition_on.gif","bt_rb_checkout_on.gif"]);
				break;
			case "interior grahams":
				preloadImages(["arrow_rainbow_small_on.gif", "arrow_grahams_small_on.gif","arrow_chipsdeluxe_small_on.gif","arrow_cheezit_small_on.gif","bt_nc_spreadtheword_on.gif","bt_nc_product_on.gif","bt_nc_nutrition_on.gif","bt_nc_checkout_on.gif"]);
				break;
			case "interior chipsdeluxe":
				preloadImages(["arrow_rainbow_small_on.gif", "arrow_grahams_small_on.gif","arrow_chipsdeluxe_small_on.gif","arrow_cheezit_small_on.gif","bt_cd_spreadtheword_on.gif","bt_cd_product_on.gif","bt_cd_nutrition_on.gif","bt_cd_checkout_on.gif"]);
				break;
			case "interior cheezit":
				preloadImages(["arrow_rainbow_small_on.gif", "arrow_grahams_small_on.gif","arrow_chipsdeluxe_small_on.gif","arrow_cheezit_small_on.gif","bt_cz_spreadtheword_on.gif","bt_cz_product_on.gif","bt_cz_nutrition_on.gif","bt_cz_checkout_on.gif"]);
				break;
		}
	}
}

setBodyClass = function() {
  var b = d.getElementsByTagName("body")[0];
  switch(query["whichskin"]) {
    case "rb":
      b.className = b.className + " rainbow";
      break;
    case "gc":
      b.className = b.className + " grahams";
      break;
    case "cd":
      b.className = b.className + " chipsdeluxe";
      break;
    case "cz":
      b.className = b.className + " cheezit";
      break;
  }
  var r = d.getElementById("redir");
  if(r) r.value = r.value.replace(/whichskin=/, "whichskin=" + query["whichskin"]);
  
  r = d.getElementById("error_redir");
  if(r) r.value = r.value.replace(/whichskin=/, "whichskin=" + query["whichskin"]);
  
  var l = d.getElementById("invite-link");
  if(l) l.href = l.href.toString().replace(/=$/, "=" + query["whichskin"]);
}

preloadImages = function(arr) {
	var imgs = new Array(arr.length - 1);
	for(var i=0; i<arr.length; i++) {
		imgs[i] = new Image;
		imgs[i].src = "/images/" + arr[i];
	}
}

imgOn = function(id) {
	var i = d.getElementById(id);
	var s = i.src;
	i.src = s.replace(/\.(gif|jpg|png)$/, "_on.$1");
}

imgOff = function(id) {
	var i = d.getElementById(id);
	var s = i.src;
	i.src = s.replace(/_on\.(gif|jpg|png)$/, ".$1");
}

getScreensaver = function() {
  if(navigator.userAgent.toLowerCase().indexOf("macintosh") != -1) {
    location.href = "/downloads/gripz/mac/GRIPZ_screensaver.sit";
  } else {
    location.href = "/downloads/gripz/win/GRIPZ_screensaver.exe";
  }
}

function popUpWindow(URL,windowName,width,height) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = Math.round((w-width)/2);
	var topPos = Math.round((h-height)/2);
	var defaults = "scrollbars=auto,resizable=yes,";
	var centerOnScreen = "top="+topPos+",left="+leftPos+",width="+width+",height="+height;
	// safari seems to need the trailer comma
	var options = "'" + defaults + centerOnScreen + ",'";
	window.name = "popup";
	var msgWindow = window.open(URL,windowName,options);
	msgWindow.creator=self;
	msgWindow.focus();
}

updateFlash = function() {
	window.open("http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash");
}

// expode and parseQuery are functions to deal with query string
function explode(item,delimiter) {
	tempArray=new Array(1);
	var Count=0;
	var tempString=new String(item);
	while (tempString.indexOf(delimiter)>0) {
		tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
		tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
		Count=Count+1
	}
	tempArray[Count]=tempString;
	return tempArray;
}

function parseQuery() {
	var returnVals = new Array();
	var qString = new String(window.location);
	var queryStart = qString.indexOf('?');
	if (queryStart==-1) {
		return returnVals;
	}
	var query = qString.substring(queryStart + 1, qString.length);
	parts = explode(query, "&");
	for (i in parts) {
		bits = explode(parts[i], "=");
		returnVals[bits[0]] = bits[1];
	}
	return returnVals;
}

var query = parseQuery();

var cookie = function (name, value, options) { // adapted from http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0, l = cookies.length; i < l; i++) {
                var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// function that's called if pre-onload handlers are available
beforeOnloadInit = function() {
	window.onload();
	window.onload = null;
};

// proprietary DOMContentLoaded Mozilla event handler
if (d.addEventListener) d.addEventListener("DOMContentLoaded", beforeOnloadInit, null);

// write out a behavior for IE/Win 5+ to use the ondocumentready events
d.write('<style type="text/css">');
d.write('body { behavior: url(/js/init.htc); }');
d.write('</style>');

window.onload = function() {
	init();
}

function isValidEmail(address) {
	if (address != "" && address.search) {
      if (address.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
      else return false;
	}
   else return true;
}

function profanityCheck(stringToCheck) {
	var badwords = ["666","adult","anal","anarchist","anarchists","anarchy","anus","aryan","aryans","ass","babe","babes","banging","bangle","bastard","beaver","beer","bestial","binaries","bitch","bitches","bra","bras","breasted","breasts","buff","bugger","butt","butts","cannabis","cigs","circumcise","clit","crack","cum","cunnilingus","cunt","damn","dead","dick","died","dirty","dyke","dynamite","ejaculate","enema","enemas","fag","fags","fantasies","fetish","fist","flagellate","flesh","frigid","fuck","fucker","gash","geisha","gin","girlie","gun","guns","hash","hell","hiv","hustler","hymen","jesus","jew","jews","jugs","kike","kill","killer","killing","kinky","kissing","kkk","klan","klux","knights","knives","latex","leather","lesbian","lesbians","lingerie","lsd","lust","lustful","lusty","mace","madame","mafia","marijuana","masturbate","masturbating","masturbation","mistress","munitions","murder","murderer","mutilation","naked","nakedness","nasty","naughty","nazi","nazis","negligee","nipple","nude","nudity","nymph","panties","panty","pcp","penetration","penis","penises","pervert","perverted","pimp","piss","playmate","playmates","prick","pricks","puss","pussy","queer","quickie","rape","rectum","rifle","rifles","rum","satan","satanism","sensual","sensuous","sex","sexual","sexuality","sexually","sexy","shit","slave","slaves","slay","slayer","slut","smack","smut","snatch","snuff","spank","spanked","spanking","sperm","spik","strip","strippers","striptease","studs","suck","sucker","sucking","suicide","supremacy","suspender","swinger","swingers","swinging","testicle","testicles","thc","tit","tits","ultimate","underwear","vagina","vaginas","virginity","virgins","wench","wenches","whipped","whiskey","wine","witchcraft"];
	var lowerCaseCheck = stringToCheck.toLowerCase();
	for(var i=0;i<badwords.length;i++) {
		if(lowerCaseCheck.indexOf(badwords[i]) != -1) return false;
	}
	return true;
}

function checkForm(form) {
	var errorList = [];
	if(!form.fname.value) errorList[errorList.length] = "Please enter your first name.";
	if(!form.email.value) errorList[errorList.length] = "Please enter your e-mail address.";
	if(form.email.value && !isValidEmail(form.email.value)) errorList[errorList.length] = "Your e-mail address is not valid.";
	if(!form.ffname.value) errorList[errorList.length] = "Please enter your friend's first name.";
	if(!form.femail.value) errorList[errorList.length] = "Please enter your friend's e-mail address.";
	if(form.femail.value && !isValidEmail(form.femail.value)) errorList[errorList.length] = "Your friend's e-mail address is not valid.";
	// SWITCHED TO PROFANITY MODULE! do profanity check, but only if there aren't already other errors so we can save some processing time
	// if(!errorList.length) {
	// 		if(!profanityCheck(form.fname.value) || !profanityCheck(form.email.value) || !profanityCheck(form.ffname.value) || !profanityCheck(form.femail.value)) 
	// 			errorList[errorList.length] = "Some information may be incorrect or inappropriate. Please try again.";
	// 	}
	
	if(errorList.length > 0) {
		var message = "";
		for(var i=0; i<errorList.length; i++) {
			message += "* " + errorList[i] + "\n";
		}
		alert(message);
		return false;
	}
	return true;
}

function manticoreTrack(pageName) {
	//alert(pageName);
	mtcSetAbsolutePageName(pageName);
	mtcGO();
}