var NoAdsToAdd = 0;
var WPShown = 0;
var WPPeriod = 0;

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.target = "_blank";  
 }  
}  

// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
// as an argument, and the collection as `this`


$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load.imgloaded',function(){
      if (--len <= 0 && this.src !== blank){
        elems.unbind('load.imgloaded');
        callback.call(elems,this);
      }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }
  });

  return this;
};



jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});

/** jQuery-Plugin "preloadCssImages" **/

;jQuery.preloadCssImages = function(settings){
	settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null,
		errorDelay: 999, // handles 404-Errors in IE
		simultaneousCacheLoading: 2
	}, settings);
	var allImgs = [],
		loaded = 0,
		imgUrls = [],
		thisSheetRules,	
		errorTimer;
	
	function onImgComplete(){
		clearTimeout(errorTimer);
		if (imgUrls && imgUrls.length && imgUrls[loaded]) {
			loaded++;
			if (settings.statusTextEl) {
				var nowloading = (imgUrls[loaded]) ? 
					'Now Loading: <span>' + imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length - 1] : 
					'Loading complete'; // wrong status-text bug fixed
				jQuery(settings.statusTextEl).html('<span class="numLoaded">' + loaded + '</span> of <span class="numTotal">' + imgUrls.length + '</span> loaded (<span class="percentLoaded">' + (loaded / imgUrls.length * 100).toFixed(0) + '%</span>) <span class="currentImg">' + nowloading + '</span></span>');
			}
			if (settings.statusBarEl) {
				var barWidth = jQuery(settings.statusBarEl).width();
				jQuery(settings.statusBarEl).css('background-position', -(barWidth - (barWidth * loaded / imgUrls.length).toFixed(0)) + 'px 50%');
			}
			loadImgs();
		}
	}
	
	function loadImgs(){
		//only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...)
		// otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads
		if(imgUrls && imgUrls.length && imgUrls[loaded]){
			var img = new Image(); //new img obj
			img.src = imgUrls[loaded];	//set src either absolute or rel to css dir
			if(!img.complete){
				jQuery(img).bind('error load onreadystatechange', onImgComplete);
			} else {
				onImgComplete();
			}
			errorTimer = setTimeout(onImgComplete, settings.errorDelay); // handles 404-Errors in IE
		}
	}
	
	function parseCSS(sheets, urls) {
		var w3cImport = false,
			imported = [],
			importedSrc = [],
			baseURL;
		var sheetIndex = sheets.length;
		while(sheetIndex--){//loop through each stylesheet
			
			var cssPile = '';//create large string of all css rules in sheet
			
			if(urls && urls[sheetIndex]){
				baseURL = urls[sheetIndex];
			} else {
				var csshref = (sheets[sheetIndex].href) ? sheets[sheetIndex].href : 'window.location.href';
				var baseURLarr = csshref.split('/');//split href at / to make array
				baseURLarr.pop();//remove file path from baseURL array
				baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
				if (baseURL) {
					baseURL += '/'; //tack on a / if needed
				}
			}
			if(baseURL != "http://www.malifaux.com/AjaxMail/") {
				if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){
					thisSheetRules = (sheets[sheetIndex].cssRules) ? //->>> http://www.quirksmode.org/dom/w3c_css.html
						sheets[sheetIndex].cssRules : //w3
						sheets[sheetIndex].rules; //ie 
					var ruleIndex = thisSheetRules.length;
					while(ruleIndex--){
						if(thisSheetRules[ruleIndex].style && thisSheetRules[ruleIndex].style.cssText){
							var text = thisSheetRules[ruleIndex].style.cssText;
							if(text.toLowerCase().indexOf('url') != -1){ // only add rules to the string if you can assume, to find an image, speed improvement
								cssPile += text; // thisSheetRules[ruleIndex].style.cssText instead of thisSheetRules[ruleIndex].cssText is a huge speed improvement
							}
						} else if(thisSheetRules[ruleIndex].styleSheet) {
							imported.push(thisSheetRules[ruleIndex].styleSheet);
							w3cImport = true;
						}
						
					}
				}
			}
			//parse cssPile for image urls
			var tmpImage = cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename" / '"' for opera-bugfix
			if(tmpImage){
				var i = tmpImage.length;
				while(i--){ // handle baseUrl here for multiple stylesheets in different folders bug
					var imgSrc = (tmpImage[i].charAt(0) == '/' || tmpImage[i].match('://')) ? // protocol-bug fixed
						tmpImage[i] : 
						baseURL + tmpImage[i];
					
					if(jQuery.inArray(imgSrc, imgUrls) == -1){
						imgUrls.push(imgSrc);
					}
				}
			}
			
			if(!w3cImport && sheets[sheetIndex].imports && sheets[sheetIndex].imports.length) {
				for(var iImport = 0, importLen = sheets[sheetIndex].imports.length; iImport < importLen; iImport++){
					var iHref = sheets[sheetIndex].imports[iImport].href;
					iHref = iHref.split('/');
					iHref.pop();
					iHref = iHref.join('/');
					if (iHref) {
						iHref += '/'; //tack on a / if needed
					}
					var iSrc = (iHref.charAt(0) == '/' || iHref.match('://')) ? // protocol-bug fixed
						iHref : 
						baseURL + iHref;
					
					importedSrc.push(iSrc);
					imported.push(sheets[sheetIndex].imports[iImport]);
				}
				
				
			}
		}//loop
		if(imported.length){
			parseCSS(imported, importedSrc);
			return false;
		}
		var downloads = settings.simultaneousCacheLoading;
		while( downloads--){
			setTimeout(loadImgs, downloads);
		}
	}
	parseCSS(document.styleSheets);
	return imgUrls;
};

