/**
* @author james
* Use this file for common javascript stuff
*/

// browser var
var browserName = navigator.appVersion;
var ieBrowserVersion = parseFloat(browserName.split('MSIE')[1]);

// some vars
var reordering = false;  // state variable for whether or not the nav is being sorted by the couple

jQuery(document).ready(function() {
	activateTooltips();
	activateSuggestions();
	swapThumbnails();
	
	jQuery('body').addClass('ready');
	
	activeClickOnEmbeds();
	setupLeadly();
	activateSelectOnTextareas();
	checkForBadge();
	checkForLeadlyReferrer();
});


/**
* Loop through div and close message divs
*/

// ?!?!!
var allPageTags = new Array();
function hideFlash()
{
    var theClass = 'message';
    var allPageTags=document.getElementsByTagName("div");

    for (i=0; i<allPageTags.length; i++)
    {
        if (allPageTags[i].className==theClass)
        {
            allPageTags[i].style.display='none';
        }
    }
}

// redirect if google or some source has linked to the 
function redirectIfInFrame()
{
	var referrer = '';
	try {
		var referrer = String(window.top.document.referrer);
	} catch(e) {}
	
	try {
		var url = String(window.location);
		if(url.match(/[\?&]is_framed/) &&
			window.top == window &&
			referrer &&
			!referrer.match(/nearly(dev|weds)/))
		{
			var loadUrl = url.replace(/([?&])is_framed/, '$1');
			window.location = loadUrl;
		}
	} catch(e) {}
}

function showTemplateSelector() {
    var f=$('tform'); f.style.display=(f.style.display=='block'?'none':'block');
    void 0;
}

function hideTemplateSelector() {
    document.getElementById('toolbar').style.display = "block";
    document.getElementById('show_toolbar').style.display = "none";
     document.body.style.paddingTop="85px";
}

function removeText(node) {
    if (node != null) {
        if (node.childNodes) {
            for(var i=0; i < node.childNodes.length; i++) {
                var oldTextNode = node.childNodes[i];
                if(oldTextNode.nodeValue != null) {
                    node.removeChild(oldTextNode);
                }
            }
        }
    }
}

function appendText(node, text) {
    var newTextNode = document.createTextNode(text);
    node.appendChild(newTextNode);
}

function setText(node, text) {
    removeText(node);
    appendText(node, text);
}

function getGroupOrder(classname, hiddenname) {
    var sections = document.getElementsByClassName(classname);  //gets a list of everything that has an item tag
    var alerttext = '';
    for(var i=1; i<=sections.length; i++) {
        var sectionID = sections[i-1].id; //the id of the indvidual medal
        var order = Sortable.serialize(sectionID);
        if(i!=sections.length) {
            alerttext += sectionID +'&';
        } else {
            alerttext += sectionID;
        }
    }
    document.getElementById(hiddenname).value=alerttext;  //set the value of our hiddentext area
    return alerttext;
}

if( typeof( Array.prototype.push ) == 'undefined' )
{
     Array.prototype.push = function(value) {
        this[ this.length ] = value;
    };
}

function killElement(id,parentID)
{
    /* detroys an element, usually created by dlgPop */
    id = document.getElementById(id);
    if (id) {
        if (parentID) document.getElementById(parentID).removeChild(id);
        else document.body.removeChild(id);
    }
}


/* ajax visual loader ("loading..", "upadting..", "canceling..") functions */
function showLoading(div, loaderType,w,h){
	// just calling the new loader.  replace/kill showLoading as you come to it!
	showLoader();
}

function hideLoading(div, loaderType) {
	// just calling the new loader.  replace/kill hideLoading as you come to it!
	hideLoader();
}

function hideMp3FileSelector() {
    try {
        var selector = document.getElementById('mp3UploadFileSelector');
        var delbox = document.getElementById('mp3DeleteBox');
        if(delbox.checked) {
            selector.style.display = "none";
        } else {
            selector.style.display = "block"
        }
    } catch (e) {
        //alert(e);
    }
}

function hideLegFileSelector() {
    try {
        var selector = document.getElementById('legPhotoUpload');
        var delbox = document.getElementById ('legDelPhoto');
        if(delbox.checked) {
            selector.style.display = "none";
        } else {
            selector.style.display = "block"
        }
    } catch (e) {
        //alert(e);
    }
}

function compareFields(type) {
	if(type == 'email')
	{
		var pw1 = document.getElementById('u_email1');
		var pw2 = document.getElementById('u_email2');
		var mess = 'Your email addresses do not match';
	}
	else if(type == 'password')
	{
		var pw1 = document.getElementById('u_password1');
		var pw2 = document.getElementById('u_password2');
		var mess = 'Your passwords do not match';
	}
	else
		return true;

    if(pw1.value != pw2.value) {
        alert(mess);
        pw2.focus();
        return false;
    } else {
        return true;
    }
}

function checkCpEmail()
{
    var em1 = document.getElementById('u_email1');
    var em2 = document.getElementById('u_email2');
    if(pw1.value != pw2.value) {
        alert('Your passwords do not match');
        pw2.focus();
        return false;
    } else {
        return true;
    }
}

/* nav bar / navigation code */
saveSortOrder_nav = function() {
	showLoader('<img src="/images/icons/ajax-loader.gif" alt="Saving..."/> Saving...');
	document.getElementById('sorted').value = Sortable.serialize('siteNav'); 
	$('navorder').request({
	  onComplete: function(transport){
		hideLoader();
		$('navbar').replace(transport.responseText); 
		}
	});
}

saveSortOrder_posts = function() {
	showLoader('<img src="/images/icons/ajax-loader.gif" alt="Saving..."/> Saving...');
	document.getElementById('posts_sort').value = Sortable.serialize('posts'); 
	$('postorder').request({
	  onComplete: function(transport){ 
		//$('posts').replace(transport.responseText); 
		hideLoader();
		}
	});
}

saveSortOrder_photos = function() {
	document.getElementById('photos_sort').value = Sortable.serialize('photogallery'); 
	$('photoorder').request({
	  onComplete: function(transport){ 
		//$('posts').replace(transport.responseText); 
		}
	});
}

