/* Logging */

function log() {
    return window.console && console.log && console.log.apply(console, arguments);
}

/* Parse Comment Data - Fn */
var commentData=(function(){var c=function(a){var b=[],node=a.firstChild;if(!node){return b}do{if(node.nodeType===8){b[b.length]=node}if(node.nodeType===1){b=b.concat(c(node))}}while(node=node.nextSibling);return b},cache=[0],expando='data'+ +new Date(),data=function(a){var b=a[expando],nextCacheIndex=cache.length;if(!b){b=a[expando]=nextCacheIndex;cache[b]={}}return cache[b]};return function(a){a=a||document.documentElement;if(data(a)&&data(a).commentJSON){return data(a).commentJSON}var b=c(a),len=b.length,comment,cData;while(len--){comment=b[len];cData=comment.data.replace(/\n|\r\n/g,'');if(/^\s*?\{.+\}\s*?$/.test(cData)){try{data(comment.parentNode).commentJSON=(new Function('return '+cData+';'))()}catch(e){}}}return data(a).commentJSON||true}})();


/* New jQuery equalHeights plugin
   For equalising column heights on Game-page */

jQuery.fn.equalHeights = (function() {
    
    var _loaded;
    
    /* We monitor the window.onload event
       (Images need to be loaded if images are within collection) */
    jQuery(window).load(function(){
        _loaded = true;
    });
    
    /* Applies the highest element's height (within the collection)
      to all elements within the collection; will use minHeight if available */
    
    var minHeightSupported = (function(){
        var d = $('<div/>').css('minHeight',1).appendTo('body'),
            h = d.height();
        d.remove();
        return +h === 1;
    })();
    
    return function(explicit) {
        var self = this;
        if (!_loaded && $('img', self)[0]) {
            var interval = setInterval(function(){
                if (_loaded) {
                    clearInterval(interval);
                    self.equalHeights(explicit);
                }
            }, 50);
        }
        return this.css(minHeightSupported && !explicit ? 'min-height' : 'height',
            Math.max.apply(null,
                jQuery(jQuery.extend({},this)).map(function(){
                    return jQuery(this).height();
                }).get()
            )
        );
    };
    
})();

/* MouseWheel events interface for jQuery
 * Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);

/* --- */



function ById(id){ return document.getElementById(id); }   

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function TrimString(str){
    var trimmed = str.replace(/^\s+|\s+$/g, '')
    return trimmed;            
}

condition = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
function isValidEmailAdd(someValue) {
    if (condition.test(someValue)) {
        return true;
    } else {
        return false;
    }
}

function isInvalid(startTime){
    var stTime = parseInt(startTime.substring(0,2));	    
    if(stTime < 0 || stTime > 23){
        return true;
    } else {
        return false;
    }
}

function NavigateToHere(objSelect){
    location.href = objSelect.value;
}

