var facebook = document.getElementById('facebook_identifier');
if (facebook) { facebook = parseInt(facebook.value,10); }
var bg_prefix = facebook ? 'FB' : '';
var coupon_bg_image  = (typeof (ci_CustomBgImage)!= "undefined" ? ci_CustomBgImage : bg_prefix+"podBgDash.jpg");
var coupon_bg_selected_image  = (typeof (ci_CustomBgSelImage)!= "undefined" ? ci_CustomBgSelImage : bg_prefix+"podBgDashSel.jpg");
var clipButtonImage  = (typeof (ci_CustomClipButtonImage)!= "undefined" ? ci_CustomClipButtonImage : "clip_button_red1.gif");
var clipButtonSelImage  = (typeof (ci_CustomClipButtonSelImage)!= "undefined" ? ci_CustomClipButtonSelImage : "clip_button_red2.gif");
var coupons_per_page_in = 0;
var coupons_per_page = (coupons_per_page_in > 1 ? coupons_per_page_in : 10);
var current_page = 0
var theForm
var printer_link_protocol = ('https:' == document.location.protocol ? 'https' : 'http');
var printer_link = printer_link_protocol+"://insight.coupons.com/cos20/PrintManager.ASPX"
var printer_message = ""
var msg_width = facebook ? 500 : 522;
var msg_template = "<table rules='none' style='visibility: visible; border:1px dashed gray; width: "+msg_width+"px; background: url(/images/gallery/shadow.jpg);'><tr><td style='width: 40px; height: 34px; text-align: center;'><img class=ci_css_img style='margin: 2px; width: 30px; height: 28px;' src='/images/gallery/information.gif'></td><td style='color: #C07410; width: 98%; padding-left: 4px; vertical-align: middle;'>##msg##</td></tr></table>"
var timeoutHandler

// This is how coupons.com does CPC stuff - we need to redirect the user through their thing
function PopClickInfo(couponId, couponType, Link) {
//{{{
   	/* 
	var remString = GetQueryString();
    var cidLoc = remString.indexOf("cid=");
    if (cidLoc > 0)
        remString = remString.replace("cid=" + GetQueryStringValue("cid"), '');
	*/
	//var ciTrackerLink = "http://print.coupons.com/ccr/RecordClick.aspx?cid=" + couponId + "&ctype=" + couponType + "&" + remString + "&link=" + Link";
	//var ciTrackerLink = "http://print.coupons.com/ccr/RecordClick.aspx?cid="+couponId+"&ctype="+couponType+"&link="+Link;
	//var ciTrackerLink = "http://www.coupons.com/RecordClick.aspx?go=14807hz7010&cid="+couponId+"&ctype="+couponType+"&link="+Link;
	//var ciTrackerLink = "http://print.coupons.com/couponweb/RecordClick.aspx?cid="+couponId+"&ctype="+couponType+"&link="+Link;
	var ciTrackerLink = Link;
	var ourTrackerLink = '';
	var completeLink = ciTrackerLink;

    window.open(completeLink, "", "");
	//return;		
	var request_params = {'ajax_request':"hidden_ci_click", 'device_id':window.ci_vUserCode, 'coupons':couponId}
//alert("JBB printing: "+window.ci_vUserCode+"; "+ci_vUserCode);
	ajaxRequest({"params":request_params});
	//ajaxRequest({'params':{'ajax_request':'track_ci_click'},'element_id':'hidden_ci_click', 'display_loading':false});
//}}}
}

function getTheForm()
{
//{{{
	theForm = document.forms['aspnetForm']
	if (!theForm)
	{
		theForm = document.aspnetForm;
	}
//}}}
}

function ajaxRequest(input)
{
//{{{
	var display_loading = (typeof(input['display_loading'])!="undefined") ? input['display_loading'] : true;
	var loading_text = (typeof(input['loading_text'])!="undefined") ? input['loading_text'] : "Loading..."
	var calling_script = (typeof(input['calling_script'])!="undefined") ? input['calling_script'] : "coupon_gallery.php"
	// JBB - made this only pageContent - for banners this makes page jumpy
	if(display_loading)
	{
		$('#'+input['element_id']).html("<BR><BR><BR><CENTER><IMG src='/images/gallery/waiting_50.gif' /><BR>"+loading_text+"</CENTER>")
		//{{{ Deprecated on account of IE
		/*
		if(input['callback_function'])
		{
			$('#'+input['element_id']).load("coupon_gallery.php",input['params'], function(data){ input['callback_function'](data) })
		}
		else
		{
			$('#'+input['element_id']).load("coupon_gallery.php",input['params'])
		}
		*/
		//}}}
	}
	//{{{ Deprecated on account of IE
	/*
	else
	{
		if(input['callback_function'])
		{
			jQuery.post("coupon_gallery.php",input['params'], function(data){ input['callback_function'](data) } )
		}
		else
		{
			jQuery.post("coupon_gallery.php",input['params'])
		}
	}
	*/
	//}}}
	
	// JBB - made this so it is dynamic for more than 1 script
	// MRG - using window.location will always resubmit parameters from the query string; chopped those off. base_url defined above
	// JBB - base_url fails since our scripts are not top-level scripts.  we end up with pages inside pages.  adding 'calling_script' parameter
	// JBB - fixed with "calling_script" variable.  defaults to coupon_gallery.php.  got a little fancy in getZipTargetinSearchtastic to pass in the shortened pathname, but it works!
	//jQuery.post("coupon_gallery.php",input['params'], function(data){ input['data'] = data; ajaxResult(input) } )
	//jQuery.post(window.location,input['params'], function(data){ input['data'] = data; ajaxResult(input) } )
	//jQuery.post(base_url,input['params'], function(data){ input['data'] = data; ajaxResult(input) } )
	jQuery.post(calling_script,input['params'], function(data){ input['data'] = data; ajaxResult(input) } )

	//FB.XFBML.parse(input['element_id']);
//}}}
}

function ajaxResult(input)
{
//{{{ Oh how I loathe IE
	if(input['element_id'])
	{
		var element = $('#'+input['element_id'])[0]
		element.innerHTML = input['data']
	}
	
	if(input['callback_function'])
	{
		input['callback_function'](input['data'])
	}
//}}}
}