/* JQuery Cookies */

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* jQuery Highlight */


jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};


	
	function setScreenClass() {
		var fmt = document.documentElement.clientWidth;
		$("body").removeClass();
		if (fmt < 1580) { $("body").addClass("LT1580")} ;
		if (fmt >= 1200) { $("body").addClass("MT1200")} ;
		if (fmt <= 1050) {
			$("#MainPanel").css("min-height", "0px");
			$("body").addClass("LT1050");
		} 
		if (fmt <= 940) { $("body").addClass("LT940") };
		if (fmt <= 800) { $("body").addClass("LT800")} ;
		
		$("#map-container AREA, #map-container .mapHighlight").mouseover(function(){
			var regionMap = '.Map'+$(this).attr('alt');
			$(".mapHighlight.Link" + $(this).attr('alt')).addClass("Hovered");
			jQuery(regionMap).css('display', 'block');
		});
		
		$("#map-container AREA, , #map-container .mapHighlight").mouseout(function(){
			var regionMap = '.Map'+$(this).attr('alt');
			$(".mapHighlight.Link" + $(this).attr('alt')).removeClass("Hovered");
			jQuery(regionMap).css('display', 'none');
		});
				

		$(".Sepiadiv").mouseover(	function(){
			$(this).find("img.Sepia").stop().animate({opacity:0}, 500);

		});
		
		 $(".Sepiadiv").mouseout(	function(){
			$(this).find("img.Sepia").stop().animate({opacity:1}, 2000);

		});
		
		$("#WNY").mouseover(	function(){
			$(this).find("img.Sepia").stop().animate({opacity:0}, 150);

		});
		
		 $("#WNY").mouseout(	function(){
			$(this).find("img.Sepia").stop().animate({opacity:1}, 250);

		});
		
		
		extraStuff();
		
		$('#Needs').removeClass();
		if ( $('#Needs').width() > 1050) {
			$('#Needs').addClass("Col4");
		}			
		else if ( $('#Needs').width() > 820 ) {
			$('#Needs').addClass("Col3");
		}
		else {
			$('#Needs').addClass("Col2");
		}
	};



function extraStuff() {

}
	
	window.onresize = function(){setScreenClass();};

	
	
function MakeColumns() {

	if (!($('#MainWrapper').hasClass("FullPage"))) {
		$('#SmallPanelBar ').columnize({ width: 280, lastNeverTallest: false, isMySpecial: true});	
	}
	setScreenClass();
}	
	