resortNav = function(which) {
	if (!which) which = "show";
	
	if (which == "show") {
		for (i=0; i < $$('#siteNav .handle').length; i++) {
			$$('#siteNav .handle')[i].style.display = 'block';
		}
		
		$('nav_reorder_done').style.display = 'block';
		$('nav_reorder').style.display = 'none';
		
		reordering = true;
		
	} else {
		
		$('nav_reorder_done').style.display = 'none';
		$('nav_reorder').style.display = 'block';
		
		for (i=0; i < $$('#siteNav .handle').length; i++) {
			$$('#siteNav .handle')[i].style.display = 'none';
		}
		
		reordering = false;
	}

}

addPageInitial = function() {
	Lightview.show({
	    href: '/features/add',
	    rel: 'ajax',
		title: 'Add a New Page - Choose Page Type',
	    options: {
			topclose: true,
			autosize: false,
			width: 520,
			height: 470,
			ajax: {
				method: 'get',
				evalScripts: true
	      }
	    }
	  });
}

addPageSecondary = function(featureType) { 
	Lightview.show({
	    href: '/features/add?featureType=' + featureType + (String(document.location).indexOf('is_framed') != -1 ? '&is_framed' : ''),
	    rel: 'ajax',
		title: 'Add a New Page to Your Site',
	    options: {
			topclose: true,
			autosize: true,
			ajax: {
				method: 'get',
				evalScripts: true
	      }
	    }
	  });
}

customCSS = function(reg_id) {
	Lightview.show({
			href: '/registries/customcss/' + reg_id + '?rand=' + Math.random() + (String(document.location).indexOf('is_framed') != -1 ? '&is_framed' : ''),
	    rel: 'ajax',
	    title: 'Add Custom CSS',
	    options: {
	      autosize: false,
	      topclose: true,
		  width: 350,
		  height: 350,
	      ajax: {
	        method: 'get',
	        evalScripts: true
	      }
	    }
	  });
}

// currently overloaded to do page title editing and landing page general edits
// TODO: handle landing page appropriately
function editPageTitle(url, title, isLandingPage) {
	if(typeof(title) != 'string')
		title = 'Edit Page Title';
	
	if(typeof(isLandingPage) != 'boolean')
		isLandingPage = false;
	
	if(url.indexOf('?') != -1)
		url += '&rand=' + Math.random();
	else
		url += '?rand=' + Math.random();
	
	Lightview.show({
	    href: url,
	    rel: 'ajax',
		title: title,
	    options: {
			topclose: true,
			autosize: false,
			width: 500,
			height: (isLandingPage ? 500 : 170),
			ajax: {
				method: 'get',
				evalScripts: true
	      }
	    }
	  });
}

function toggleMinipics() {
	$('posts_container').toggleClassName('minipics');	
	var make_minipics = $$('.entryphoto .lightview img');
	
	// modify the thumbnail to be the larger image, for preview benefit
	// only making the small image be the larger one when toggling minipics off
	// no benefit to doing the reverse since this is just a temporary preview
	for ( var i in make_minipics ) {
		if ( make_minipics[i].src ) var src = make_minipics[i].src;
		if ( src ) var tmb_index = src.indexOf('tmb_');
		if ( src && tmb_index != -1 ) {
			make_minipics[i].src = src.substring(0, tmb_index) + src.substr(tmb_index+4);
		}
	}
}



// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function alphaNumericOnly(e)
{
	var key;
	var keychar;

	if (window.event) {
		key = window.event.keyCode;
		var shiftPressed = window.event.shiftKey;
	} else if (e) {
		key = e.which;
		var shiftPressed = e.shiftKey;
	} else 
		return true;
	var shiftPressed = true;
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();

	// control keys
	if ( (key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) || 
		(key==35) || (key==36) || (key==37) || (key==38) || (key==39) || (key==40) || 
		(key==45) || (key==46)	)
		return true;	
	else if  ((key >  57  && key <  65)  ||  (key >  90  && key <  96) ||  (key==111) ||  (key==106))
	{
		return false;
	}
	// alphas and numbers
	else if (shiftPressed && (("0123456789").indexOf(keychar) > -1))
		return false;
	else if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) > -1))
		return true;
	else
		return false;
	   
}

function removeBadChars(text) {
	return text.replace(/[^a-zA-Z0-9\-]+/, '');
}

function enforceCharLimits() {
	// wildly inaccurate since text fields in IE all report back that their 'size' attribute == 20
	if(jQuery.browser.msie && jQuery.browser.version <= 7)
		return;
	
	jQuery('input[size]').keypress(checkCharLimit);
}

function addTemplateNameToLinks(templateName) {
	var links = document.getElementsByTagName('a');
	for (i=0;i<links.length;i++) {
		if ( typeof links[i] != 'undefined' && typeof links[i].href != 'undefined' && !$(links[i]).hasClassName('lightview') ) links[i].href += "/?template="+templateName;
	}
}

// Adds the 'is_framed' query param to forms and links
function addFramedToLinksAndForms()
{
	jQuery('a,form').each(function(i) {
		var self = jQuery(this);
		var attrName = this.tagName == 'A' ? 'href' : 'action';
		var attr = self.attr(attrName);
		
		// add to UGC links to prevent outbound links from staying within the frame
		if(this.tagName == 'A' && self.attr('rel') == 'nofollow' && self.attr('target') != '_blank')
		{
			self.attr('target', '_top');
			return;
		}
		
		// number of reasons why the param wouldn't be added to the link/form
		if(self.attr('rel') == 'nofollow' || 
			self.parents('#footer').length || 
			self.parents('#toolbar').length ||
		 	attr.indexOf('is_framed') != -1 || 
		 	attr.indexOf('void') != -1 ||
		 	self.hasClass('no_is_framed') ||
		 	self.attr('target') == '_top')
			return;
		
		if(!attr)
			attr = '?is_framed';
		else
		{
			if(attr.indexOf('?') == -1)
				attr += '?';
			else
				attr += '&';
			attr += 'is_framed';
		}
		
		self.attr(attrName, attr);
	});
}

/* used to globally limit the character length of a field by checking its HTML size parameter.  */
function checkCharLimit(obj) {
	if(!obj && this && this != window);
		obj = this;
		
	
	
	if (obj && !jQuery(obj).attr('nocharlimit')) {
		if (obj.size && obj.size > 0) {
			if (obj.value.length > obj.size) obj.value = obj.value.substr(0, obj.size-1);
		}
	}
}