function setNavigation(selected_id)
{
//{{{
	var tmp_links = $('#ci_css_mainNavigation').find('a')
	var links = new Array()
	
	//{{{ Dirty reordering; don't look
	var first_links = new Array()
	var last_links = new Array()
	for(var i=0; i<tmp_links.length; i++)
	{
		if(tmp_links[i].id && (tmp_links[i].id=="register_menu" || tmp_links[i].id=="sing_up_menu"))
		{
			first_links[first_links.length] = tmp_links[i]
		}
		else
		{
			last_links[last_links.length] = tmp_links[i]
		}
	}
	links = first_links.concat(last_links)
	//}}}
	
	for(var i=0; i<links.length; i++)
	{
		var link = links[i]
		if(link.id && link.id==selected_id)
		{
			link.className = "on"
			if(i==(links.length-1))
			{
				$('#menu_closer').addClass("on")
			}
		}
		else
		{
			link.className = "off"
			if(i==(links.length-1))
			{
				$('#menu_closer').removeClass("on")
			}
		}
	}
//}}}
}

function toggleCouponBackground(allowPrint,evnTyp,cid)
{
//{{{								   
	if( allowPrint != 1 ) 
	{
		return;
	}
	
	var coupon_table = $("#coupon_table_"+cid)[0];
	if(evnTyp == 1) //mouseover
	{
		coupon_table.style.background = 'url(/images/gallery/' + coupon_bg_selected_image + ') no-repeat';
	}
	else //mouseout
	{
		if(isCouponChecked(cid))
			coupon_table.style.background = 'url(/images/gallery/'+ coupon_bg_selected_image + ') no-repeat';
		else
			coupon_table.style.background = 'url(/images/gallery/' + coupon_bg_image + ') no-repeat';
	}
//}}}
}

function isCouponChecked(a)
{
//{{{
	try {	
		var b=document.getElementById("PrintCart").value;
	} catch(Err) {}
//}}}
	return(b!=null&&b.indexOf(a)>-1?"checked":"")
}

function toggleCoupon(CID)
{
//{{{
	var coupon = $("#coupon_table_"+CID)[0]
	var coupon_table = $("#coupon_"+CID+"_checkbox_table")[0]
	
	if(coupon_table)
	{
		var bCIDInCart = (coupon) ? TglCart(CID) : false
		
		if(bCIDInCart)
		{
			if(coupon)
			{
				coupon.style.backgroundImage = "url(/images/gallery/" + coupon_bg_selected_image + ")";
			}
			
			coupon_table.style.backgroundImage = "url(/images/gallery/" + clipButtonSelImage + ")";
		}
		else
		{
			if(coupon)
			{
				coupon.style.backgroundImage = "url(/images/gallery/" + coupon_bg_image + ")";
			}
			
			coupon_table.style.backgroundImage = "url(/images/gallery/" + clipButtonImage + ")";
		}
	}
//}}}
}

function addCoupon(remote_id)
{
//{{{
	var box = $("#cpcartchk"+remote_id)[0]
	
	if(box && !box.checked)
	{
		toggleCoupon(remote_id)
	}
//}}}
}

function TglCart(b)
{
//{{{
	var a=b+"";
	var c=document.getElementById("PrintCart").value;
	
	if(c==null)
	{
		AddCart(b)
	}
	else
	{
		if(c.indexOf(a)>-1)
		{
			RemoveFromCart(b)
		}
		else
		{
			AddCart(b)
		}
	}
	
//}}}
	return(document.getElementById("PrintCart").value.indexOf(a)>-1)
}

function RemoveFromCart(e,f)
{
//{{{
	if(f=="undefined"||f==null)
	{
		f=true
	}
	
	if(document.getElementById("cpcartchk"+e)!=null)
	{
		document.getElementById("cpcartchk"+e).checked=false
	}
	
	var g=document.getElementById("PrintCart").value;
	var c=document.getElementById("PrintCartAmt").value.length>0 ? parseInt(document.getElementById("PrintCartAmt").value) : 0;
	
	if(g.length>0)
	{
		var d=e+"";
		var a=g.split(",");
		if((a.length==1)&&(a[0]==d))
		{
			g="";
			c=0
		}
		
		if(a.length>1)
		{
			for(remove_i=a.length-1;remove_i>=0;remove_i--)
			{
				if(a[remove_i]==d)
				{
					a.splice(remove_i,1)
				}
			}
			g=a.join(",");
			
			
			var cbox = document.getElementById('cpcartchk'+d);
			if(cbox)
			{
				c = c-parseInt(cbox.getAttribute("cvalue"))
				if(!g)
				{
					c = 0
				}
			}
		}
		
		document.getElementById("PrintCart").value=g;
		document.getElementById("PrintCartAmt").value=c
	}
	
	if(f)
	{
		UpdateCartCount(CheckForCartCoupon(g));
		UpdateCartSessionCookie(g.replace(/,/g,'~'))
	}
//}}}
}

function AddCart(d,e)
{
//{{{
	if(e=="undefined"||e==null)
	{
		e=true
	}
	
	var b= (document.getElementById("PrintCartAmt").value.length>0) ? parseInt(document.getElementById("PrintCartAmt").value) : parseInt(0);
	var g=0;
	
	var cbox = document.getElementById('cpcartchk'+d);
	if(cbox)
	{
		g = parseInt(cbox.getAttribute("cvalue"))
		if(!g)
		{
			g = 0
		}
	}
	var c=d+"";
	
	if(document.getElementById("cpcartchk"+d)!=null)
	{
		document.getElementById("cpcartchk"+d).checked=true
	}
	
	if(document.getElementById("PrintCart")==null)
	{
		document.getElementById("PrintCart").value=c;
		document.getElementById("PrintCartAmt").value=g
	}
	else
	{
		var f=document.getElementById("PrintCart").value;
		if(f.indexOf(c)==-1)
		{
			if(f.length>0)
			{
				f=f+","
			}
			f=f+c;
			b=b+g
		}
		
		document.getElementById("PrintCart").value=f;
		document.getElementById("PrintCartAmt").value=b
	}
	
	if(e)
	{
		UpdateCartCount(CheckForCartCoupon(f));
		UpdateCartSessionCookie(f.replace(/,/g,'~'))
	}
//}}}
}

function UpdateCartCount(count)
{
//{{{
	
	/// Update the clipped coupon count
	if (document.getElementById("ClippedCouponsTD") != null)
	{
		document.getElementById("ClippedCouponsTD").innerHTML = (count > 0 ? count : "0");
	}

	//Update the clipped coupon cart table
	if (document.getElementById("CartWrapper") != null)
	{
		var currPC = document.getElementById("PrintCart").value;
		var cartArray = currPC.length > 0 ? currPC.split(",") : new Array();
		document.getElementById("CartWrapper").innerHTML = ReturnCartHTML(cartArray)
	}
//}}}
}