$(document).ready(function() {

	/* Rollovers on creatures */
	$("a#animal1").mouseover(function() {
		$("div#quote1").css("display","block");
		$("a#animal1 img").attr("alt", "");
	});
	
	$("a#animal1").mouseout(function() {
		$("div#quote1").css("display","none");
	});
	
	$("a#animal2").mouseover(function() {
		$("div#quote2").css("display","block");
		$("a#animal2 img").attr("alt", "");
	});
	
	$("a#animal2").mouseout(function() {
		$("div#quote2").css("display","none");
	});
	
	$("a#animal3").mouseover(function() {
		$("div#quote3").css("display","block");
		$("a#animal3 img").attr("alt", "");
	});
	
	$("a#animal3").mouseout(function() {
		$("div#quote3").css("display","none");
	});
	
	
	/* ======== day and night time background images /start ================ */		
    if(DayTimeStart == "" || isInvalid(DayTimeStart) || DayTimeStart >= NightTimeStart || isNaN(DayTimeStart)){
        DayTimeStart = "6"; // 6am
    }
    if(NightTimeStart == "" || isInvalid(NightTimeStart) || DayTimeStart >= NightTimeStart || isNaN(NightTimeStart)){
        NightTimeStart = "18"; // 6pm
    }
    DayTimeStart = parseInt(DayTimeStart.substring(0,2),10);
    NightTimeStart = parseInt(NightTimeStart.substring(0,2),10);
    var now = new Date();
    var nowHour = now.getHours();	
    if(nowHour >= DayTimeStart && nowHour < NightTimeStart){
        $("body").css("background-color","#27BBBC");
            $("body").css("background-image","url('/library/images/bg_bodyDay.png')");
            $("body").css("background-repeat","repeat-x");
            $("div#main h1").css("background-image","url('" + HeaderDayImage + "')");
    } else {
            $("body").css("background-color","#117071");
            $("body").css("background-image","url('/library/images/bg_bodyNight.png')");
            $("body").css("background-repeat","repeat-x");
            $("div#main h1").css("background-image","url('" + HeaderNightImage + "')");
            $("div#footer").css("background-color","#117071");
            $("a#share").css("left","591px");
    }
    /* ======== day and night time background images /end ================ */
    
    /* EqualHeights */
    /* NOTE: Footer MUST be done first in order for this to work */
    /* var gameContent = $('#gameContent');
    if (gameContent[0]) {
        gameContent
            .find('div.footer').equalHeights().end()
            .find('div.header').equalHeights();
    } */
        
    $('.leftpanel, .rightpanel', '#center').find('.contentArea').equalHeights(true);
    
    /* Make mouse-scrolling work for flash <object>s */
    $('body').bind('mousewheel', function(e, delta){
        if (e.target.nodeName.toLowerCase() === 'object') {
            var docEl = $(document.documentElement);
            docEl.scrollTop( docEl.scrollTop() + (delta>0?-120:120) )
        }
    });
    
    /* Voting without page refresh; using iFrame much easier than XHR approach */
    $('.htVoteNow :image').each(function(){
        
        var input = $(this);
        var parents = input.parents('.htVoting, .htVideoVoting');
        var form = input.parents('form');
        
        input.click(function(e){
            
            $.get("/voting.aspx",
				{ id: parents.find('.txtVotingId').val(), type: parents.find('.txtVotingType').val(), rand: Math.random() },
			   	function(data) {
					// success assumed
				}, "json"
			);
			
            if (parents.find('.txtVotingType').val() == "tip") {
    			input.animate({opacity:0}, function(){
                    /* Fade and change msg to "thank you" msg */
                    parents.find('.txtArea').animate({
                        opacity: 0
                    }, function(){
                        $(this).html(commentData(input.parent()[0]).successMessage).animate({opacity:1});
                    })
                    
                    var updateBox = parents.find('.htVotesSoFar'),
                        span = updateBox.find('span:first').clone(),
                        innerText = updateBox.text();
                        
                    /* Increment the vote number */
                    updateBox.empty().append(span).append(
                        '' + (parseInt(innerText.match(/\d+/)[0], 10) + 1)
                    );
                    input.css({visibility:'hidden', cursor: 'default'});
                });
            } else {
                $(this).animate({opacity:0});
                $("#voteMessage").animate({opacity:0}, function(){
                    $("#voteMessage").html(commentData(input.parent()[0]).successMessage).animate({opacity:1});
                });
                
                /* update count & hide image */
                $("#htRating").html(parseInt($("#htRating").html()) + 1);
                input.css({visibility:'hidden', cursor: 'default'});
            }
			return false;
        });
        
    });
    
    sharing.init();
});
 