function iebug() { $('body').style.paddingBottom = '300px';}

CkEditors = [];
Event.observe(document, 'lightview:opened', function(event) {
	
	var config = {
		height: 150,
		resize_enabled: false,
		toolbar:
		[
			['FontSize','Font','TextColor','Bold','Italic','-','Link','Unlink','ImageButton','-','Indent','Outdent'],
			['NumberedList','BulletedList','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','RemoveFormat','PasteFromWord','Source','MediaEmbed']
		]
	};

	function ckCallback(ta) {
		this.on('insertHtml', function(e) {
			if(e && typeof(e.data) == 'string' && e.data.match(/name="ProgId" content="Word\.Document"/))
			{
				alert("Whoa there! We detected some jumbled formatting from your MS Word text paste. Please copy text in without formatting then use the editor we provide for formatting. Thanks!");
			}
		});
	}
	
	jQuery('textarea').filter(function() {
		if(jQuery(this).hasClass('no_nic'))
			return false;
		return true;
	}).ckeditor(ckCallback, config);
	
	
	activateTooltips();
});

Event.observe(document, 'lightview:hidden', function() {
	if(CKEDITOR.instances)
	{
		for(var i in CKEDITOR.instances)
			CKEDITOR.remove(CKEDITOR.instances[i]);
	}
})

function position_nav() {
	var offsets = $('siteNav').positionedOffset();

	if ( offsets[1] < 50 ) {
		$('siteNav').style.top = '50px';
	var offsets = $('siteNav').positionedOffset();
	}

	var navOptions = $('nav_options');
	if(navOptions)
	    navOptions.setStyle({'left': eval(offsets[0])+'px', 'top': eval(offsets[1])+'px', 'display': 'block'});
}

function showLoader(msg) {
	if (!msg) 
		msg = '<img src="/images/icons/ajax-loader.gif" alt="Loading..."/> Loading...';
	
	var loader_msg = $$('#loader.interface_box .content_container .content')[0];
	loader_msg.innerHTML = msg;
	
	var leftIndent = eval(document.viewport.getWidth() / 2 - $$('#loader.interface_box .content_container .content')[0].getWidth() / 2 )+"px";
	jQuery('#loader').css({'display': 'block', 'left': leftIndent});
	
	new Effect.Morph('loader', {
	  style: 'bottom: -17px;',
	  duration: 0.3
	});
}

function hideLoader() {
	
	var leftIndent = eval(document.viewport.getWidth() / 2 - $$('#loader.interface_box .content_container .content')[0].getWidth() / 2 )+"px";
	$$('#loader')[0].style.left = leftIndent;
	
	new Effect.Morph('loader', {
	  style: 'bottom: '+eval( -67 - ($$('#loader.interface_box .content_container .content')[0].getHeight()) ) +'px;',
	  duration: 0.3
	});
	
	activateTooltips();
	activateSuggestions();
}
// TODO: kill all refs to this function, then kill this function
function addNote() {}

function activateTooltips() {
	$$('.help').each(function(element) {
		if ($(element).readAttribute('help')) 
		{
			var classname = 'default', cls;
			if((cls = $(element).readAttribute('protoclass')))
				classname = cls;
			new Tip(element, $(element).readAttribute('help'), {
				hideOn: 'mouseout',
				delay: 0,
				border: 3,
				radius: 3,
				offset: { x: 12, y: 12 },
				borderColor: '#f99e1c',
				className: classname
			});
		}
	});	
}

var Suggest = new Array();
var SuggestIndexes = new Array();

function activateSuggestions() {
	$$('.suggest').each(function(element) {
		if ( $(element).readAttribute('suggestions') ) {
			Suggest[ $(element).readAttribute('id') ] = $(element).readAttribute('suggestions').split(",");
			SuggestIndexes[ $(element).readAttribute('id') ] = 1;
		}
	});	
}

function suggest(id)
{
	var input_id = id.substr(8);
		$( input_id ).value = Suggest[ id ][ SuggestIndexes[ id ] ];
		SuggestIndexes[ id ]++;
		if ( SuggestIndexes[ id ] == Suggest[ id ].length ) SuggestIndexes[ id ] = 0;
}


/* cookie code:  thanks to http://www.exit404.com/2005/57/unobtrusive-persistant-scriptaculous-effects  !! */
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = ";expires="+date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = name+"="+value+expires+";path=/";
}

function readCookie(name) {
	var needle = name + "=";
	var cookieArray = document.cookie.split(';');
	for(var i=0;i <cookieArray.length;i++) {
		var pair = cookieArray[i];
		while (pair.charAt(0)==' ') {
			pair = pair.substring(1, pair.length);
		}
		if (pair.indexOf(needle) == 0) {
			return pair.substring(needle.length, pair.length);
		}
	}
	return null;
}

/** TODO: change this to accept an element and open its parent */
function openComments(id) {
	if ($(id+'_comments')) $(id+'_comments').style.display = "block";
	//if ($(id+'_hideComments')) $(id+'_hideComments').style.display = "block";
	if ($(id+'_showComments')) $(id+'_showComments').style.display = "block";
}


/**
 * Map flash js
 * @dependency jquery 1.3+
 */
FlashMap = function() {
	this.init();
};