function UpdateCartSessionCookie(c)
{
//{{{
	var b = GetCookie("clipped_coupons_cookie");
	var a = (b!=null && b.indexOf("CLIENTCOOKIE")>-1 ? b.substring(b.indexOf("CLIENTCOOKIE")) : "");
	
	SetCookie("clipped_coupons_cookie",(c!=null && c.length>0 ? c+"~":"") + a,0,"/",null,null)
//}}}
}

function CheckForCartCoupon(printcart)
{
//{{{
	var count=0;
	
	try
	{
		var cart=new Array();
		if(printcart.constructor.toString().indexOf("Array")==-1)
		{
			cart=printcart.toString().split(",")
		}
		else
		{
			cart=printcart
		}
		
		count=(cart.length>1?cart.length:(printcart.length>0?1:0))
	}
	catch(err){}
//}}}	
	return count
}

function ReturnCartHTML(cartArray)
{
//{{{
	var cartTotal = 0;
	cartTotal = document.getElementById("PrintCartAmt").value.length > 0 ? parseInt(document.getElementById("PrintCartAmt").value) : 0;
	var strCartTotal = "$" + (cartTotal > 0 ? (cartTotal / 100) : "0.00");

	if (strCartTotal.indexOf(".") == -1)
		strCartTotal += ".00";
	else
		if (strCartTotal.substring(strCartTotal.indexOf(".")).length <= 2)
			strCartTotal += "0";

	var cart_html =  '<div id="ci_css_couponCarrier" class="ci_css_portlet">' +
	'<div class="ci_css_top">&nbsp;</div>' +
	'<div class="ci_css_middle">' +
	'<h2>Coupon Carrier</h2>' +
	'<dl>' +
	'<dt><img src="/images/gallery/carriertextmoney.gif" alt="Money Saved" /></dt>' +
	'<dd id="ClippedCouponTotalTD">' +
	strCartTotal +
	'</dd>' +
	'</dl>' +
	'<dl class="last">' +
	'<dt><img src="/images/gallery/carriertextclipped.gif" alt="Coupons Clipped" /></dt>' +
	'<dd id="ClippedCouponsTD">' +
	cartArray.length +
	'</dd>' +
	'</dl>' +
	'</div>' +
	'<div class="ci_css_bottom">&nbsp;</div>' +
	'</div>';
//}}}
	return cart_html
}

function GetCookie(name)
{
//{{{
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	
	while(i<clen)
	{
		var j=i+alen;
		
		if(document.cookie.substring(i,j)==arg)
		{
			var eCookieIx=document.cookie.indexOf(";",j);
			
			if(eCookieIx==-1)
			{
				eCookieIx=document.cookie.length
			}
			return unescape(document.cookie.substring(j,eCookieIx))
		}
		
		i=document.cookie.indexOf(" ",i)+1;
		
		if(i==0)
		{
			break
		}
	}
	
//}}}
	return ''
}

function GetCookieVal(cookie,name)
{
///{{{
	var value="";
	var sValIx=cookie.indexOf(name+"=");
	
	if(sValIx>=0)
	{
		eValIx=cookie.indexOf("&",sValIx+name.length+1);
		
		if(eValIx==-1)
		{
			eValIx=cookie.length
		}
		
		value=cookie.substring(sValIx+name.length+1,eValIx)
	}
	
//}}}
	return value
}

function SetCookie(name,value,expDays,path,domain,secure)
{
//{{{
	var expDate=new Date();
	expDate.setTime(expDate.getTime()+(expDays*1000*60*60*24));
	
	document.cookie=name+"="+value+((expDays>0)?";expires="+expDate.toGMTString():"")+((path)?";path="+path:"")+((domain)?";domain="+domain:"")+((secure)?";secure":"")
//}}}
}

function SelectAllOffers(pageNo, elem)
{
//{{{
	var boxes = $('#OffersPageInnerContent').find('input')//.filter('[@class=ci_css_checkbox]')
	
	var flag = elem.checked;
	
	var topPager = document.getElementById("pager_0");
	var bottomPager = document.getElementById("pager_1");
	var topPagerSpan = topPager.getElementsByTagName('span')[0];
	var bottomPagerSpan = bottomPager.getElementsByTagName('span')[0];
	var topCheckbox = topPager.getElementsByTagName('input')[0];
	var bottomCheckbox = bottomPager.getElementsByTagName('input')[0];
	
	if (flag)
	{
		for(var i=0; i<boxes.length; i++)
		{
			var box = boxes[i]
			
			if(!box.checked)
			{
				box.checked = true
				var id = GetNumericValue(box.name)
				toggleCoupon(id)
			}
		}
		
		topPagerSpan.innerHTML = "Deselect All";
		bottomPagerSpan.innerHTML = "Deselect All";
		topCheckbox.checked = true;
		bottomCheckbox.checked = true;
		//setTimeout("SelectAll();", 300);
	}
	else
	{
		for(var i=0; i<boxes.length; i++)
		{
			var box = boxes[i]
		   
			if(box.checked)
			{
				box.checked = false
				var id = GetNumericValue(box.name)
				toggleCoupon(id)
			}
		}
		
		topPagerSpan.innerHTML = "Select All";
		bottomPagerSpan.innerHTML = "Select All";
		topCheckbox.checked = false;
		bottomCheckbox.checked = false;
		//setTimeout("UnSelectAll();", 300);
	}
//}}}
}

function getCID(i)
{
//{{{
	var ClipDivHTML = document.getElementById("ClipDiv" + i).innerHTML.toString();
	var CID = ClipDivHTML.substring(ClipDivHTML.indexOf('cpcartchk') + 9, ClipDivHTML.indexOf('cpcartchk') + 20);
	
	CID = CID.substring(0, CID.indexOf(' '));
	CID = GetNumericValue(CID);
//}}}
	return CID;
}

function GetNumericValue(str)
{
//{{{
	if(str==null)
	{
		return ""
	}
	
	var numVal="";
	for(var i=0;i<str.length;i++)
	{
		if(str.charAt(i)>="0"&&str.charAt(i)<="9")
		{
			numVal+=str.charAt(i)
		}
	}
	
//}}}
	return numVal
}

function GoToPage(destination_page)
{
//{{{
	//TrackPagesViewed(i);
	
	if(current_page!=destination_page)
	{
		var pages = getCouponPages();
		for(var i=0; i<pages.length; i++)
		{
			$('#'+pages[i].id).hide()
		}
		//setTimeout("$('#coupon_page_'+i).animate({width: 'show', direction: 'left'},1000)", 1000)
		$('#coupon_page_'+destination_page).show()
		current_page = destination_page
		RenderPageNav()
	
	}
	// JBB
	if (!facebook) {
		ajaxRequest({'params':{'ajax_request':'rotate_right_banner'},'element_id':'right_banner_container', 'display_loading':false});
		ajaxRequest({'params':{'ajax_request':'rotate_bottom_banner'},'element_id':'bottom_banner_container', 'display_loading':false});
	}
	
//}}}
}

