/*
Final - The JS script that is to be loaded last in the document header
--
Written by Ivik Injerd, Dave Sienkowski
Dependedcies:
---->Jquery
---->Jquery UI
*/

var dumont;

// Places ads based on the size of the widget
// Live ad rotation:
function adRotation(){
	if (ads == undefined || !ads.length) return false;
	var myads = [];
	var imageWidth = 370;
	
	if ($('.nde-window.w-ad .nde-content .content img.ad-dyn-next').length){
		$('.nde-window.w-ad .nde-content .content img').parent().hide();
		$('.nde-window.w-ad .nde-content .content img.ad-dyn-next').removeClass('ad-dyn-next').parent().show();
	}
	$('.nde-window.w-ad .nde-content .content').each(function(){
		var workingWidth = $(this).innerWidth();
		var imagesShowing = $(this).find('img').length;
		var imagesToShow = Math.floor(workingWidth/imageWidth);
		if (imagesToShow < 1) imagesToShow = 1;
				
		// To prevent the images from scanning when loading
	
		//$(this).find('img').hide();
		while(imagesToShow > 0){
			if (myads.length == 0){
				myads = ads.slice();
				myads.sort(function() {return 0.5 - Math.random();});
			}
			var ad = myads.shift();
			var obj = $(this).find('img.ad-id-'+ad.id);
			if (obj.length)
				obj.addClass('ad-dyn-next');
			else
				$(this).find('div.dynamic-ads').append('<a href="'+savings_uri+'/clicked_ad/'+ad.id+'"><img class="ad-dyn ad-id-'+ad.id+' ad-dyn-next" alt="'+ad.alt+'" src="'+adbase+ad.media+'" width="370" height="90" /></a>').find('img.ad-dyn-next').parent().hide();
			imagesToShow--;
		}
	});
}