var sharing = function() {
    var _this = {
		fullyLoaded: false,
		tabSwitchingFunction: null,
		easing: 'easeOutQuart',
		scrollSpeed: 7500,
		absoluteTop: 0,
		init : function(bdnShare) {
			//default sharing setup
			var a2aUrl ='http://static.addtoany.com/menu/page.js';
			var linkName = document.title; //Can also be specific string
			var linkUrl = location.href; //Can also be specific URL string
			var linkClick = 1; //Switches menu to appear onclick instead of mouseover
			var showTitle = 0; //Shows the title of the item (from a2a_linkname) within the sharing menu
			var numServices = 5000; //Number of share options to display
			var prioritize = ['faves', 'facebook', 'myspace', 'twitter', 'bebo', 'digg', 'netlog', 'delicious', 'wordpress', 'technorati_favorites', 'yahoo_bookmarks', 'blogger_post']; //Options to prioritise
			var customServices = []; //Customise menu UI ['Example dot com', 'http://www.example.com/add?name=A2A_LINKNAME_ENC&url=A2A_LINKURL_ENC', 'http://www.example.com/images/icon_16x16.png']'
			var colorMain = '24b3bb';
			var colorBorder = '86abad';
			var colorLinkText = '5091bb';
			var colorLinkTextHover = 'ffffff';

			bdnShare = (bdnShare && typeof bdnShare == 'object') ? bdnShare : {};
			a2a_linkname = (bdnShare.linkName) ? bdnShare.linkName : linkName;
			a2a_linkurl = (bdnShare.linkUrl) ? bdnShare.linkUrl : linkUrl;
			a2a_track_links='a2a'; //Activate tracking
			a2a_onclick = (bdnShare.linkClick) ? bdnShare.linkClick : linkClick;
			a2a_show_title = (bdnShare.showTitle) ? bdnShare.showTitle : showTitle;
			a2a_num_services = (bdnShare.numServices) ? bdnShare.numServices : numServices;
			a2a_prioritize = (bdnShare.prioritize) ? bdnShare.prioritize : prioritize;
			a2a_custom_services = (bdnShare.customServices) ? bdnShare.customServices : customServices;
			a2a_color_main = (bdnShare.colorMain) ? bdnShare.colorMain : colorMain;
			a2a_color_border = (bdnShare.colorBorder) ? bdnShare.colorBorder : colorBorder;
			a2a_color_link_text = (bdnShare.colorLinkText) ? bdnShare.colorLinkText : colorLinkText;
			a2a_color_link_text_hover = (bdnShare.colorLinkTextHover) ? bdnShare.colorLinkTextHover : colorLinkTextHover;
			a2a_color_bg = 'bbe9e9';
			a2a_hide_embeds = (bdnShare.hideEmbeds) ? bdnShare.hideEmbeds : (!navigator.userAgent.match('MSIE')) ? 1 : 0;

			if ($('#a2aPage').length === 0) { //if Script reference doesn't already exist then create
				$('body').append('<script type="text/javascript" id="a2aPage" src="' + a2aUrl + '"></script>');
			}
			sharing.pollForShareCompletion();
		},
		pollForShareCompletion : function() {
			/*
				Waits for all the external A2A code to load, and then additionally, their HTML to be
				appended to the page. Once done, set the hdp.sharing.fullyLoaded boolean to true
				and call hdp.sharing.shareFullyLoaded().
					We do this because we need to modify their content once delivered to the page.
				
				NOTE: Only do this once, in case init is called a second time with different params.
			*/
			if (!sharing.fullyLoaded) {
				if ($('#a2apage_cols_container').length) {
					sharing.fullyLoaded = true;
					sharing.shareFullyLoaded();
				} else {
					setTimeout(function() { sharing.pollForShareCompletion(); }, 500);
				}
			}
		},
		shareFullyLoaded : function() {
			if (sharing.fullyLoaded !== true) { return; }

			// Cufon
			if (typeof(Cufon) != 'undefined') { Cufon.replace('#a2apage_dropdown a', { fontFamily: 'Futura Condensed Medium' }); }

			// So we can stop the left / right position of the box changing depending on the user's
			// screen resolution, wrap their outer-most DIV in one of our own that's the right width.
			$('#a2apage_dropdown').parent().wrap('<div id="a2apage_container_outer"></div>');
			
			// Because the content can vary in height (e.g. Disclaimer page), move the whole
			// shebang into the footer element so we're always displaying with the share button
			$('#main').prepend($('#a2apage_container_outer'));

			// While we could add onclick events to the tabs to detect switching, their code
			// calls the tab switching function internally as well, which we need to trap
			sharing.tabSwitchingFunction = a2a.tabs;
			a2a.tabs = sharing.tabSwitched;

			// Enable smooth scrolling by default (because 'share' panel is the default panel)
			sharing.enableSmoothScroll();

            // add class around tabs for styling
            $('.a2apage_wide:first').addClass('a2apage_wide_tabs');

			// Wrap their table in a DIV that we can control the height of the scrollable section
			$('#a2apage_cols_container').wrap('<div id="a2apage_cols_container_outer"></div>');

			// Add smooth scrolling up and down arrows before and after that DIV
			$('#a2apage_cols_container_outer').before('<a id="a2apage_smooth_scroll_up" class="a2apage_smooth_scroll_button" href="javascript:void(0);"><img src="/library/images/share/clear.gif" class="a2a_i_uarr" alt="Scroll up"/></a>').after('<a id="a2apage_smooth_scroll_down" class="a2apage_smooth_scroll_button" href="javascript:void(0);"><img src="/library/images/share/clear.gif" class="a2a_i_darr" alt="Scroll down"/></a>');
			$('div.a2a_tabs:last-child').after('<div class="a2a_close">&nbsp;</div>');
			$('div.a2a_close').bind('click',function(e) { a2a.toggle_dropdown('none',a2a.type); });

			$('#a2apage_smooth_scroll_up').bind('mousedown', function(e) {
			    e.preventDefault(); sharing.scrollUp(e);
			}).bind('mouseup', function(e) {
				e.preventDefault(); sharing.stopScroll(e);
			}).bind('click', function(e) {
				e.preventDefault();
			});

			$('#a2apage_smooth_scroll_down').bind('mousedown', function(e) {
				e.preventDefault(); sharing.scrollDown(e);
			}).bind('mouseup', function(e) {
				e.preventDefault(); sharing.stopScroll(e);
			}).bind('click', function(e) {
				e.preventDefault();
			});

			$('#a2apage_find').bind('keydown', sharing.resultsFiltered);
		},
		resultsFiltered : function() {
			// When filtering the list, jump it back to the top
			$('#a2apage_cols_container').css('top', '0px');
		},
		tabSwitched : function(tabName, showNote) {
			$('#a2apage_cols_container').css('top', '0px');		// Not done in CSS as we only want to do it on tab switch
			if (tabName == 'DEFAULT') {
				sharing.enableSmoothScroll();
			} else {
				sharing.disableSmoothScroll();
			}
			return sharing.tabSwitchingFunction(tabName, showNote);
		},
		enableSmoothScroll : function() {
			$('#a2apage_dropdown').addClass('show_smooth_scroll_buttons');
		},
		disableSmoothScroll : function() {
			$('#a2apage_dropdown').removeClass('show_smooth_scroll_buttons');
		},
		scrollUp : function(e) {
			$('#a2apage_cols_container').animate({ top:0 }, sharing.scrollSpeed, sharing.easing);
		},
		scrollDown : function(e) {
		    a2aContainer = $('#a2apage_cols_container');
			if(!sharing.absoluteTop) {

    			// We can only determine the height of their table once it has been shown
				sharing.absoluteTop = a2aContainer.parent().height() - a2aContainer.height();
			}

			a2aContainer.animate({ top:sharing.absoluteTop + 'px' }, sharing.scrollSpeed, sharing.easing);
		},
		stopScroll : function(e) {
			$('#a2apage_cols_container').stop();
		}
	};
    return _this;
}();

function changeMonsterImage(obj, isCurrent, imgSrc) {
    if (isCurrent == "True") return;
    $(obj).attr("src", imgSrc);
}