function ShowPage(i)
{
	$('#coupon_page'+i).animate({width: 'show'},1000)
}

function GoToPreviousPage()
{
//{{{
	if(current_page!=1)
	{
		GoToPage(current_page-1)
	}
//}}}
}

function GoToNextPage()
{
//{{{
	var num_pages = getCouponPages().length
	if(!current_page)
	{
		current_page = 1
	}
	
	if(current_page<num_pages)
	{
		GoToPage(current_page+1)
	}
//}}}
}

function RenderPageNav()
{
//{{{
	var divs = Array("pageListBar0","pageListBar1")
	
	for(d=0; d<divs.length; d++)
	{
		var div_name = divs[d]
		var links = $('#'+div_name).find('a')
		var link_groups = $('#'+div_name).find("[id^=nav_link_group_]").filter(function() { return this.id.match(/^nav_link_group_\d+_\d+$/)} )
		var current_link_group
		
		for(i=0; i<links.length; i++)
		{
			var link = links[i]
			var rel = link.getAttribute("rel")
			
			if(rel)
			{
				if(rel==current_page)
				{
					link.className = "ci_css_current"
					current_link_group = link.parentNode
				}
				else
				{
					link.className = ""
				}
			}
		}
		
		//alert("selected: "+current_link_group.id)
		for(i=0; i<link_groups.length; i++)
		{
			var style = (current_link_group && link_groups[i].id==current_link_group.id) ? "inline" : "none";
			link_groups[i].style.display = style
		}
	}
//}}}
}

function selectCouponsByAttribute(attribute,value)
{
//{{{
	sortCouponsByAttribute(attribute,value);
	
	GoToPage(1)
//}}}
}

function sortCouponsByAttribute(sort_attribute,selected_attribute)
{
//{{{
	var containers = getCouponContainers()
	var pages = getCouponPages()
	var sorted_containers = Array()
	var num_rows = 5
	var num_columns = 2
	var tmp_pages = Array()
	
	//{{{ Sort all of the coupons/containers
	var selected_containers = Array()
	var remaining_containers = Array()
	for(var i=0; i<containers.length; i++)
	{
		if(containers[i].getAttribute(sort_attribute) == selected_attribute)
		{
			selected_containers.push(containers[i])
		}
		else
		{
			remaining_containers.push(containers[i])
		}
	}
	sorted_containers = selected_containers.concat(remaining_containers)
	
	/*
	var str = ""
	for(var i=0; i<containers.length; i++)
	{
		str+= containers[i].id+"\t"+sorted_containers[i].id+"\n"
	}
	alert(str)
	*/
	
	//}}}
	
	buildPages(sorted_containers)
//}}}
}

function buildPages(sorted_containers)
{
//{{{
	var pages = getCouponPages()
	var num_rows = Number($('#coupon_page_rows').val())
	var num_columns = Number($('#coupon_page_columns').val())
	var tmp_pages = Array()
	
	//{{{ Rebuild the pages
	for(page_counter=0; page_counter<pages.length; page_counter++)
	{
		var rows = new Array()
		for(var row_counter=0; row_counter<num_rows; row_counter++)
		{
			var row = "<TR class='ci_css_tr'>\n";
			
			///{{{ Build each column (table cell)
			for(var column_counter=0; column_counter<num_columns; column_counter++)
			{
				var cell = ""
				//{{{ If we still have coupons left get the display for the next one. If not, use &nbsp
				if(sorted_containers.length)
				{
					var coupon = sorted_containers.shift();
					cell = (coupon.outerHTML) ? coupon.outerHTML : new XMLSerializer().serializeToString(coupon)
				}
				else
				{
					cell = "&nbsp;";
				}
				//}}}
				
				row+= "<TD id='' class='ci_css_td'>"+cell+"</TD>"
			}
			///}}}
			
			row+= "</TR>\n";
			rows.push(row);
		}
		tmp_pages[page_counter] = "<TABLE id='coupon_grid_"+(page_counter+1)+"' class='ci_css_table coupon_grid'>\n"+rows.join("\n")+"</TABLE>"
	}
	//}}}
	
	//{{{ Assign the pages
	//var str = ""
	for(var i=0; i<pages.length; i++)
	{
		//str+= pages[i].id+"\n"
		pages[i].innerHTML = tmp_pages[i]
	}
	//alert(str)
	//}}}
	
//}}}
}

function resetCouponOrder()
{
//{{{
	var tmp_str = $('#coupons_original_order').val()
	var coupon_codes = tmp_str.split("~")
	var sorted_containers = new Array()
	
	for(var i=0; i<coupon_codes.length; i++)
	{
		var container = $("#coupon_table_"+coupon_codes[i])[0]
		if(container)
		{
			sorted_containers.push(container)
		}
	}
	
	buildPages(sorted_containers)
	GoToPage(1)
//}}}
}

function getCouponContainers()
{
	return $("[id^=coupon_table_]").filter(function() { return this.id.match(/^coupon_table_\d+$/)} )
}

function getCouponPages()
{
	return $("[id^=coupon_page_]").filter(function() { return this.id.match(/^coupon_page_\d+$/)} )
}

function getCategoryLinks()
{
	return $("[id^=lnkCat]")
}

function getBrandLinks()
{
	return $("[id^=lnkBrand]").filter(function() { return this.id.match(/^lnkBrand\d+$/)} )
}

function getSelectedCoupons()
{
	return $("[id^=cpcartchk]").filter(function() { return (this.id.match(/^cpcartchk\d+$/) && this.checked)} )
}

function HighlightLink(selected_option)
{
//{{{
	//{{{ Old code
	/*
	for(var b=0;b<6;b++)
	{
		if(document.getElementById("lnkBrand"+b)!=null)
		{
			document.getElementById("lnkBrand"+b).className="ci_css_CategoryLink"
		}
	}
	
	for(var b=0;b<ci_categories.length;b++)
	{
		if(document.getElementById("lnkCat"+b)!=null)
		{
			document.getElementById("lnkCat"+b).className="ci_css_CategoryLink"
		}
		
		if(document.getElementById("catmenu_"+ci_categories[b].category)!=null)
		{
			for(var a=0;a<ci_categories[b].subCategories.length;a++)
			{
				if(document.getElementById("sublnkCat_"+ci_categories[b].category+a)!=null)
				{
					document.getElementById("sublnkCat_"+ci_categories[b].category+a).className="ci_css_CategoryLink"
				}
			}
		}
	}
	
	if(document.getElementById("lnkCatShowAll")!=null)
	{
		document.getElementById("lnkCatShowAll").className="ci_css_CategoryLink"
	}
	
	if(document.getElementById("lnkCatExp")!=null)
	{
		document.getElementById("lnkCatExp").className="ci_css_CategoryLink"
	}
	*/
	//}}}
	
	var categories = getCategoryLinks()
	var brands = getBrandLinks()
	
	for(var i=0; i<categories.length; i++)
	{
		categories[i].className = "ci_css_CategoryLink"
	}
	
	for(var i=0; i<brands.length; i++)
	{
		brands[i].className = "ci_css_CategoryLink"
	}
	
	selected_option.className = "ci_css_CategoryLinkClicked"
//}}}
}