$(document).ready(function(e){
	$(".LinkDiv, #WallpaperBox, #MultiBar .Content, #Downloads #MultiBar .SectionBlock, #crew_box, .BoxSet, .IndexModule .InnerBlock, .NeedObj .InnerBlock, #MalifauxMap").prepend('<div class="Border"><div class="Middle"><div class="Left"></div><div class="Right"></div></div><div class="Top"><div class="Left"></div><div class="Right"></div></div><div class="Bottom"><div class="Left"></div><div class="Right"></div></div></div>');
	
	$(".Product.ComingSoon").each(function() {
			$(this).find(".Sepiadiv").prepend('<img class="ComingSoon" src="FrontPage/Images/ComingSoon.png">');
		});
	
  setScreenClass();
  $.preloadCssImages();

	setInterval(function() {
		if (WPPeriod == 0) {
			RaiseWP();
		}
		else {
			WPPeriod -- ;
		}
	}, 1000)
  
			$("#MalifauxMap area").mouseover(function(){
				var regionMap = '.Map'+$(this).attr('alt');
				jQuery(regionMap).css('display', 'block');
				$("#MapPage #HoverOver").html($(this).attr('title'));
			});
			
			$("#MalifauxMap area").mouseout(function(){
				var regionMap = '.Map'+$(this).attr('alt');
				jQuery(regionMap).css('display', 'none');
				$("#MapPage #HoverOver").html("");
			});
  
	$("li.toplevel a img.SecImg").mouseover(	function(){
		var CurrentImg = $(this).attr("src").split(".png")[0];
		$(this).attr("src" , CurrentImg + "Hover.png");
	});
	
	 $("li.toplevel a img.SecImg").mouseout(	function(){
		var CurrentImg = $(this).attr("src").split("Hover.png")[0];
		$(this).attr("src" , CurrentImg + ".png");
	});
	$(".LinkDiv").addClass("dontsplit");
	$("#ToColumns p").prepend("<span class='indent'></span>");
	$("#ToColumns").wrap("<div id='ToCopy' />");
	$("#ToCopy").append("<div id='CopiedColumn'>" + $("#ToColumns").html() + "</div>")
	$("#ToColumns").unwrap();
	$('#CopiedColumn').addClass($("#ToColumns").attr("class"));
	// $('#CopiedColumn ').columnize({ lastNeverTallest: true, Columns : 2, buildOnce : true});	
	if ($('#MainWrapper').hasClass("FullPage")) {
		$('#ToColumns').columnize({ width: 350, NeverSolo: true, MaxColumn : 4 });
		$('#CopiedColumn').columnize({ columns : 2, buildOnce : true });
	}	
	else {

		$('#ToColumns').columnize({ width: 350, NeverSolo: true, MaxColumn : 3 });
		$('#CopiedColumn').columnize({ columns : 3, buildOnce : true });
	}	
	$('#CopiedColumn').addClass("Hidden");
		MakeColumns()

}); 


function LowerWP() {
	WPPeriod = 5;
	backWP();
}

function backWP() {
	if (WPShown > 0) {
		$('.Wallpaper').removeClass('Display LeftWP RightWP');
		WPShown --;
		$('.Wallpaper:eq(' + WPShown + ')' ).addClass('Display LeftWP');
		$('.Wallpaper:eq(' + ( WPShown + 1 ) + ')' ).addClass('Display RightWP');
	}

	else if (WPShown == 0) {
		$('.Wallpaper').removeClass('Display LeftWP RightWP');
		WPShown = $('.Wallpaper').length - 1  ;
		$('.Wallpaper:eq(' + WPShown + ')' ).addClass('Display LeftWP');
		$('.Wallpaper:eq(' + 0 + ')' ).addClass('Display RightWP');
	}
}

function RaiseWP() {
	WPPeriod = 5;
	forwardWP();
}

function forwardWP() {
	if (WPShown < $('.Wallpaper').length - 2 ) {
		$('.Wallpaper').removeClass('Display LeftWP RightWP');
		WPShown ++;
		$('.Wallpaper:eq(' + WPShown + ')' ).addClass('Display LeftWP');
		$('.Wallpaper:eq(' + ( WPShown + 1 ) + ')' ).addClass('Display RightWP');
	}
	else if (WPShown == $('.Wallpaper').length - 2 ) {
		$('.Wallpaper').removeClass('Display LeftWP RightWP');
		WPShown = $('.Wallpaper').length - 1  ;
		$('.Wallpaper:eq(' + WPShown + ')' ).addClass('Display LeftWP');
		$('.Wallpaper:eq(' + 0 + ')' ).addClass('Display RightWP');
	}
	else  if (WPShown == $('.Wallpaper').length - 1 ) {
		$('.Wallpaper').removeClass('Display LeftWP RightWP');
		WPShown = 0  ;
		$('.Wallpaper:eq(' + WPShown + ')' ).addClass('Display LeftWP');
		$('.Wallpaper:eq(' + ( WPShown + 1 ) + ')' ).addClass('Display RightWP');
	}
}

function GotoWallPaper(WPNum) {
		WPPeriod = 2;
		WPShown = WPNum;
		$('.Wallpaper').removeClass('Display LeftWP RightWP');
		$('.Wallpaper:eq(' + WPShown + ')' ).addClass('Display LeftWP');
		$('.Wallpaper:eq(' + ( WPShown + 1 ) + ')' ).addClass('Display RightWP');
}