FlashMap.prototype = {
	
	
	overlayVisible: false,
	
	// state : map has been clicked, prevents multiple click listeners attached to dom layers from
	// registring a click more than once
	mapHasBeenClicked: false,

	flashZoomWasntOne: false,
	
	// get flash movie object
	flashMovie: null,
	
	posx: null,
	posy: null,
	zoomsValue: null,
	
	ie_mapXOffset: 0,
	ie_mapYOffset: 0,
	
	init: function() 
	{
		this.addEventListeners();
	},
	
	addEventListeners: function()
	{
		var self = this;
		
		// listen for zoom for benefit of map
		// requires jquery because using jquery to store the current zoom in window as a data object
		jQuery(document).ready(function() {
			
			jQuery(window).bind('onFlashZoom', function(e) { self.onMapFlashZoom(e); });
			setTimeout(function() { self.onMapFlashZoom()}, 1800);
			
			jQuery('#mapOverlay')[0].onclick = function(e) { self.getPushpinCoordinates(e); };

			// have to delay attachment to ammap since it is added when swfobject embeds the map
			var inc = 0;
			var interval = setInterval(function() {
					if(!jQuery('#ammap').length)
					{
						++inc;
						if(inc > 30)
						{
							clearInterval(interval);
							return;
						}
					}
					self.flashMovie = $("ammap");
					jQuery('#ammap')[0].onclick = function(e) { self.getPushpinCoordinates(e); };
					jQuery('#ammap')[0].onmousedown = function(e) { self.getPushpinCoordinates(e); };
					clearInterval(interval);
				}, 400);
			
			jQuery('#pinInstructionsHide,#addPinInitial').click(function(e) { self.toggleAddPins(); });
			jQuery('#pinDeleteHide').click(function() { self.showDeletePins(); });
			jQuery('#addPinSubmit').click(function() { self.setPushpin(); });
			jQuery('#cancelPin').click(function() { self.cancelPushpin(); });
			jQuery('#deletePinInitial').click(function() { self.showDeletePins(); });
		})
	},
	
	reloadAll: function() {
		if(!this.flashMovie)
			return;
		
		this.flashMovie.reloadAll();
	},
	
	
	getPushpinCoordinates: function(e){
		if(!this.overlayVisible || this.mapHasBeenClicked || jQuery(window).data('flashZoom').scale != 1)
			return
		
		this.mapHasBeenClicked = true;
		
		/* get the zoom info and write to hidden inputs */
		this.getZoomInfo();
		
		/* IE is borking without yScroll, so add it to the mouse click position for IE only */
		var yScroll;
		if (window.pageYOffset) {
			yScroll = window.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
		}
		/* get mouse position */
		posx=0;posy=0;
		var ev=(!e)?window.event:e;//Moz:IE
		
		//Mozilla or compatible
		if (ev.pageX)
		{
			this.posx=ev.pageX;
			this.posy=ev.pageY;
		}
		//IE or compatible
		else if(ev.clientX)
		{
			this.posx = ev.clientX + 10 + this.ie_mapXOffset;
			this.posy = ev.clientY + this.ie_mapYOffset + yScroll}
		//old browsers
		else
		{
			return false;
		}
	
		/* do magics */
		var flashContentPos = Position.cumulativeOffset($('mapOverlay'));
		var clickX = this.posx - flashContentPos[0];
		var setX = (clickX-parseFloat($('zoom_x').value))/parseFloat($('zoom_level').value);
		var clickY = this.posy - flashContentPos[1];
		var setY = (clickY-parseFloat($('zoom_y').value))/parseFloat($('zoom_level').value);

		this.zoomsValue = " zoom=\"" + parseFloat($('zoom_level').value) + 
			"\" map_x=\"" + setX + 
			"\" map_y=\"" +setY+
			"\" zoom_x=\"" + parseFloat($('zoom_x').value) +
			"\" zoom_y=\"" + parseFloat($('zoom_y').value) +
			"\"";

		Effect.toggle($('mapPromptBg'),'appear',{duration:0.3,from:0.0,to:0.6});
		Effect.toggle($('mapPrompt'),'appear',{duration:0.3,from:0.0,to:1.0});
	},
	
	/* retrieve data from map click and post it to DB */
	setPushpin: function() {
		this.overlayVisible = false;
		this.mapHasBeenClicked = false;
		
		var map_title = $('map_title').value;
		map_title = map_title.replace("/","&#47;")
		map_title = escape(encodeURIComponent(map_title));
		//zoomsValue += ' title="'+map_title+'"';
		//$('zooms').value = zoomsValue;
		var postPinUrl = '/maps/add_pin/'+registryID+'/'+featureID+'/'+map_title+'/'+this.zoomsValue; //GOKCE: put the url here.
		
		var self = this;
		var postPins = new Ajax.Request( postPinUrl, {method: 'post', onComplete: function() { self.pushPinDone(); }}); 
	},
	
	cancelPushpin: function()
	{
		this.overlayVisible = true;
		this.mapHasBeenClicked = false;
		Effect.toggle($('mapPromptBg'),'appear',{duration:0.3,to:0.0});
		Effect.toggle($('mapPrompt'),'appear',{duration:0.3,to:0.0});
	},
	
	/* execute after setPushpIn */
	pushPinDone: function() {
		this.hidePushpinForm();
		$('mapOverlay').style.display='none';
		$('pinInstructions').style.display='none';
		this.reloadData();
		
	},
	
	pushPinDoneDelete: function() {
		//Effect.toggle($('mapOverlayDelete'),'slide');
		//Effect.toggle($('deleteInstructions'),'slide');
		var listPinUrl = '/maps/list_pins/'+registryID+'/'+featureID+'/';
		
		var self = this;
		new Ajax.Request( listPinUrl, {
					method: 'post',
					onSuccess: function(transport) {
						self.writeDeletePins(transport.responseText);
					}
				});
		
		this.reloadData();
	},
	
	toggleAddPins: function() {
		this.mapHasBeenClicked = false;
		if($('mapOverlay').getStyle('display')  == 'none')
			this.overlayVisible = true;
		else
			this.overlayVisible = false;
		
		// hide the delete elements if visible
		if ($('mapOverlayDelete').style.display != 'none') 
			Effect.toggle($('mapOverlayDelete'));
		if ($('deleteInstructions').style.display != 'none') 
			Effect.toggle($('deleteInstructions'));
		
		Effect.toggle($('mapOverlay'),'slide');
		Effect.toggle($('pinInstructions'),'slide');
	},
	
	/* get current pins to create delete list */
	showDeletePins: function() {
		// hide the 'add pin' elements if visible
		if ($('mapOverlay').style.display != 'none') 
			Effect.toggle($('mapOverlay'), 'slide');
		if ($('pinInstructions').style.display != 'none') 
			Effect.toggle($('pinInstructions'), 'slide');
		if ($('mapPromptBg').style.display != 'none') 
			Effect.toggle($('mapPromptBg'),'appear',{duration:0.3});
		if ($('mapPrompt').style.display != 'none') 
			Effect.toggle($('mapPrompt'),'appear',{duration:0.3});
		
		Effect.toggle($('mapOverlayDelete'), 'slide');
		Effect.toggle($('deleteInstructions'), 'slide');
		
		//$('mapOverlayDelete').style.display='block';
		//$('deleteInstructions').style.display='block';
		var listPinUrl = '/maps/list_pins/'+registryID+'/'+featureID+'/';
		
		var self = this;
		new Ajax.Request( listPinUrl, {
				method: 'post',
				onSuccess: function(transport) {
					self.writeDeletePins(transport.responseText);
				}
			});
	},
	
	writeDeletePins: function(listPins) {
		// strip the response time comment, if any
		if (listPins.indexOf("<!--") != -1) listPins = listPins.substr(0,listPins.indexOf("<!--"));
		var pinArray = listPins.split("~~~");
		var deletePinHTML = '';
		if (pinArray.length > 1) {
			jQuery('#mapOverlayDelete').html('');
			var self = this;
			
			for (var i=0;i<pinArray.length-1;i++) {
				var thisPinArray = pinArray[i].split("###");
				
				var onclick = function(e) {
					var pinId = jQuery(this).attr('pin_id');
					jQuery.post('/maps/del_pin/'+registryID+'/'+featureID+'/'+pinId, function() {
						self.pushPinDoneDelete();
					});
				};
				
				var childDiv = jQuery('<div></div>').attr('style', 'float:left;width:200px;border:1px solid red;background:#fcc;padding:5px;');
				
				var anch = jQuery('<a></a>').
					attr('href', 'javascript:void(0)').
					attr('pin_id', thisPinArray[0]).
					text('Delete').
					click(onclick);
				childDiv.append(anch).append(' ' + thisPinArray[1]);
				jQuery('#mapOverlayDelete').append(childDiv);
			}
		} else {
			var div = jQuery('<div></div>').addClass('noPins').text('There are no pins to delete!');
			jQuery('#mapOverlayDelete').html(div);
		}
	},
	
	hidePushpinForm: function() {
		Effect.toggle($('mapPromptBg'),'appear',{duration:0.3,to:0.0});
		Effect.toggle($('mapPrompt'),'appear',{duration:0.3,to:0.0});
	},
	
	// reload data
	reloadData: function() {
		if(this.flashMovie)
			this.flashMovie.reloadData(mapDataFile.replace(/rand=.+/, 'rand=' + Math.random()));
	},
	
	// reload settings
	reloadSettings: function() {
		if(this.flashMovie)
			this.flashMovie.reloadSettings();
	},
	
	getZoomInfo: function(){
		if (this.flashMovie)
			this.flashMovie.getZoomInfo();
	},

	onMapFlashZoom: function(e)
	{
		var zoom = jQuery(window).data('flashZoom');
		
		if(!zoom || typeof(zoom.scale) != 'number')
			return;
		
		if(zoom.scale != 1)
		{
			jQuery('#addPinInitial').hide();
			jQuery('#addPinZoomWarning').show();
			jQuery('#addPinZoomNowReload').hide();
			
			if(jQuery('#mapOverlay').css('display') != 'none')
			{
				this.toggleAddPins();
				this.cancelPushpin();
			}
			
			this.flashZoomWasntOne = true;
		}
		
		if(this.flashZoomWasntOne && zoom.scale == 1)
		{
			jQuery('#addPinInitial').hide();
			jQuery('#addPinZoomWarning').hide();
			jQuery('#addPinZoomNowReload').show();
			
		}
	}
};