function PrtCartHandling(clicked_button)
{
//{{{
	var cart = $("#PrintCart")[0];
	//alert("JBB trying to print: "+window.ci_vUserCode+"; "+ci_vUserCode);
	
	//{{{ Coupons were selected; print if we can
	if (cart != null && cart.value.length > 0)
	{
		HideBothMsgs(clicked_button)
		if(!window.ci_vUserCode || window.ci_vUserCode=="-1")
		{
			var request_params = {'ajax_request':"install_printer_page", 'facebook':facebook}
			ajaxRequest({"params":request_params, "element_id":"pageContent"});
			//setNavigation('install_menu')
		}
		else
		{
			document.getElementById("printCouponButton").href = null;
			//setTimeout("document.getElementById(\"printCouponButton\").href = \"javascript:PrtCartHandling('PrintBtnA0'); return false;\"",4000);
			//{{{ Get all the selected coupon IDs
			var selected_coupons = getSelectedCoupons()
			var coupon_ids = new Array()
			for(var i=0; i<selected_coupons.length; i++)
			{
				coupon_ids.push(GetNumericValue(selected_coupons[i].id))
			}
			//}}}
			
			// Make the call to get the print token
			var request_params = {'ajax_request':"get_print_token", 'device_id':window.ci_vUserCode, 'coupons':coupon_ids.join('~')}
			//alert("JBB printing: "+window.ci_vUserCode+"; "+ci_vUserCode);
			ShowBothMsgs("Printing...")
			ajaxRequest({"params":request_params, "callback_function":initiatePrinter});
			
		}
	}
	//}}}
	//{{{ No coupons were selected; inform them of such
	else
	{
		if (clicked_button != null)
		{
			//ShowMsg(clicked_button, "Please select coupons by clicking on checkboxes next to each offer.")
			ShowBothMsgs("Please select coupons by clicking on checkboxes next to each offer.")
		}
	}
	//}}}
	
//}}}
}

function ShowMsg(srcID, msg)
{
//{{{
	/*
	if (srcID == 'PrintNowA' || srcID == 'PrintBtnA1')
	{
		ShowFooterMsg(msg);
	}
	else
	{
		ShowHeaderMsg(msg);
	}
	*/
	ShowBothMsgs(msg)
//}}}
}

function ShowBothMsgs(msg)
{
//{{{
	ShowHeaderMsg(msg)
	ShowFooterMsg(msg)
//}}}
}

function HideMsg(srcID)
{
//{{{
	/*
	if (srcID == 'PrintNowA' || srcID == 'PrintBtnA1')
	{
		HideFooterMsg();
	}
	else
	{
		HideHeaderMsg();
	}
	*/
	HideBothMsgs()
//}}}
}

function ShowHeaderMsg(msg)
{
//{{{
	var el = $("#MsgHeaderTD")[0]
    el.style.display = "block";
    el.innerHTML = msg_template.replace("##msg##",msg)
//}}}
}

function HideBothMsgs()
{
//{{{
	HideHeaderMsg()
	HideFooterMsg()
//}}}
}

function HideHeaderMsg()
{
//{{{
	document.getElementById("MsgHeaderTD").style.display = "none";
	document.getElementById("MsgHeaderTD").innerHTML = "";
//}}}
}

function ShowFooterMsg(msg)
{
//{{{
	var el = $("#MsgFooterTD")[0]
	el.style.display = "block";
	el.innerHTML = msg_template.replace("##msg##",msg)
//}}}
}

function HideFooterMsg()
{
//{{{
	document.getElementById("MsgFooterTD").style.display = "none";
	document.getElementById("MsgFooterTD").innerHTML = "<img class=ci_css_img src='/images/gallery/dot.gif' style='width: 1px; height: 1px;' alt=''>";
//}}}
}

function checkPrinterInstallProgress () {
//{{{
	var mytimeout = 3000; // give slower browsers have a chance to load the addon - making this too short short-circuits the addon load - especially in chrome
	if(ci_CheckInstall) {
		//if (!jQuery.browser.chrome) {
		ci_CheckInstall();
		//}
			// in chrome, further calle so ci_CheckInstall can break  ci_vUserCode
			//alert("JBB 1: "+window.ci_vUserCode+"; "+ci_vUserCode);
			//alert("JBB 2: "+window.ci_vUserCode+"; "+ci_vUserCode);
		//}	
		if (window.ci_vUserCode > 0) {
			ajaxRequest({'params':{'ajax_request':'coupon_page', 'device_id':window.ci_vUserCode, 'zip_code':GetCookie('zip'), 'facebook':facebook, 'cid':GetCookie('clipped_coupons_cookie')}, 'element_id':'pageContent', 'callback_function':resetCouponPageThenPrint, 'loading_text':'Loading Coupons...'})
		} else {
			//alert("JBB: "+window.ci_vUserCode+"; "+ci_vUserCode);
			//alert("JBB sup with chrome2: "+window.ci_vUserCode+"; "+ci_vUserCode);
			window.clearTimeout(window.timeoutHandler);
			window.timeoutHandler = window.setTimeout('checkPrinterInstallProgress();',mytimeout); 
		}
	} else {
		alert("Please reload your page - something is wrong");
	}
//}}}
}

function InstallPrinter(type)
{
//{{{
	if( typeof(ci_downloadFFSilent) == 'function')
	{
		window.clearTimeout(window.timeoutHandler);
		window.timeoutHandler = window.setTimeout('checkPrinterInstallProgress();',5000);
		ci_downloadFFSilent();
		//window.setTimeout('ci_CheckInstall();',3000);
	}
	else
	{
		alert("We currently do not support printer installs for your browser. We apologize for the inconvenience.\n\nIf you wish to proceed you could try using a different browser.")
	}
	var request_params = {'ajax_request':"hidden_printer_install_request"}
	ajaxRequest({"params":request_params});
//}}}
}