$(document).ready(function(){
	
	// Centsable Savings
	$("#savingsbg .stabs ul li a").live('click',function(e){
		var cid = $(this).parents('li').attr('id').replace(/cat-id-(\w+)/i,'$1');
		$('#savingsbg .coupons .finish').hide();
		if (cid == 'all'){
			$('#savingsbg .savingswrapper').hide();
			$('#savingsbg .coupons').show();
			$('#savingsbg .coupons ul li').show();
		}else if (cid == 'help'){
			$('#savingsbg .coupons').hide();
			$('#savingsbg .savingswrapper').show();
		}else if (cid == 'mine'){
			$('#savingsbg .coupons').show();
			$('#savingsbg .coupons ul li:not(.coupon-cat-mine)').hide();
			$('#savingsbg .coupons ul li.coupon-cat-mine').show();
			$('#savingsbg .savingswrapper').hide();
		}else{
			$('#savingsbg .savingswrapper').hide();
			$('#savingsbg .coupons').show();
			$('#savingsbg .coupons ul li:not(.coupon-cat-'+cid+')').hide();
			$('#savingsbg .coupons ul li.coupon-cat-'+cid).show();
		}
		$('#savingsbg .subtabs ul li:not(.ctrl)').hide(200,function(){
			$(this).remove();
		});
		$(this).parents('li').find('ul.subcats li').clone().appendTo('#savingsbg .subtabs ul').show(200);
		$(this).parents('ul').find('li.active').removeClass('active');
		$(this).parents('li').addClass('active');
		e.preventDefault();
	});
	$("#savingsbg .subtabs ul li:not(.ctrl) a").live('click',function(e){
		var cid = $(this).parents('li').attr('id').replace(/cat-id-(\d+)/i,'$1');
		$('#savingsbg .coupons .finish').hide();
		$('#savingsbg .coupons ul li:not(.coupon-cat-'+cid+')').hide();
		$('#savingsbg .coupons ul li.coupon-cat-'+cid).show();
		e.preventDefault();
	});
	$("#savingsbg .subtabs ul li.ctrl a").live('click',function(e){
		var type = $(this).parent().attr('class').replace(/^.*(print|phone|email).*$/i,'$1');
		$('#savingsbg .coupons ul li').hide();
		$('#savingsbg .coupons ul li:has(.coupon-ctrl a.'+type+'.selected)').show();
		$('#savingsbg .coupons .finish').hide();
		$('#savingsbg .coupons .finish.'+type).show();
		e.preventDefault();
	});
	$("#savingsbg .coupons ul li .coupon-ctrl a").live('click',function(e){
		var obj = $('#savingsbg .subtabs ul li.ctrl.'+$(this).attr('href').replace(/\#(\w+)/i,'$1')+' a');
		if (obj.length){
			var count = Number(obj.html().replace(/\w+(?: \((\d+)\))?/i,'$1'));
			if ($(this).hasClass('selected')){
				count--;
				$(this).removeClass('selected');
			}else{
				count++;
				$(this).addClass('selected');
			}
			if (count < 1){
				obj.html(obj.html().replace(/(\w+)(?: \(\d+\))?/i,'$1'));
			}else{
				obj.html(obj.html().replace(/(\w+)(?: \(\d+\))?/i,'$1 ('+count+')'));
			}
		}
		e.preventDefault();
	});
	$("#savingsbg .coupons a.printcoupons").live('click',function(e){
		var output = '<style type="text/css" media="print">.noprint{display:none;}</style><a href="#print" onclick="print();return false" class="noprint">Print</a><div style="width:700px">';
		$('#savingsbg .coupons ul li:has(.coupon-ctrl a.print.selected) .coupon').each(function(){
			if ($(this).has('a').length)
				output += $(this).find('a').html();
			else
				output += $(this).html();
		});
		output += '</div>';
		couponwin = window.open(null,"couponwin","toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=no, width=720, height=600");
		couponwin.document.write(output);
		e.preventDefault();
	});
	$("#savingsbg .coupons a.emailcoupons").live('click',function(e){
		var cids = [];
		$('#savingsbg .coupons ul li:has(.coupon-ctrl a.email.selected) .coupon img').each(function(){
			cids.push($(this).attr('src').replace(/^.*\/(\d+)$/, '$1'));
		});
		cids = cids.join();
		$('#savingsbg .coupons .finish.email .status').html('Sending...');
		dumont.doRequest({wik:getWIK(this),action:'savings/email',cids:cids},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$('#savingsbg .coupons .finish.email .status').html(reply.content?'The email has been sent!':'Sorry, the email failed to send.');
		});
		e.preventDefault();
	});
	$("#savingsbg .coupons form.finish.phone").live('submit',function(e){
		var cids = [];
		var destnum = $(this).find('input[name=phone]').val();
		if (destnum.match(/^\D*\+?1?\D*([2-9][0-8][0-9])\D*([2-9][0-9]{2})\D*([0-9]{4})\D*$/)){
			$('#savingsbg .coupons ul li:has(.coupon-ctrl a.phone.selected)').each(function(){
				cids.push($(this).attr('id').replace(/^coupon-cid-(\d+)$/, '$1'));
			});
			cids = cids.join();
			$('#savingsbg .coupons .finish.phone .status').html('Sending...');
			dumont.doRequest({wik:getWIK(this),action:'savings/phone',cids:cids,destnum:destnum},function(reply){
				debugWin(reply,false,'#ff0');
				debugWin(this,false,'#f0f');
				$('#savingsbg .coupons .finish.phone .status').html(reply.content?'Texting of coupons is temporarily down, Sorry for the inconvenience.':'Sorry, the text failed to send.');
			});
		}else{
			$('#savingsbg .coupons .finish.phone .status').html('Invalid phone number, please enter a valid U.S. cell phone number and try again.');
		}
		e.preventDefault();
	});
	// End Centsable Savings

	// Widget Select Accordian
	$('#headerbar .widgetselect').click(function(e){
		if ($(this).hasClass('open')){
			$(this).removeClass('open');
			$('#widget-list').slideUp(100);
		}else{
			$(this).addClass('open');
			$('#widget-list').slideDown(100);
		}
		e.preventDefault();
	});
	$('#widget-list .widgetselect').click(function(e){
		$('#widget-list').slideUp(100);
		$('#headerbar .widgetselect').removeClass('open');
		e.preventDefault();
	});
	$('#widget-list').hide();
	$('#widget-sects').show();
	$('#all-widgets').css('margin-left','150px');
	$('#widget-cats ul li a').click(function(e){
		$(this).parents('ul').find('a').removeClass('active');
		$(this).addClass('active');
		if ($(this).parent().hasClass('wcat-all'))
			$('#all-widgets ul li').show();
		else
			$('#all-widgets ul li').hide().parent().find('.'+$(this).parent().attr('class')).show();
		e.preventDefault();
	});
	$('#widget-cats ul li').each(function(){
		if ($(this).attr('class') != 'wcat-all' && $('#all-widgets ul li.'+$(this).attr('class')).length == 0)
			$(this).hide();
		else if ($(this).attr('class') == 'wcat-all')
			$(this).find('a').append(' ('+$('#all-widgets ul li').length.toString()+')');
		else
			$(this).find('a').append(' ('+$('#all-widgets ul li.'+$(this).attr('class')).length.toString()+')');
	});
	$('#widget-cats').hide();
	$('#widget-sects ul li a').click(function(e){
		if ($(this).hasClass('active')){
			$('#widget-cats').hide();
			$('#all-widgets ul li').show();
			$(this).removeClass('active');
			e.preventDefault();
		}else{
			$(this).parents('ul').find('a').removeClass('active');
			$(this).addClass('active');
			switch($(this).attr('href')){
				case '#Widget_Categories':
					$('#widget-cats ul li a').removeClass('active');
					$('#widget-cats ul li.wcat-all a').addClass('active');
					$('#widget-cats').show();
					$('#all-widgets ul li').show();
					e.preventDefault();
					break;
				case '#Widget_Featured':
					$('#widget-cats').hide();
					$('#all-widgets ul li').hide().parent().find('.wfeatured').show();
					e.preventDefault();
					break;
				case '#Widget_New':
					$('#widget-cats').hide();
					$('#all-widgets ul li').hide().parent().find('.wnew').show();
					e.preventDefault();
					break;
				case '#Widget_Popular':
					$('#widget-cats').hide();
					$('#all-widgets ul li').hide().parent().find('.wpopular').show();
					e.preventDefault();
					break;
			}
		}
	});
	// End Widget Select Accordian
	
	// Had to comment this out because it was causing problems on sub registration page by hiding image zend form element. 
	// Hide all parts of hidden elements (<dt> and <dd>) generated by zend_form
	// $('dl.zend_form dd input[type=hidden]').each(function(){
		// $(this).parent().hide().prev().hide();
	// });
	// End hide hidden elements
	
	dumont = new IOTower();
	//$('a').click(function(e){
		//e.preventDefault();
	//});
	$('.nde-tabs ul li:not(.alt, .reload) > div > a').live('click',function(e){
		beginTabLoading();
		var tik = $(this).attr('href').replace(/^.*tab\/(\w+)$/,'$1');
		if ($('.nde-tabsettings:visible').length){
			$('.nde-tabsettings').slideUp(200);
			var settingswasopen = true;
		}else{
			var settingswasopen = false;
		}
		dumont.addRequest({id:'tabsettings',tik:tik,action:'tab/settings'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$('.nde-tabsettings').html(reply.content+'<div style="clear:both"></div>');
			if (settingswasopen)
				$('.nde-tabsettings').slideDown(200);
		}, true);
		dumont.doRequest({id:'tabload',tik:tik,action:'tab/load'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$('#widgets').slideUp(300,function(){
				exitalert_active = $(reply.content).find('iframe').length;
				$(this).html(reply.content).slideDown(300, function(){
					endTabLoading(dumont.outgoing.length==0&&dumont.outgoing_active.length==0);
				});
				
				// Load up the ads after switching tabs
				adRotation();
			});
		}, true);
		$('.nde-tabs ul li:not(.alt)').removeClass('active');
		$(this).parents('li').addClass('active');
		
		e.preventDefault();
	});
	$('#all-widgets ul li a').live('click',function(e){
		dumont.doRequest({tik:getTIK(),action:'widget/add',wid:$(this).attr('href').replace(/^.*add\/(\w+)$/,'$1')},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$('.nde-column:first').prepend(reply.content).find('.nde-window:first').hide().slideDown(300);
		});
		e.preventDefault();
	});
	$('.nde-tabs .nde-tsettings').live('click',function(e){
		$('.nde-tabsettings').slideToggle(300);
		e.preventDefault();
	});
	$('.nde-tabs .nde-tclose').live('click',function(e){
		var go = $(this).attr('href');
		$(document).xmodal({
			title:'Remove Tab',
			html:'Are you sure you want to remove this tab?<br />'
			 +'<small>Removing this tab will permanently delete all contained widgets and settings.</small>',
			width:480,
			height:130,
			type:'confirm',
			callback:function(reply){
				if (reply) window.location = go;
			},
			speed:0.2
		});
		e.preventDefault();
	});
	$('.nde-window .nde-wsettings').live('click',function(){
		$(this).parents('.nde-window').find('.settings').slideToggle(300);
	});
	$('.nde-window .nde-wrefresh').live('click',function(){
		dumont.doRequest({wik:getWIK(this),action:getWAction(this)},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$('.wik-'+this.data.wik+' .nde-content .content').fadeOut(500,function(){
				exitalert_active = $(reply.content).find('iframe').length;
				$(this).html(reply.content).fadeIn(500);
				
			    $("#tabs_"+getWIK(this)).tabs();

			});
		});
	});
	$('.nde-window .nde-wminimize').live('click',function(){
		$(this).parents('.nde-window').find('.nde-content').slideToggle(300);
		//dumont.addRequest({wik:getWIK(this),action:getWAction(this)});
	});
	$('.nde-window .nde-wclose').live('click',function(){
		var wreq_data = {wik:getWIK(this),action:getWAction(this)};
		$(this).parents('.nde-window').fadeTo(500, 0.25, function(){
			dumont.doRequest(wreq_data,function(reply){
				debugWin(reply,false,'#ff0');
				debugWin(this,false,'#f0f');
				if (reply.content == true){
					$('.wik-'+this.data.wik).slideUp(500, function(){
						$(this).remove();
					});
				}else{
					$('.wik-'+this.data.wik).fadeTo(500, 1, function(){
						throwError('ERROR: Failed to remove widget!');
					});
				}
			});
		});
	});
	var widgets_minimized = false;
	$('#toggle-minimize').click(function(e){
		if (widgets_minimized){
			$('.nde-window:not(.w-ad) .nde-content').slideDown(300);
		}else{
			$('.nde-window:not(.w-ad) .nde-content').slideUp(300);
		}
		widgets_minimized = !widgets_minimized;
		e.preventDefault();
	});
	$('.nde-window a.cancel').live('click',function(e){
		$(this).parents('.nde-window').find('.nde-wrefresh').click();
		e.preventDefault();
	});
	$('#head-profile').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'user/profile'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'Profile',html:reply.content,width:525,height:400,anim:false});
		});
		e.preventDefault();
	});
	$('#head-register,#fpopup-register').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'user/register'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'Register',html:reply.content,width:320,height:175+128+50,anim:false});
		});
		e.preventDefault();
	});
	$('#head-login,#fpopup-login').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'user/login'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'Login',html:reply.content,width:300,height:200,anim:false,onload:function(){
				$('.reminder_toggle #username').focus();
			}});
		});
		e.preventDefault();
	});
	$('#tab-savings').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'wsl/savings'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'Cents-Able-Savings',html:reply.content,width:900,height:600,anim:false});
		});
		e.preventDefault();
	});
	$('.tab-invite').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'feedback/index'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'Group Invite',html:reply.content,width:500,height:425,anim:false});
		});
		e.preventDefault();
	});
	$('.nu-complaint').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'user/complaint'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'HOA Concern Form',html:reply.content,width:500,height:380,anim:false});
		});
		e.preventDefault();
	});
	$('.nu-vcomplaint').click(function(e){
		var editid = $(this).attr('href').split('/').pop();
		dumont.doRequest({uid:dumont.uid,action:'user/viewcomplaint',editid:editid},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'View Complaint',html:reply.content,width:500,height:350,anim:false});
		});
		e.preventDefault();
	});
	
	var wtitle_mousedown = false;
	$('.nde-window:not(.w-ad) .nde-wlt').live('dblclick',function(e){
		$(this).parents('.nde-window').find('.nde-content').slideToggle(300);
		e.preventDefault();
	}).live('mouseenter',function(){
		$(this).find('a').stop(true,true).fadeIn(300);
	}).live('mouseleave',function(){
		$(this).find('a').fadeOut(300);
	}).live('mousedown',function(e){
		wtitle_mousedown = {
			x:e.pageX,
			y:e.pageY,
			name:$(this).parents('.nde-window').find('.nde-title').html(),
			wik:getWIK(this)};
		e.preventDefault();
	}).find('.nde-title').live('mouseover',function(){
		$(this).css('cursor', 'move');
	});
	var current_col = null;
	var current_row = null;
	var current_closest_col = null;
	var current_closest_row = null;
	var current_use_append = false;
	var current_ignore = null;
	var distance = 0;
	var current_layout = [];
	$(document).mousemove(function(e){
		if (typeof wtitle_mousedown == 'object'){
			if (current_ignore === null)
				distance = Math.sqrt(Math.pow(e.pageX-wtitle_mousedown.x,2)+Math.pow(e.pageY-wtitle_mousedown.y,2));
			if (distance > 20){
				if (!$('#movable-wtitle').length){
					$('body').append('<div id="movable-wtitle">'+wtitle_mousedown.name+'</div>');
					var wlist = '<ol id="organize-wlist">';
					$('.nde-column').each(function(){
						wlist += '<li style="width:'+$(this).css('width')+'"><ul>';
						var col_idx = $('.nde-column').index(this);
						$(this).find('.nde-window:not(.w-ad)').each(function(){
							var wik = getWIK(this);
							var curw = (wtitle_mousedown.wik == wik);
							wlist += '<li'+(curw?' class="current-widget"':'')+'>'+$(this).find('.nde-title').html()+'</li>';
							if (curw){
								current_col = col_idx;
								current_row = $('.nde-column:eq('+col_idx+') .nde-window').index(this);
							}
						});
						wlist += '</ul></li>';
					});
					wlist += '</ol>';
					$(document).xmodal({title:'Move Widget To...',html:wlist,width:500,height:400,anim:false,close:false});
					current_ignore = true;
				}
				if ($('#organize-wlist').length){
					var start_x = $('ol#organize-wlist > li:first').offset().left;
					var width_each = $('ol#organize-wlist > li:first').outerWidth(true);
					var col_idx = Math.round(((e.pageX-start_x)/width_each)-0.5);
					var closest_col = $('ol#organize-wlist > li:eq('+col_idx+')');
					if (closest_col.length){
						if(closest_col.find('ul > li:not(.moving-widget)').length){
							var rowlen = closest_col.find('ul > li:not(.moving-widget)').length;
							var start_y = closest_col.find('ul > li:first').offset().top;
							var height_each = closest_col.find('ul > li:not(.moving-widget):first').outerHeight(true);
							var idx = Math.round((e.pageY-start_y)/height_each)-1;
							if (idx < -1 && idx > -4) idx = -1;
							else if (idx >= rowlen && idx < rowlen+10) idx = rowlen-1;
							else if (idx < -1 || idx >= rowlen) idx = null;
							if (idx != current_closest_row || col_idx != current_closest_col){
								$('#organize-wlist .moving-widget:animated').remove();
								$('#organize-wlist .moving-widget').slideUp(200,function(){$(this).remove();});
								if (idx != null){
									if (idx < 0){
										closest_col.find('ul > li:not(.moving-widget):eq(0)').before('<li class="moving-widget">'+wtitle_mousedown.name+'</li>').prev().slideDown(200);
									}else{
										closest_col.find('ul > li:not(.moving-widget):eq('+idx+')').after('<li class="moving-widget">'+wtitle_mousedown.name+'</li>').next().slideDown(200);
									}
									current_ignore = false;
								}else{
									current_ignore = true;
								}
								current_closest_row = idx;
								current_closest_col = col_idx;
								current_use_append = false;
							}
						}else if (!current_use_append || col_idx != current_closest_col){
							$('#organize-wlist .moving-widget:animated').remove();
							$('#organize-wlist .moving-widget').slideUp(200,function(){$(this).remove();});
							closest_col.find('ul').append('<li class="moving-widget">'+wtitle_mousedown.name+'</li>').find('.moving-widget').slideDown(200);
							current_closest_col = col_idx;
							current_use_append = true;
							current_ignore = false;
						}
					}else{
						$('#organize-wlist .moving-widget').slideUp(200,function(){$(this).remove();});
						current_ignore = true;
						current_closest_col = null;
					}
				}
				var o = $('#movable-wtitle');
				o.css({'left':e.pageX-2,'top':e.pageY-2});
			}
			e.preventDefault();
		}
	}).mouseup(function(){
		if (current_ignore === false){
			var to_kill = $('.nde-column:eq('+current_col+') .nde-window:eq('+current_row+')');
			if (current_use_append){
				to_kill.clone().appendTo($('.nde-column:eq('+current_closest_col+')')).hide().slideDown(300);
			}else{
				if (current_closest_row < 0){
					to_kill.clone().insertBefore($('.nde-column:eq('+current_closest_col+') .nde-window:eq(0)')).hide().slideDown(300);
				}else{
					to_kill.clone().insertAfter($('.nde-column:eq('+current_closest_col+') .nde-window:eq('+current_closest_row+')')).hide().slideDown(300);
				}
			}
			current_layout = [];
			to_kill.slideUp(300,function(){
				$(this).remove();
				var cmt_data = $('#widgets > .metadata').html();
				var numcols = $('.nde-column').length;
				if (typeof cmt_data == 'string' && cmt_data.search('awl') > -1){
					var awl = cmt_data.replace(/awl\{(\d+(?:[,;]\d+)*)\}/i,'$1').split(';');
					for (i in awl){
						awl[i] = awl[i].split(',');
					}
				}else{
					var awl = []; for(var i=0;i<numcols;i++){ awl[i] = [2]; }
				}
				var colidx = -1;
				var add_ad = null;
				$('.nde-column').each(function(){
					colidx++;
					current_layout.push([]);
					$(this).find('.nde-window:not(.w-ad)').each(function(){
						var wik = getWIK(this);
						current_layout[current_layout.length-1].push(wik);
					});
					var ccol = $(this);
					var at = -1;
					var ii = -1;
					var awln = awl[colidx].length-1;
					$(this).find('.nde-window.w-ad').each(function(){
						if (awln || ii == -1) ii = (ii<awln)?ii+1:0;
						at += Number(awl[colidx][ii]);
						if (ccol.find('.nde-window:not(.w-ad):eq('+at+')').length){
							$(this).insertAfter(ccol.find('.nde-window:not(.w-ad):eq('+at+')'));
						}else{
							$(this).remove();
						}
						//at++;
					});
					if (awln || ii == -1) ii = (ii<awln)?ii+1:0;
					if ($(this).find('.nde-window:not(.w-ad):gt('+at+')').length >= Number(awl[colidx][ii])
					 || (at == -1 && $(this).find('.nde-window:not(.w-ad)').length >= Number(awl[colidx][ii]))){
						at += Number(awl[colidx][ii]);
						add_ad = {col:colidx,row:at};
					}
				});
				
				dumont.addRequest({id:'wiklayout',tik:getTIK(),action:'layout',layout:current_layout},function(reply){
					debugWin(reply,false,'#ff0');
					debugWin(this,false,'#f0f');
				},true);
				if (add_ad != null)
					dumont.addRequest({tik:getTIK(),action:'widget/add',wid:'ad',col:add_ad.col,row:add_ad.row},function(reply){
						debugWin(reply,false,'#ff0');
						debugWin(this,false,'#f0f');
						$(reply.content).insertAfter('.nde-column:eq('+this.data.col+') .nde-window:not(.w-ad):eq('+this.data.row+')').hide().slideDown(300);
					});
			});
		}
		if ($('#movable-wtitle').length){
			$('#movable-wtitle').remove();
			$(document).xmodal.close();
		}
		wtitle_mousedown = false;
		current_col = null;
		current_row = null;
		current_closest_col = null;
		current_closest_row = null;
		current_use_append = false;
		current_ignore = null;
	});
	$('.nde-window .nde-wlt a').fadeOut(300).live('click',function(e){
		e.preventDefault();
	});
	$('.nde-window .nde-content form[method=post]:not(:has(input[type=file]))').live('submit',function(e){
		var wobj = $(this);
		var wik = getWIK(this);
		var waction = ($(this).parents('.settings').length)?'form/settings':'form/widget';
		var formact = $(this).attr('action');
		var formval = {};
		$(this).find('input:not(:checkbox):not(:radio), input:checkbox:checked, input:radio:checked, textarea, select').each(function(){
			var val = $(this).attr('name');
			if (val.indexOf('[') != -1){
				var p = val.split(']').shift().split('[');
				if (formval[p[0]] == undefined)
					formval[p[0]] = (p[1].length > 0)?{}:[];
				if (p[1].length > 0)
					formval[p[0]][p[1]] = $(this).val();
				else
					formval[p[0]].push($(this).val());
			}else{
				formval[val] = $(this).val();
			}
			$(this).attr('disabled','disabled');
		});
		//debug_mode = 2;
		debugWin(formact,false,'#ccc');
		debugWin(formval,false,'#ccc');
		dumont.doRequest({wik:wik,action:waction,formaction:formact,vars:formval},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			dumont.doRequest({wik:this.data.wik,action:'refresh'},function(reply){
				debugWin(reply,false,'#ff0');
				debugWin(this,false,'#f0f');
				$('.wik-'+this.data.wik+' .nde-content .content').fadeOut(500,function(){
					$(this).html(reply.content).fadeIn(500,function(){
						if (waction == 'form/settings') wobj.find('input, textarea, select').removeAttr('disabled');
					});
				});
			});
		});
		e.preventDefault();
	});
	$(document).bind('keydown', 'f8', function(e){
		$('#debug-stuff').toggle();
		e.preventDefault();
	}).bind('keydown', 'f9', function(e){
		dumont.sendRequest();
		e.preventDefault();
	}).bind('keydown', 'f10', function(e){
		if (debug_mode==2){
			debug_mode = false;
		}else if (debug_mode){
			debug_mode = 2;
		}else{
			debug_mode = true;
		}
		alert('Debug mode is: '+((debug_mode==2)?'EXTRA':debug_mode?'ON':'OFF'));
		e.preventDefault();
	});
	
	// Commented out because was causing unnecessary requests.
	// $(window).unload(function(e){
		// $.ajax({async:false});
		// dumont.sendRequest();
	// });
	
	// Opens up a user profile in a modal window
	$('.viewProfileLink').live('click', function(e){
		var otherUserBreaks = $(this).attr('href');
		var otherUser = otherUserBreaks.split('/').pop();
		
		dumont.doRequest({uid:dumont.uid,action:'user/viewprofile',viewuser:otherUser},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'View Profile',html:reply.content,width:600,height:400,anim:false});
		});
		e.preventDefault();
	});	

	// Render the tabs for the widgets
    $(".tabable").tabs();

    //First time popup new
	//The following lines remove ALL old cookies except PHPSESSID and site_first_visit
	var cookies = document.cookie.split(";");
	var date = new Date();
	date.setTime(date.getTime()-(1*24*60*60*1000));
	var expires = "; expires="+date.toGMTString(); //creates expires string in the past
	
	var host = document.domain;
	if(host.indexOf('.com') != -1)
		host = '.nnliving.com';
	else if(host.indexOf('.net') != -1)
		host = '.nnliving.net';
	else
		host = '';
	
	for (var i = 0; i < cookies.length; i++)	{
		var name = cookies[i].split("=")[0];
		name = name.replace(/^\s+|\s+$/g,"");//trim
		if(name != 'PHPSESSID' && name != 'site_first_visit'){
			document.cookie = name+"="+expires+";";//clears cookies where not path=/ 
			document.cookie = name+"="+expires+"; path=/";//clears cookies with path=/
			document.cookie = name+"="+expires+"; domain="+host;//clears cookies where not path=/ and all sub domains
			document.cookie = name+"="+expires+"; path=/; domain="+host;//clears cookies with path=/ and all sub domains
			//mutually exclusive, need all to definitely clear cookies
		}		
	}
	
	if($.cookie('site_first_visit') == null || $.cookie('site_first_visit') != 'no'){
    	$.cookie('site_first_visit', 'no', {expires: 365, path: '/', domain: host});
    	dumont.doRequest({uid:dumont.uid,action:'user/fpopup'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({html:reply.content,width:520,height:450,anim:false});
		});
	}
    //End First time popup

	// When widget links are clicked, perform the request then refresh
	
	$('.nde-window .nde-content .ajaxlink').live('click', function(e) {
		e.preventDefault();	
		$('*').css('cursor', 'progress');

		// If the link is not in the current tag, search for the next anchor tag 
		link = $(this).attr('href') ? $(this).attr('href') : $(this).find('a').attr('href');

		splits = link.split('/');
		requestParams = new Object;
		requestParams['uid'] = dumont.uid;
		requestParams['ajax_link'] = 'yes';

		
		// We may assume these parameters for the widgets
		/*
		requestParams['controller'] = 'widget';
		requestParams['action'] = 'index';
		requestParams['module'] = 'default';
		*/
		
		// Organize the URL into a usable request object
		var lastProperty = null;

		for (var seg in splits)
		{
			if (splits[seg] == '')
				continue;
		
			if (lastProperty == null)
				lastProperty = splits[seg];
			else
			{
				requestParams[lastProperty] = splits[seg];
				lastProperty = null;
			}
		}
		
		var wobj = $(this);
		var wik = getWIK(this);

		dumont.doRequest(requestParams,function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			dumont.doRequest({wik:wik,action:'refresh'},function(reply){
				debugWin(reply,false,'#ff0');
				debugWin(this,false,'#f0f');
				$('.wik-'+this.data.wik+' .nde-content .content').fadeOut(300,function(){
					$(this).html(reply.content).fadeIn(300,function(){
						$('*').css('cursor', '');
					});
				});
			});
		});
	});
	
	$('.reminder_toggle a').live('click', function(e){
		e.preventDefault();
		$(this).parents('div.reminder_toggle').fadeOut(200, function(){
			$('.reminder_form').fadeIn(200);
		});
	});
	
	$('.reminder_form a').live('click', function(e){
		e.preventDefault();
		$(this).parents('div.reminder_form').fadeOut(200, function(){
			$('.reminder_toggle').fadeIn(200);
		});
	});
	
	// Neighor updater control panel button - opens window with NU controls
	$('a#nu-cp').live('click', function(){
        window.open(this.href,'NUCP','location=0,status=0,scrollbars=1,width=775,height=550');
        return false;
	});
	$('.documents li a:not(.ajaxlink)').live('click', function(){
        window.open(this.href,'View Document','location=0,status=0,scrollbars=1,width=750,height=550');
        return false;
	});
	// End Nu control panel button
	
	// Invite window
	$('a#invite').click(function(e){
		dumont.doRequest({uid:dumont.uid,action:'user/invite'},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$(document).xmodal({title:'Invite',html:reply.content,width:525,height:350,anim:false});
		});
		e.preventDefault();
	});
	$('#invite-form form').live('submit',function(e){
		var emails = $(this).find('textarea#inviteemails').val();
		var regcode = $(this).has('input#addregcode-include:checked').length?$(this).find('input#addregcode-include').val():'';
		//debug_mode = 2;
		dumont.doRequest({uid:iotower_uid,action:'user/invite',emails:emails,regcode:regcode},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');
			$('#invite-form').parent().fadeOut(300,function(){
				$(this).html(reply.content).fadeIn(300);
			});
		});
		e.preventDefault();
	});
	// End invite window

	tcodecheck = null;
	checkRegcode = function(){
		var obj = $('form[action$="/user/register"] #regcode');
		if (obj.parent().find('img.status').length == 0)
			obj.parent().append('<img src="'+iotower_base_url+'/images/loading-icon.gif" class="status" width="16" height="16" alt="Checking..." style="margin-bottom:-3px;" />');
		else if (obj.parent().find('img.status:first').attr('alt') != 'Checking...')
			obj.parent().find('img.status:first').attr({src:iotower_base_url+'/images/loading-icon.gif',alt:'Checking...'});
		var code = obj.attr('value');
		dumont.addRequest({id:'codecheck',uid:dumont.uid,action:'user/registercheckcode',regcode:code},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');

			var obj = $('form[action$="/user/register"] #regcode');
			if (reply.content == '0')
			{
				obj.parent().find('img.status:first').attr({src:iotower_base_url+'/images/no-icon.png',alt:'Registration code is invalid.'});
				//obj.css('background-color','pink');
				
				if ($('.errors-user').length == 0)
					$('ul.errors').prepend('<li class="errors-user">Registration code is not valid! (If you don\'t know your registration code, leave the field blank)</li>');
			}
			else
			{
				obj.parent().find('img.status:first').attr({src:iotower_base_url+'/images/yes-icon.png',alt:'Registration code is valid.'});
				//obj.css('background-color','limegreen');
				$('.errors-user').remove();
			}
		}, true);
	}

	$('form[action$="/user/register"] #regcode').live('keyup', function() {
		clearTimeout(tusercheck);
		if ($(this).parent().find('img.status').length == 0)
			$(this).parent().append('<img src="'+iotower_base_url+'/images/loading-icon.gif" class="status" width="16" height="16" alt="Checking..." style="margin-bottom:-3px;" />');
		else
			$(this).parent().find('img.status:first').attr({src:iotower_base_url+'/images/loading-icon.gif',alt:'Checking...'})
		var user = $(this).attr('value');
		tcodecheck = setTimeout('checkRegcode();',1000);
	});

	tusercheck = null;
	checkUsername = function(){
		var obj = $('form[action$="/user/register"] #username');
		if (obj.parent().find('img.status').length == 0)
			obj.parent().append('<img src="'+iotower_base_url+'/images/loading-icon.gif" class="status" width="16" height="16" alt="Checking..." style="margin-bottom:-3px;" />');
		else if (obj.parent().find('img.status:first').attr('alt') != 'Checking...')
			obj.parent().find('img.status:first').attr({src:iotower_base_url+'/images/loading-icon.gif',alt:'Checking...'});
		var user = obj.attr('value');
		dumont.addRequest({id:'usercheck',uid:dumont.uid,action:'user/registercheckuser',username:user},function(reply){
			debugWin(reply,false,'#ff0');
			debugWin(this,false,'#f0f');

			var obj = $('form[action$="/user/register"] #username');
			if (reply.content == '0')
			{
				obj.parent().find('img.status:first').attr({src:iotower_base_url+'/images/no-icon.png',alt:'Username taken.'});
				//obj.css('background-color','pink');
				
				if ($('.errors-user').length == 0)
					$('ul.errors').prepend('<li class="errors-user">This username already exists!</li>');
			}
			else
			{
				obj.parent().find('img.status:first').attr({src:iotower_base_url+'/images/yes-icon.png',alt:'Username available.'});
				//obj.css('background-color','limegreen');
				$('.errors-user').remove();
			}
		}, true);
	}
	$('form[action$="/user/register"] #username').live('keyup', function() {
		clearTimeout(tusercheck);
		if ($(this).parent().find('img.status').length == 0)
			$(this).parent().append('<img src="'+iotower_base_url+'/images/loading-icon.gif" class="status" width="16" height="16" alt="Checking..." style="margin-bottom:-3px;" />');
		else
			$(this).parent().find('img.status:first').attr({src:iotower_base_url+'/images/loading-icon.gif',alt:'Checking...'})
		var user = $(this).attr('value');
		tusercheck = setTimeout('checkUsername();',1000);
	});
	tabLoadingDepth = 0;
	beginTabLoading = function(){
		tabLoadingDepth++;
		if (tabLoadingDepth == 1){
			$('body').append('<div id="tab-loading-bg"></div><div id="tab-loading">Loading...</div>');
			$('#tab-loading-bg').css({
				top: $('#widgets').offset().top,
				height: $('#widgets').outerHeight(),
				opacity: 0.75
			});
			$('#tab-loading').css({
				top: $('#widgets').offset().top+128
			});
			animateTabLoading(true);
		}
	}
	endTabLoading = function(all){
		tabLoadingDepth--;
		if (tabLoadingDepth == 0 || all == true){
			$('#tab-loading-bg, #tab-loading').remove();
			animateTabLoading(false);
			tabLoadingDepth = 0;
		}
	}
	animateTabLoading = function(go){
		if (go == true){
			var off = $('#tab-loading').css('background-position').split(' ');
			var offy = parseInt(off[1])
			//alert(parseInt(offy[1]));
			if (offy <= -1088){
				$('#tab-loading').css('background-position', '0px 0px');
			}else{
				$('#tab-loading').css('background-position', '0px '+(offy-64)+'px');
			}
			atl_t = setTimeout('animateTabLoading(true);',50);
		}else{
			clearTimeout(atl_t);
		}
	}
	//animateTabLoading(true);
	//beginTabLoading();
	
	dumont.sendRequest();
	
	// If there are ads, prep for ad rotation.
	if (ads != null){
		// Set rotation interval.
		adRotation(); // The first execution will load the next ads in rotation.
		setInterval('adRotation();',10000); // Rotate ads every 6 seconds
	}

	var hashRequest = window.location.hash;
	if(hashRequest == '#launchRegister')	{
		$('#head-register').click();
	}
	if(hashRequest == '#launchInvite')	{
		$('.tab-invite').click();
	}
	if(hashRequest == '#savings')	{
		$('.savings-tab-link').click();
	}

	// Modal for Delete Button
	$('.bn-delete').live('click',function(e){
		var go = $(this).attr('href');
		$(document).xmodal({
			title:'Delete',
			html:'<p>Are you sure you want to remove this?</p>',
			width:280,
			height:130,
			type:'confirm',
			callback:function(reply){
				if (reply) window.location = go;
			},
			speed:0.2
		});
		e.preventDefault();
	});
	//End Modal for Delete option.
});





var exitalert_active = 0;

// Cross browser event handling for IE 5+, NS6+ and Gecko
 function addEvent(elm, evType, fn, useCapture)
 {
 	if (elm.addEventListener)
 	{
 		// Gecko
 		elm.addEventListener(evType, fn, useCapture);
 		return true;
 	}
 	else if (elm.attachEvent)
 	{
 		// Internet Explorer
 		var r = elm.attachEvent('on' + evType, fn);
 		return r;
 	}
 	else
 	{
 		// nutscrape?
 		elm['on' + evType] = fn;
 	}
 }
 
 // Add Listeners
 function addListeners(e)
 {
 	// Before unload listener
 	  addEvent(window, 'beforeunload', exitAlert, false);
 }
 
 // Exit Alert
 function exitAlert(e)
 {
 	// default warning message
	//alert(exitalert_active);
	if (exitalert_active > 0){
		var msg = "You will lose information if it has not already been saved.";
	 
		// set event
		if (!e) { e = window.event; }
		if (e) { e.returnValue = msg; }
	 
		// return warning message
		return msg;
	}
 }
 
 // Initialise
addListeners();