function setZoomInfo(x,y, level){
	 document.getElementById("zoom_x").value = x;
	 document.getElementById("zoom_y").value = y;
	 document.getElementById("zoom_level").value = level;
  }



function checkPromoCode(payType) {
	
	var promoCode = jQuery('#PaymentPromoCode').val();
	
	if(!promoCode || promoCode.match(/^\s*$/))  // don't bother looking up a blank promo code
	    return;
	
	var promoCodeUrl = '/pay/validate_code/' + promoCode + '/' + payType;
	
	jQuery.ajax( {
		type: 'POST',
		url: promoCodeUrl,
		success: function(data, status, xhr) {
			jQuery('#promoCodeMsg').html(data);
			if (data.indexOf("Congratulations!") != -1) 
				jQuery('#promoCodeMsg').css('border', '1px solid #547DB7');
			else 
				jQuery('#promoCodeMsg').css('border', '1px solid red');
			
			jQuery('#promoCodeMsg').fadeIn('slow');
		}
	} );
}

function addRsvpEvent() {
	var postParams = "data[Event][title]=" + escape($('event_title').value);
	postParams += "&data[Event][description]=" + escape($('event_description').value);
	postParams += "&data[Event][event_date]=" + escape($('event_date').value);
	new Ajax.Request( '/events/add/', 
			{method: 'post',postBody:(postParams),onSuccess: function(transport) {
		if (transport.responseText == "success") {window.location = '/events/index'; }
		else {new Insertion.bottom($('add_event_error'), 'There was an error adding this event - please try again!'); Effect.toggle($('add_event_error')); }
	}
	});
}

function delRsvpEvent(id) {
	if (confirm('Are you sure you want to delete this event?')) {
		var postParams = "data[Event][id]=" + id;
		new Ajax.Request( '/events/delete/', 
				{method: 'post',postBody:(postParams),onSuccess: function(transport) {
			if (transport.responseText == "success") {window.location = '/events/index'; }
			else {alert('There was an error deleting this event - please try again!');}
		}
		});
	}
}

function clearDefault() { this.style.color = '#000'; if (this.value == this.alt) this.value='';}
function resetDefault() { if (this.value == '') { this.value = this.alt; this.style.color = '#aaa';} }

function setDefaults() {
	var textInputs = document.getElementsByTagName('input');
	var inputsDefault = new Array();
	for (i=0;i<textInputs.length;i++) {
		var inputName = textInputs[i].id;
		inputsDefault[inputName] = textInputs[i].value;
		if (textInputs[i].type == "text") {
			if (textInputs[i].value == "") { textInputs[i].value = textInputs[i].alt; textInputs[i].style.color = '#aaa'; }
			Event.observe(textInputs[i],'focus',clearDefault.bind(textInputs[i]));
			Event.observe(textInputs[i],'blur',resetDefault.bind(textInputs[i]));
		}
	}
}
		