function initiatePrinter(in_data)
{
//{{{
	//{{{ Parse up the response
	var lines = in_data.split("\n")
	var data = new Object()
	for(var i=0; i<lines.length; i++)
	{
		var tmp = lines[i].split(":")
		
		if(tmp[1]=="")
		{
			continue
		}
		
		if(tmp[0]=="ineligible_coupons")
		{
			data[tmp[0]] = tmp[1].split("~")
		}
		else
		{
			data[tmp[0]] = tmp[1]
		}
	}
	//}}}
	
	var pid = $("#pid")[0].value
	var ineligible_msg = ""
	var print_msg = ""
	var messages = Array()
	var coupon_codes = Object()
	var successful_coupons = Array()
	var selected_coupons = getSelectedCoupons()
	var num_selected_coupons = selected_coupons.length
	var num_ineligible_coupons = (data['ineligible_coupons']) ? data['ineligible_coupons'].length : 0
	var print_success = false
	
	selected_coupons.each(function() {
		coupon_codes[$(this).attr('remote_coupon_code')] = $(this).attr('coupon_code');
	});
	if (data['ineligible_coupons']) {
		$.each(data['ineligible_coupons'],function(index,remote_coupon_code) {
			coupon_codes[remote_coupon_code] = 0;
		});
	}
	$.each(coupon_codes,function(remote_coupon_code,coupon_code) {
		if (coupon_code) {
			successful_coupons.push(coupon_code);
		}
	});

	//{{{ Print them up if we can
	if(data['print_token'] && pid && num_selected_coupons>num_ineligible_coupons)
	{
		//alert("got data to print")
		var printer_frame = $("#printer_iframe")[0];
		if(printer_frame)
		{
			messages.push("Thank you for printing!")
			printer_frame.src = printer_link+"?PID="+pid+"&PrintCartToken="+data['print_token']
			
			// Uncheck all the offers
			//var cbox = $("#select_all_checkbox_0")[0]
			//cbox.checked = false
			//SelectAllOffers(0,cbox)
			print_success = true
			//ShowBothMsgs("Printing...")
		}
		else
		{
			messages.push("There was an error printing your coupons. We apologize for the inconvenience.")
		}
	}
	//}}}
	
	//{{{ Check for ineligible coupons
	if(num_ineligible_coupons)
	{
		var num = (num_selected_coupons==num_ineligible_coupons) ? "Your" : num_ineligible_coupons
		messages.push("Sorry! "+num+" coupon(s) could not be printed")
	}
	//}}}
	
	//{{{ Set the message and, if need be, reload the coupon page
	window.printer_message = messages.join("<BR>")
	//displayPrinterMessage()
	if(print_success)
	{
		//$("#TDContent").append("<IMG src='http://offers.grocerycouponnetwork.com/ctrk.gif' style='height:0px; width:0px; border:0px;'>") 
		//$("#TDContent").append("<IMG src='http://test.grocerycouponnetwork.net/ctrk.gif' style='height:0px; width:0px; border:0px;'>")
		//ajaxRequest({'params':{'ajax_request':'coupon_page', 'zip_code':GetCookie('zip'), 'cid':GetCookie('clipped_coupons_cookie')}, 'element_id':'pageContent', 'callback_function':resetCouponPage, 'display_loading':false})
		// Create an ajax request for the print session
		ajaxRequest({'params':{'ajax_request':'record_print_session','facebook':facebook,'coupon_code':successful_coupons}, 'display_loading':false});
	}
	else
	{
		//displayPrinterMessage()
	}
	//ajaxRequest({'params':{'ajax_request':'coupon_page', 'zip_code':GetCookie('zip'), 'cid':''}, 'element_id':'pageContent', 'callback_function':resetCouponPage, 'display_loading':false})
	setTimeout("ajaxRequest({'params':{'ajax_request':'coupon_page', 'get_restricted_coupons':'1', 'facebook':facebook, 'zip_code':GetCookie('zip'), 'cid':''}, 'element_id':'pageContent', 'callback_function':resetCouponPage, 'display_loading':false});",4000);
	
	
	//}}}
	
//}}}
}

function preCheckCoupons()
{
//{{{
	var coupon_codes_box = $("#prechecked_coupon_codes")[0]
	
	if(coupon_codes_box)
	{
		var coupon_codes = coupon_codes_box.value.split("~")
		
		if(coupon_codes.length)
		{
			for(var i=0; i<coupon_codes.length; i++)
			{
				toggleCoupon(coupon_codes[i])
			}
		}
	}
	
	// It's a hack to put this here, but at the moment we'll want to do this every time
	var cookie_zip = GetCookie('zip')
	if(!cookie_zip && !facebook)
	{
		ShowBothMsgs("Don't forget to enter your zip code to see your local coupons!")
	}
//}}}
}

//<-- JBB
function getZipTargetingSearchtastic() {
//{{{
	var zip_box = $("#zip_target")[0]
	
	if(zip_box) {
		var zip_code = zip_box.value
		
		if(zip_code.length==5) {
			//window.location.reload(true);
 			var fullpath = location.pathname;
			var a = fullpath.split("/");
			var mypath = a[2];
			ajaxRequest({'params':{'ajax_request':'set_zip', "zip_code":zip_code}, 'element_id':'pageContent', 'calling_script':'searchtastic_coupon_list.php?value='+mypath});
			//alert('yo');
		}
	}
	
///}}}
	return false;
}

function getZipTargeting()
{
//{{{
	var zip_box = $("#zip_target")[0]
	
	if(zip_box)
	{
		var zip_code = zip_box.value
		
		if(zip_code.length==5)
		{
			//alert('"'+facebook+'"');
			ajaxRequest({'params':{'ajax_request':'coupon_page', "zip_code":zip_code, "facebook":facebook, "cid":GetCookie("clipped_coupons_cookie")}, 'element_id':'pageContent', 'callback_function':resetCouponPage, 'loading_text':'Loading Coupons...'})
		}
	}
	
///}}}
	return false;
}

function checkUserCode () {
	if (window.ci_vUserCode > 0) {
		//alert("JBB: "+window.ci_vUserCode+"; "+ci_vUserCode);
		//clearInterval(int);
		PrtCartHandling('PrintBtnA0');
	}

}

function resetCouponPageThenPrint(data) {
	//setNavigation('coupon_menu')
	resetCouponPage(data);
	//var int = setInterval('checkUserCode;',1000);
	if (window.ci_vUserCode > 0) {
		//alert("JBB: "+window.ci_vUserCode+"; "+ci_vUserCode);
		//clearInterval(int);
		PrtCartHandling('PrintBtnA0');
	}
	var request_params = {'ajax_request':"hidden_printer_install_return", 'device_id':window.ci_vUserCode}
	ajaxRequest({"params":request_params});
}

function resetCouponPage(data)
{
//{{{
	$("#PrintCart")[0].value=""
	GoToPage(1)
	preCheckCoupons()
	if(window.printer_message)
	{
		displayPrinterMessage()
	}
	document.getElementById("printCouponButton").href = "javascript:PrtCartHandling('PrintBtnA0');";
	//if (ci_CheckInstall) {
		//ci_CheckInstall();
		//alert("JBB: "+window.ci_vUserCode+"; "+ci_vUserCode);
	//}
//}}}
}

function reloadCouponPage()
{
	ci_CheckInstall();
	ajaxRequest({'params':{'ajax_request':'coupon_page', 'zip_code':GetCookie('zip'), 'facebook':facebook, 'cid':GetCookie('clipped_coupons_cookie')}, 'element_id':'pageContent', 'callback_function':resetCouponPage, 'loading_text':'Loading Coupons...'})
}

function displayPrinterMessage()
{
//{{{
	if(window.printer_message)
	{
		ShowBothMsgs(window.printer_message)
		setTimeout("HideBothMsgs()",10000)
		window.printer_message = ""
	}
//}}}
}

function print_r(x, max, sep, l) {
//{{{
 
	l = l || 0; 
	max = max || 10; 
	sep = sep || ' '; 
 
	if (l > max) { 
		return "[WARNING: Too much recursion]\n"; 
	} 
 
	var 
		i, 
		r = '', 
		t = typeof x, 
		tab = ''; 
 
	if (x === null) { 
		r += "(null)\n"; 
	} else if (t == 'object') { 
 
		l++; 
 
		for (i = 0; i < l; i++) { 
			tab += sep; 
		} 
 
		if (x && x.length) { 
			t = 'array'; 
		} 
 
		r += '(' + t + ") :\n"; 
 
		for (i in x) { 
			try { 
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1)); 
			} catch(e) { 
				return "[ERROR: " + e + "]\n"; 
				} 
		} 
 
	} else { 
 
		if (t == 'string') { 
			if (x == '') { 
				x = '(empty)'; 
			} 
		} 
 
		r += '(' + t + ') ' + x + "\n"; 
 
	} 

//}}}
	return r; 
}; 