function selectGuest(obj,singleRow) {
	if (obj.id) var id = obj.id;
	else { var id = obj; $(id+"").checked = true; }
	$(id+"").ancestors()[1].style.background = ($(id+"").checked != false) ? "#fffabb":"";
	if (!singleRow) $(id+"").ancestors()[1].next(0).style.background = ($(id+"").checked != false) ? "#fffabb":"";
}

function fixPNG(myImage) 
{
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);

    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
	   var imgStyle = "display:inline-block;" + myImage.style.cssText
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
	   myImage.outerHTML = strNewHTML	  
    }
} 

// Function By Waqas
function set_default_path(path,title)
{
	new Ajax.Request('/controlpanel/set_default?path='+path+'&title='+title, { method:'get' });
	// document.getElementById('set_def').innerHTML = "Make Default";
		var postParams = 'path='+path+'&title='+title;
		new Ajax.Request( '/controlpanel/set_default/', 
				{method: 'post',postBody:(postParams),onSuccess: function(transport) {
			if (transport.responseText == "success") {
					document.getElementById('current_default').style.display="block";
					document.getElementById('mkdefault').style.display="none";
				}
			else {alert('There was an error Makint this default - please try again!');}
		}
		});
	
	
}
function toggle_default(current)
{
	if(current  == "0" ){
		
		document.getElementById('current_default').style.display="none";
		document.getElementById('mkdefault').style.display="block";	
		//alert("zero:"+current);	
	}
	else{
		//alert("one:"+current);	
		document.getElementById('current_default').style.display="none";
		document.getElementById('mkdefault').style.display="none";	
	}
}

// for thumbnail images, if the real width of the image is smaller than the displayed width
// (because the template is forcing wider images) fetch the fullsize and replace the image's
// src
function swapThumbnails()
{
	$$('img[src]').
		findAll(function(img,i) { return img.src.match(/tmb/);  }).
		each(function(img,i) {
			var testImg = new Image(); 
			testImg.onload = function() { 
				if(this.width < img.width)
				{
					var bigImg = new Image();
					bigImg.onload = function() {
						img.src = this.src;
					};
					bigImg.src = img.src.replace(/tmb_/, '');
				}
			};
			testImg.src = img.src; 
		});
}

/**
 * Validates submission of Feature (aka page) form for new and update actions
 */
function validateFeature(form)
{
	var featureTitle = $('FeatureFeatureTitle');
	if(featureTitle)
	{
		if(featureTitle.getValue().match(/^\s*$/))
		{
			alert("Please give the page a title");
			if(featureTitle.focus)
				featureTitle.focus();
			return false;
		}
	}
	
	return true;
}

function validatePhotoPost(form)
{
	var uploadField = $('PhotoFilename');
	
	if(uploadField && !uploadField.getValue())
	{
		alert("Please select a photo to upload");
		return false;
	}
	
	return true;
}