function OpenFBWin(xPos, yPos, CID) {
//{{{
	var TAFDiv = document.getElementById('TAFDiv');
	if (!TAFDiv) {
		$('html').append('<div style="left: -2000px;" id="TAFDiv"></div>');
		TAFDiv = document.getElementById('TAFDiv');
	}
	var fbDivHeight = 103;
	var fbDivWidth = 487;
	var contentWidth = 550;
	// get the coupon object
	var obj = $('#coupon_table_'+CID)[0];
	if (obj != null) {
		TAFDiv.innerHTML = '<div id="fbPopup">' + FacebookLikeButton(CID) + '</div>'
		var scrollYPos = (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
		var scrollXPos = (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft);
		//if (ci_bSafari) scrollYPos = 0;
		var contentHeight = document.getElementById('ci_css_content').clientHeight;
		TAFDiv.style.width = fbDivWidth;
		TAFDiv.style.height = fbDivHeight;
		//var top = (contentHeight - fbDivHeight) / 2;
		//var left = (contentWidth - fbDivWidth) / 2;
		var top = yPos + scrollYPos;
		var left = xPos - fbDivWidth/2 - 8 + scrollXPos;
		TAFDiv.style.top = top + 'px';
		TAFDiv.style.left = left + 'px';
		document.getElementById('fbPopup').style.display = 'block';
		//TAFDiv.scrollIntoView(true);
	}
//}}}
} 

function OpenEmailWin(xPos, yPos, CID) {
//{{{
	var TAFDiv = document.getElementById('TAFDiv');
	if (!TAFDiv) {
		$('html').append('<div style="left: -2000px;" id="TAFDiv"></div>');
		TAFDiv = document.getElementById('TAFDiv');
	}
	var emailDivHeight = 286;
	var emailDivWidth = 330;
	var contentWidth = 550;
	// get the coupon object
	var obj = $('#coupon_table_'+CID)[0];
	if (obj != null) {
		TAFDiv.innerHTML = '<div id="emailPopup">' + EmailCouponToFriends(CID) + '</div>'
		//document.getElementById('Email_4').value = GetClientSessionCookieValue("CLIENTCOOKIETAF4", "Email");
		//document.getElementById('Name').value = GetClientSessionCookieValue("CLIENTCOOKIETAFNAME", "FirstName");
		var scrollYPos = (window.pageYOffset || document.body.scrollTop);
		//if (ci_bSafari) scrollYPos = 0;
		var contentHeight = document.getElementById('ci_css_content').clientHeight;
		TAFDiv.style.width = emailDivWidth;
		TAFDiv.style.height = emailDivHeight;
		var top = (contentHeight - emailDivHeight) / 2;
		var left = (contentWidth - emailDivWidth) / 2;
		TAFDiv.style.top = top + 'px';
		TAFDiv.style.left = left + 'px';
		document.getElementById('emailPopup').style.display = 'block';
		TAFDiv.scrollIntoView(true);
	}
//}}}
} 

function FacebookLikeButton(CID)
{
//{{{
	var imgURL = $('#ImageID'+CID).attr('src');
return ''
+'			<table class=c_css_table id="FBTbl" style="width: 450px;">'
+'				<tr class=ci_css_tr>'
+'					<td style="color:#0F94D2; font-size:11px; font-weight:bold">Click to like this coupon</td>'
+'					<td class=ci_css_td style="text-align:right; vertical-align:top;">'
+'						<a class=ci_css_a href="javascript:CloseEmailWin(0);" style="float:right; color:#999; font-size:11px; text-decoration:none; cursor:pointer">'
+'							Close <img class=ci_css_img alt="close window" style="width: 13px; height: 16px; cursor:pointer" src="/images/gallery/closeIconBig.gif">'
+'						</a>'
+'					</td>'
+'				</tr>'
+'				<tr class=ci_css_tr>'
+'					<td colspan=2 class=ci_css_td style="padding-top:5px">'
+'						<!--<div class="fb-like" data-send="false" data-width="450" data-show-faces="false"></div>-->'
+'						<!--<fb:like href="http://www.grocerycouponnetwork.com/coupons/?cid=' + CID + '" send="false" width="280" show_faces="false"></fb:like>-->'
+'						<iframe src="http://www.facebook.com/plugins/like.php?send=false&width=425&show_faces=false&href=http://'+document.location.hostname+document.location.pathname+'?gallery=clip%26cid='+CID+'" scrolling=no frameborder=0 style="border:none; width:425px; height:40px; margin:auto"></iframe>'
+'					</td>'
+'				 </tr>'
+'			</table>'
// end content
//}}}
}

function EmailCouponToFriends(CID)
{
//{{{
	var imgURL = $('#ImageID'+CID).attr('src');
	// Replace http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/progress_bar.gif
	// Replace http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/closeIconBig.gif
	// Replace http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/dotGrey.jpg
	// Replace http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/btn_TAFsend.gif 
return ' <div class=ci_css_div style="width: 294px;height:286; text-align: center; font-size: 12px; font-weight: bold; margin: 0px; margin-top: 100px; display: none;" id="EmailTblThankYou">Sending email...<br><br><img class=ci_css_img style="width:280px;height:15px;" src="http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/progress_bar.gif"></div>'
// content
+'			<table class=c_css_table id="EmailTbl" style="width: 304px;height: 170px;">'
+'				<tr class=ci_css_tr>'
+'					<td class=ci_css_td colspan="2" style="width: 304px;text-align:right;vertical-align: top;margin-right:5px;"><a class=ci_css_a href="javascript:CloseEmailWin(0);"><img class=ci_css_img alt="close window" style="width: 13px; height: 16px; float: right; cursor: hand; cursor: pointer;" src="http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/closeIconBig.gif"></a></td>'
+'				</tr>'
+'				<tr class=ci_css_tr>'
+'					<td class=ci_css_td>'
+'						<table class=ci_css_table style="width: 285px;">'
+'							<tr class=ci_css_tr>'
+'								<td class=ci_css_td style="text-align: center;vertical-align:middle;height:80px;"><img class=ci_css_img style="width: 80px; height: 80px;" src="' + imgURL + '"></td>'
+'								<td class=ci_css_td style="vertical-align:middle;padding-left:10px;height:80px;">'
+'									<div class=ci_css_div style="width:200px;overflow:hidden;font-weight: bold;color:#134B9E";font-size:small;">Spread the word, your friends will thank you!</div>'
+'									<div class=ci_css_div style="width:200px;overflow:hidden;color:#616161">Help up to 4 friends save money by telling them about this coupon.</div>'
+'								</td>'
+'							</tr>'
+'						</table>'
+'					</td>'
+'					<td></td>'
+'				</tr>'
+'				 <tr class=ci_css_tr>'
+'					 <td class=ci_css_td>'
+'						 <table class=ci_css_table style="width: 285px;padding-top:2px;">'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td colspan="2" style="width: 285px; height: 5px;"></td>'
+'							 </tr>'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td colspan="2" style="width: 285px; height: 1px;background: url(http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/dotGrey.jpg);"></td>'
+'							 </tr>'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td colspan="2" style="width: 285px; height: 5px;"></td>'
+'							 </tr>'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td style="padding-bottom: 8px; padding-right: 12px;">'
+'									 <div class=ci_css_div class="ci_css_inputFieldText" id="email1Label">Email (Friend 1) *</div>'
+'									 <input type="text" id="Email_0" class="ci_css_inputField" onkeydown="var e = arguments[0] || window.event; if(e.keyCode == 13) { SendEmailToFriend(' + CID + '); return false; }">'
+'								 </td>'
+'								 <td class=ci_css_td>'
+'									 <div class=ci_css_div class="ci_css_inputFieldText" id="email2Label">Email (Friend 2)</div>'
+'									 <input type="text" id="Email_1" class="ci_css_inputField" onkeydown="var e = arguments[0] || window.event; if(e.keyCode == 13) { SendEmailToFriend(' + CID + '); return false; }">'
+'								 </td>'
+'							 </tr>'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td style="padding-right: 12px;">'
+'									 <div class=ci_css_div class="ci_css_inputFieldText" id="email3Label">Email (Friend 3)</div>'
+'									 <input type="text" id="Email_2" class="ci_css_inputField" onkeydown="var e = arguments[0] || window.event; if(e.keyCode == 13) { SendEmailToFriend(' + CID + '); return false; }">'
+'								 </td>'
+'								 <td class=ci_css_td>'
+'									 <div class=ci_css_div class="ci_css_inputFieldText" id="email4Label">Email (Friend 4)</div>'
+'									 <input type="text" id="Email_3" class="ci_css_inputField" onkeydown="var e = arguments[0] || window.event; if(e.keyCode == 13) { SendEmailToFriend(' + CID + '); return false; }">'
+'								 </td>'
+'							 </tr>'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td colspan="2" style="width: 285px; height: 12px;background: url(http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/dotGrey.jpg);background-repeat:repeat-x;background-position : center;"></td>'
+'							 </tr>' 
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td style="padding-right: 12px;">'
+'									 <div class=ci_css_div class="ci_css_inputFieldText">Your Email *</div>'
+'									 <input type="text" id="Email_4" class="ci_css_inputField" value="" onkeydown="var e = arguments[0] || window.event; if(e.keyCode == 13) { SendEmailToFriend(' + CID + '); return false; }">'
+'								 </td>'
+'								 <td class=ci_css_td>'
+'									 <div class=ci_css_div class="ci_css_inputFieldText">Your Name *</div>'
+'									 <input type="text" id="Name" class="ci_css_inputField" value="" onkeydown="var e = arguments[0] || window.event; if(e.keyCode == 13) { SendEmailToFriend(' + CID + '); return false; }">'
+'								 </td>'
+'							 </tr>'
+'							 <tr class=ci_css_tr>'
+'								 <td class=ci_css_td colspan="2" style="width: 285px; height: 44px; text-align: center; vertical-align: top;padding-top:10px;">'
+'									 <img class=ci_css_img src="http://download3.coupons.com/7/19/7125/1450/print.coupons.com/CouponWeb/Themes/CI_Affiliates/_images/btn_TAFsend.gif" style="width:86px;height:24px;cursor: hand; cursor: pointer;" alt="send" onclick="SendEmailToFriend(' + CID + '); return false;">'
+'								 </td>'
+'							 </tr>'
+'						 </table>'
+'					 </td>'
+'					<td></td>'
+'				 </tr>'
+'			</table>'
// end content
//}}}
}

function CloseEmailWin(delay) {
//{{{
	if (delay > 0) {
		setTimeout("CloseEmailWin(0);", delay);
	} else {
		var TAFDiv = document.getElementById('TAFDiv');
		TAFDiv.style.left = "-2000px";
	}
//}}}
} 