function validatePublishForm(form)
{
	var fields = [
		['#TemplateName', 'template name'],
		['#TemplateColorName', 'template color'],
		['#TemplateColorPrimary', 'primary color', function(el) { return el.val().match(/^#?[a-f0-9]{6}$/i) }]
	];
		
	for(var i=0; i<fields.length; ++i)
	{
		var f = jQuery(fields[i][0]);
		if(!f.length)
			continue;
		
		if(!f.val() || (fields[i].length == 3 && !fields[i][2](f)))
		{
			alert('A valid ' + fields[i][1] + ' is required');
			if(typeof(f[0].focus) == 'function')
				f[0].focus();
			
			return false;
		}
	}
	
	if(jQuery('#TemplatePreviewImageId').val() || jQuery('#TemplatePreviewImage').val())
		return true;
	
	alert('Please add a preview image');
	return false;
}

function createCustomerServiceEntry(divId)
{
	if(!divId)
		return;
	
	if(divId.charAt(0) != '#')
		divId = '#' + divId;
	
	jQuery.ajax({
			url: '/customer_service_entries/create?rand=' + Math.random(),
			type: 'POST',
			data: getCustomerServiceVariables(),
			success: function(data, textStatus, xhr) {
				if(parseInt(data) != NaN)
					jQuery(divId).html("Please include this Customer Support number with your help request: <b>" + data + '</b>');
			},
			error: function() {}
	});
	
}

function getCustomerServiceVariables()
{
	var response = {
		flashVersion: null,
		likelyBrowser: 'unknown',
		flashDetectedZoom: null
	};
	
	if(typeof(swfobject) == 'object')
	{
		var flVer = swfobject.getFlashPlayerVersion();
		response.flashVersion = flVer.major + '.' + flVer.minor + '.' + flVer.release;
	}
	
	if(typeof(jQuery) != 'undefined')
	{
		if(jQuery.browser.mozilla)
			response.likelyBrowser = 'Firefox';
		else if(jQuery.browser.msie)
			response.likelyBrowser = 'Internet Explorer ' + jQuery.browser.version;
		else if(jQuery.browser.opera)
			response.likelyBrowser = 'Opera ' + jQuery.browser.version;
		else if(jQuery.browser.webkit || jQuery.browser.safari)
			response.likelyBrowser = 'Safari or other Webkit (Konqueror, Chrome)';
		
		var zoom = jQuery(window).data('flashZoom');
		if(zoom && typeof(zoom.scale) != 'undefined')
			response.flashDetectedZoom = zoom.scale;
	}
	
	if(typeof(navigator.platform) != 'undefined')
		response.platform = navigator.platform;
	
	return response;
}


/**
 * Show / hide the edit toolbar on a user's registry
 */
jQuery(document).ready(function() {
	
	// don't bother adding listener to the frameset parent
	if(window.frames.length == 2 && window == window.top)
	{
		console.log('skipping this parent');
		return;
	}
	
	var shell = jQuery('#shell');
	
	if(!shell.length)
	{
		return;
	}
	
	if(jQuery('#show_toolbar'))
	{
		var paddingHeight = shell.css('padding-top');
		
		var toggle = function() {
			console.log(jQuery('#toolbar'));
			
			// hide toolbar
			if(jQuery('#toolbar').css('display') != 'none')
			{
				jQuery('#toolbar,#toolbar_shadow').css('display', 'none');
				jQuery('#show_toolbar').css('display', 'block');
				jQuery('#shell').css('padding-top', '0');
			}
			else
			{
				jQuery('#toolbar, #toolbar_shadow').css('display', 'block');
				jQuery('#show_toolbar').css('display', 'none');
				jQuery('#shell').css('padding-top', paddingHeight);
			}
		};
		
		jQuery('#show_toolbar,#hide_toolbar').click(toggle);
	}
});



function submitLoginOrSignup(form, isAjax)
{
	if(typeof(isAjax) != 'boolean')
		isAjax = false;
	
	var f = jQuery(form);
	
	if(isAjax)
	{
		jQuery.post(f.attr('action'), f.serialize(), 
			function(data, textStatus, xhr) {
				console.log('ajax login or signup', data, textStatus);
				jQuery(window).data('userLoggedIn', true);
				jQuery(window).trigger('onUserLogin');
			}
		);
		
		return false;
	}
	
	return true;
}

function activeClickOnEmbeds()
{
	jQuery(document.body).click(onWindowEmbedClick);
	
	function onWindowEmbedClick(e)
	{
		var target = jQuery(e.target);
		
		if(target.get(0).tagName == 'BUTTON' && target.hasClass('embed') && target.attr('url'))
		{
			var span = jQuery('<span></span>').load(target.attr('url') + '?rand=' + Math.random());
			target.replaceWith(span);
		}
		else if(target.get(0).tagName == 'INPUT' && target.hasClass('embed') && target.get(0).select)
			target.get(0).select();
	}
}

function activateSelectOnTextareas()
{
	jQuery(document.body).click(function(e) {
		try {
			if(e.target.select && jQuery(e.target).attr('select_on_click'))
				e.target.select();
		} catch(e) {}
	});
}

/**
 * Quick and dirty handling of dynamic comment loading, replaces the old method by which all
 * the comment data was loaded at page load time (horrible for performance)
 */
(function() {
		
	jQuery(document).ready(function() {
		function onCommentSubmit(e) {
			e.preventDefault();
			var form = jQuery(e.target);
			
			if(!form.hasClass('comment_addForm'))
				form = form.parents('.comment_addForm');
			
			if(!form.hasClass('comment_addForm'))
			{
				console.log('no form for submission');
				return;
			}
			
			var parent = form.parents('.comments[entry_id]');
			var currentComments = form.parents('.currentComments');
			
			if(!parent.length || !currentComments.length)
				return;
			
			var addUrl = '/visitorcomments/add/' + parent.attr('entry_type') + '/' + parent.attr('entry_id') + '?rand=' + Math.random();
				
			jQuery.post(addUrl, jQuery(form).serialize(), function(data) {
				currentComments.html(data);
				updateCommentCount(currentComments);
			});
		};
	
		function onDeleteCommentClick(e) {
			e.preventDefault();
			
			var link = jQuery(e.target);
			
			if(!link.hasClass('delete_comment'))
				return;
			
			var currentComments = link.parents('.currentComments');
			jQuery.post(link.attr('href'), function(data) {
				currentComments.html(data);
				updateCommentCount(currentComments);
			});
		}
		
		// frontend update of comment count until page reload
		function updateCommentCount(commentsContainer)
		{
			var len = commentsContainer.find('.comment_container').length;
			commentsContainer.prev('.showComments').text(len + ' comment' + (len != 1 ? 's' : ''));
		}
		
		function showComments(e)
		{
			if(e.target)
				var target = jQuery(e.target);
			else
				var target = jQuery(e);
			
			var commentsContainer = [];
			
			if(target.hasClass('currentComments'))
				commentsContainer = target;
			
			if(!commentsContainer.length)
				commentsContainer = target.next('.currentComments');
			
			if(!commentsContainer.length)
				commentsContainer = target.parents('.currentComments');
			
			if(!commentsContainer.length)
			{
				console.error("Couldn't find comments container based on target %o", target);
				return;
			}
			
			if(commentsContainer.css('display') == 'block')
			{
				Effect.toggle(commentsContainer[0],'slide',{duration:0.5});
				
				if(jQuery.browser.msie && jQuery.browser.version == 7)
				{
					jQuery('.photo.not-active').removeClass('not-active');
				}
				
				commentsContainer.removeClass('visible');
				return;
			}
			
			jQuery('.currentComments.visible').each(function() {
				if(this != commentsContainer[0])
				{
					console.log('hiding %o', this);
					jQuery(this).removeClass('visible').css('display', 'none');
				}
			});
			
			
			if(jQuery.browser.msie && jQuery.browser.version == 7)
			{
				var par = target.parents('.photo');
				
				if(par.length)
				{
					jQuery('#photogallery .photo').each(function() {
						if(this != par[0])
							jQuery(this).addClass('not-active');
					});
				}
			}
			
			var addUrl = '/visitorcomments/add/' + target.parent().attr('entry_type') + '/' + target.parent().attr('entry_id') + 
				(target.parent().attr('template_mode') ? '/' + target.parent().attr('template_mode') : '') +
				'?rand=' + Math.random();
			
			// just expand comments if pre-loaded
			if(target.parent().attr('non_ajax'))
			{
				console.log(commentsContainer);
				commentsContainer.addClass('visible');
				Effect.toggle(commentsContainer[0],'slide',{duration:0.5});
			}
			else
			{
				commentsContainer.html('').addClass('visible').load(addUrl, function(e) {
					Effect.toggle(commentsContainer[0],'slide',{duration:0.5});
				});
			}
		}
		
		jQuery(document).click(function(e) {
			var target = jQuery(e.target);
			
			if(!target.parents('.comments').attr('entry_type') || !target.parents('.comments').attr('entry_id'))
				return;
			
			if(target.hasClass('showComments'))
				showComments(e);
			else if(target.hasClass('comment_submit'))
				onCommentSubmit(e);
			else if(target.hasClass('delete_comment'))
				onDeleteCommentClick(e);
		});
	});
})();



(function() {
	var postInProgress = false;
	var autoPostDraftInterval = null;
	var prevPostData = '';
	
	function onLightviewOpenedPostDraft(prototypeEvent)
	{
		if(jQuery('#post_draft_id,#feature_draft_id').length != 2 || !CKEDITOR.instances.PostPostContent)
		{
			console.log('no post_draft_id or no feature_draft_id or no ckeditor instance');
			return;
		}
		else if(!jQuery(window).data('userLoggedIn'))
		{
			console.log('user not logged in, not auto-saving post draft');
			return;
		}
		
		autoPostDraftInterval = setInterval(autoPostDraft, 3000);
	}
	
	function onLightviewHiddenPostDraft()
	{
		console.log('onLightviewHiddenPostDraft');
		if(autoPostDraftInterval)
			clearInterval(autoPostDraftInterval);
	}
	
	function showAutoSave()
	{
		var autosave = jQuery('#auto_saved');
		
		var d = new Date();
		
		var h = d.getHours();
		var m = d.getMinutes();
		var am = 'am';
		
		if(h > 12)
		{
			h = h - 12;
			am = 'pm';
		}
		
		if(autosave.attr('h') && autosave.attr('m') && autosave.attr('h') == h && autosave.attr('m') == m)
			return;
		
		autosave.attr('h', h).attr('m', m).text('Draft saved at ' + h + ':' + m + ' ' + am).show();
	}
	
	function autoPostDraft()
	{
		var featureId = jQuery('#feature_draft_id').val();
		var postId = jQuery('#post_draft_id').val();
		
		if(postInProgress)
		{
			console.log('post draft in progress');
			return;
		}
		
		var postContent = CKEDITOR.instances.PostPostContent.getData();
		
		if(typeof(postContent) != 'string' || postContent.match(/^[\s]*(<[\w]+>)?([\s]|&nbsp;)+(<\/[\w]+>)?[\s]*$/))
		{
			// console.log('post content is empty, skipping auto save');
			return;
		}
		else if(prevPostData == postContent)
		{
			// console.log('skipping post data, content is the same');
			return;
		}
		
		postInProgress = true;
		
		var data = {
			post_id: postId,
			feature_id: featureId,
			post_id: postId,
			draft_content: postContent
		};
		
		prevPostData = postContent;
		
		jQuery.ajax({
			url: '/posts/ajax_save_draft',
			type: 'post',
			dataType: 'json',
			data: data,
			error: onPostDraftError,
			success: onPostDraftSuccess
		});
	}
	
	function onPostDraftError(xhr, textStatus, errorThrown)
	{
		postInProgress = false;
		prevPostData = ''; // ensures that post data can be re-sent
	}
	
	function onPostDraftSuccess(data, textStatus, xhr)
	{
		postInProgress = false;
		
		// ensures that auto-save and real save will use the existing post id
		if(data && data.post_id)
			jQuery('#PostId,#post_draft_id').val(data.post_id);
		
		showAutoSave();
	}
	
	jQuery(document).ready(function() {
		// delay ensures that IE will have the ckeditor available
		Event.observe(document, 'lightview:opened', function() { setTimeout(onLightviewOpenedPostDraft, 1200) });
		Event.observe(document, 'lightview:hidden', onLightviewHiddenPostDraft);
	});
})();

function setupLeadly()
{
	if(!jQuery('#leadly_share').length)
		return;
	
	console.log('will load leadly');
	jQuery('#leadly_share').click(loadLeadlyShare);
}

function loadLeadlyShare() 
{
	if(jQuery('#leadly_content textarea').length)
	{
		showLeadly();
		return;
	}
	
	var options = {
		callAfter: function() {
			jQuery('#leadly_content textarea').addClass('no_nic');
			showLeadly();
		}
	};
	
	jQuery('<div>', {id: 'leadly_content'}).appendTo(document.body);
	Leadly.load("#leadly_content", options);
}

function showLeadly()
{
	Lightview.show({ 
		href: '#leadly_content', 
		options: {
			width: 800,
			height: 355
		}
	});
}

function checkForBadge()
{
	var match = (window.location.hash || '').match(/#b=(.+)$/);
	
	if(match)
	{
		if(document.referrer)
		{
			var url = '/ghgh_badges/click/' + match[1] + '?referrer=' + encodeURIComponent(document.referrer);
			
			jQuery.post(url);
		}
		window.location = '#';
	}
	
}

function checkForLeadlyReferrer()
{
	if(typeof(Leadly) != 'undefined' && Leadly.user.referringUserId)
	{
		jQuery.post('/leadly/store_user_id/' + Leadly.user.referringUserId);
	}
	
}

function updateSifrData(registryId)
{
	jQuery(window).load(function() {
		setTimeout(function() {
			if(!jQuery('.sIFR-flash:visible').length)
			{
				console.log('no visible sifr');
				return;
			}
			
			var firstSifr = jQuery('.sIFR-flash:visible:first');
			
			var bounds = jQuery('.sIFR-flash:visible').bounds();
			
			console.log('bounds', bounds);
			
			
			var data = { 
				x: bounds.left, 
				y: bounds.top, 
				width: bounds.right - bounds.left, 
				height: bounds.bottom - bounds.top,
				window_width: jQuery(window).width(),
				window_height: jQuery(window).height()
			};
			
			jQuery.post('/cloned_sites/store_sifr_data/' + registryId, data);
		}, 2000);
	});
}

(function() {
   jQuery.fn['bounds'] = function () {
     var bounds = {  left: Number.POSITIVE_INFINITY, 
                      top: Number.POSITIVE_INFINITY,
                    right: Number.NEGATIVE_INFINITY, 
                   bottom: Number.NEGATIVE_INFINITY};

     this.each(function (i,el) {
                 var elQ = jQuery(el);
                 var off = elQ.offset();
                 off.right = off.left + jQuery(elQ).width();
                 off.bottom = off.top + jQuery(elQ).height();

                 if (off.left < bounds.left)
                   bounds.left = off.left;

                 if (off.top < bounds.top)
                   bounds.top = off.top;

                 if (off.right > bounds.right)
                   bounds.right = off.right;

                 if (off.bottom > bounds.bottom)
                   bounds.bottom = off.bottom;

               });
     return bounds;
   }
 })();
