//###################################
// UTILITIES
//###################################

// phone number - strip out delimiters and check for 10 digits
function CheckPhoneNumber(strng)
{
	var error = "";

	if( strng == "" )
	{
		alert("Please enter your phone number.");
		return false;
	}

	var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters and whitespace
	if (isNaN(parseInt(stripped)))
		error = "The phone number contains illegal characters.";

	if (!(stripped.length == 10))
		error = "The phone number is the wrong length. Make sure you included an area code.";

	if( error != "" )
	{
		alert( error );
		return false;
	}
	else
		return true;
}

function CheckPassword(val)
{
    var error = "";
    if (val == "")
        error = "You didn't enter a password.\n";

    var strng = val.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters and whitespace
    //alert( strng );

    var illegalChars = /[\W_]+/; // check for non-alphanumeric chars
    var alphaChars = /[a-zA-Z]+/; // check for letters and numbers
    var numericChars = /[0-9]+/; // check for letters and numbers
    if (strng.length < 7)
    {
        error = "Your password must be at least 7 characters long.\n";
    }
    else if (!illegalChars.test(strng))
    {
        //error = "The password contains illegal characters.\n";
        error = "Your password must contain at least one non-alphanumeric character (!, @, _).\n";
    }
    else if (!alphaChars.test(strng))
    {
        //error = "The password contains illegal characters.\n";
        error = "Your password must contain at least one letter.\n";
    }
    else if (!numericChars.test(strng))
    {
        //error = "The password contains illegal characters.\n";
        error = "Your password must contain at least one number.\n";
    }
    /*
    else if (!((strng.search(/^[0-9a-zA-Z]+$/) > -1)))
        //&& (strng.search(/[A-Z]+/) > -1)
        //&& (strng.search(/[.!@#$*_-+]+/) > -1)
        //&& (strng.search(/[0-9]+/) > -1)))
    {
        error = "The password must be a combination of letters, numbers and characters.\n";
    }
    */
    
    if( error != "" )
    {
        alert( error );
        return false;
    }
    else
        return true;
}
  
function CheckEmail(e, t)
{	
	if (e == "")
	{	alert("Please fill in your "+ t +".");
		return false; 
	}
	else
	{
		var emailStr = e;
			
		var emailPat=/^(.+)@(.+)$/;
		var specialChars="\\(\\)<>@,;:\*\\\\\"\\.\\[\\]";
		var validChars="\[^\\s" + specialChars + "\]";
		var quotedUser="([^\"]*\")";
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
		var atom=validChars + '+';
		var word="(" + atom + "|" + specialChars + ")";
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
		
		var matchArray=emailStr.match(emailPat);
		if (matchArray==null)
		{	alert("Your "+ t +" seems incorrect. Please check @ and .'s!");
			return false;
		}
		
		var user=matchArray[1];
		var domain=matchArray[2];
		if (user.match(userPat)==null)
		{	alert("Please do not use any symbols (ie. quotes or asterisks) other than @ in your "+ t +".");
			return false;
		}
		
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null)
		{  for (var i=1;i<=4;i++)
			  {	if (IPArray[i]>255)
			  	{	alert("Destination IP address is invalid!");
					return false;
				}
			}
		}
		
		var domainArray=domain.match(domainPat)
		if (domainArray==null)
		{	alert("Your "+ t +" domain name doesn't seem to be valid.");
			return false;
		}			

		var atomPat=new RegExp(atom,"g");
		var domArr=domain.match(atomPat);
		var len=domArr.length;
		if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
		{	alert("Your "+ t +" must end in a three-letter domain, or two letter country.");
			return false;
		} 

		var Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		if (domArr[domArr.length-1].length == 2 || domArr[domArr.length-1].length == 3)
		{	for (var i = 0; i < domArr[domArr.length-1].length; i++)
			{	if (Chars.indexOf(domArr[domArr.length-1].charAt(i)) == -1)
				{	alert("The domain name can only contain letters.");
					return false;
				}
			}
		}
		
		if (len<2 || len>3)
		{   alert("Your "+ t +" is missing a hostname!");
		   return false;
		}
	}
	return true;
}

function CheckNums(n, t)
{	if (n == "")
	{	alert("Please enter a number in "+ t +".")
		return false;
	}
	else
	{	var Chars = "0123456789";
		for (var i = 0; i < n.length; i++)
		{	if (Chars.indexOf(n.charAt(i)) == -1)
			{	alert ("Please enter only numbers in "+ t +".")
				return false
			}
		}
	}
	
	return true;
}

function CheckName(n, t)
{	if (n == "")
	{	alert("Please enter your "+ t +".")
		return false;
	}
	else
	{	var Chars = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
		for (var i = 0; i < n.length; i++)
		{	if (Chars.indexOf(n.charAt(i)) == -1)
			{	alert ("Please enter a valid "+ t +".")
				return false
			}
		}
	}
	
	return true;
}

function CheckZip(z, t)
{
	if (z == "")
	{	alert("Please fill in your "+ t +".");
		return false; 
	}
	else
	{	// check to see that the value contains at least 5 numbers
		if (z.length < 5)
		{	alert ("Please enter at least 5 numbers into the "+ t +" field.");
			return false;
		}
		// check to see that the value contains either 5 or 10 numbers
		if (z.length > 5 && z.length < 10)
		{	alert ("Please enter either your 5-digit "+ t +" OR your 10-digit "+ t +" including the 4 digit extension (12345-1234) into the "+ t +" field.");
			return false;
		}
		// check to see that the value contains only numbers and possibly a hyphen
		var nums = "0123456789-";
		for (var i = 0; i < z.length; i++)
		{	if (nums.indexOf(z.charAt(i)) == -1)
			{	alert ("Please enter only numbers into the "+ t +" field.");
				return false;
			}
		}
		// check to see if the 6th character is a hyphen
		if (z.length == 10)
		{	if (z.charAt(5) != "-")
			{	alert("Please make sure that your "+ t +" is properly formatted. (12345-1234)");
				return false;
			}
		}
	}
	return true;
}

function CheckDate(val)
{
	// allow an empty field
	if( val.strip() == "" )
		return true;
		
	//Basic check for format validity
	var validformat = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
	var returnval = false;
	if (!validformat.test(val))
	{
		alert("Please select another expiration date.");
		return false;
	}
	else
	{
		var currDate = new Date();
		
		//Detailed check for valid date ranges
		var monthfield = val.split("/")[0];
		var dayfield = val.split("/")[1];
		var yearfield = val.split("/")[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		var today = new Date(currDate.getFullYear(), currDate.getMonth(), currDate.getDate());	

		if( dayobj < today )
		{				
			alert("Please select a date which is greater than or equal to today's date.");
			return false;
		}

		if ((dayobj.getMonth()+1 != monthfield)||(dayobj.getDate() != dayfield)||(dayobj.getFullYear() != yearfield))
		{
			alert("Please select another expiration date and submit again.");
			return false;
		}
		
		else
			returnval = true;
	}
	
	return returnval
}

//###################################
// toggle the visibility of a layer
//###################################
function ToggleLayer(layerID)
{
    layer = $(layerID);

    if( layer.style.display == 'none' || layer.style.display == '' )
        layer.style.display = 'block';
    else
        layer.style.display = 'none';
}

//###################################
// used to auto-tab through the phone number fields
//###################################
var phone_field_length=0;
function TabNext( obj, event, len, _next_field )
{
	var ret = false;
	var num = NumbersOnly(obj);
	next_field = $(_next_field);
	
	if (num)
	{
		if (event == "down")
			phone_field_length = obj.value.length;
		else if (event == "up")
		{
			if (obj.value.length != phone_field_length)
			{
				phone_field_length=obj.value.length;
				if (phone_field_length == len)
				{
					ret = true;
					next_field.focus();
				}
			}
		}
	}
	
	return ret;
}

//###################################
// used to restrict text field user input to alpha chars only
//###################################
function AlphaOnly(f)
{
    var re = /^[a-zA-Z]*$/;
    if (!re.test(f.value))
    {
        f.value = f.value.replace(/[^a-zA-Z]/g,"");
        return false;
    }
    
    return true;
}

//###################################
// used to restrict text field user input to numeric chars only
//###################################
function NumbersOnly(f)
{
    var re = /^[0-9]*$/;
    if (!re.test(f.value))
    {
        f.value = f.value.replace(/[^0-9]/g,"");
        return false;
    }
    
    return true;
} 

//###################################
// used to restrict text field user input to numeric chars only
//###################################
function CurrencyOnly(f)
{
    var re = /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/;
    if (!re.test(f.value))
        return false;
    
    return true;
} 


//################################
// USED TO COPY COUPON CODES TO THE USERS CLIPBOARD
//################################
function copyToClipboard(inElement)
{
	if (inElement.createTextRange) 
	{
		var range = inElement.createTextRange();
		if (range && BodyLoaded == 1 )
		range.execCommand('Copy');
	}
	
	else 
	{
		var flashcopier = 'flashcopier';
		
		if(!document.getElementById(flashcopier)) 
		{
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		
		document.getElementById(flashcopier).innerHTML = '';
		
		var divinfo = '<embed src="/swf/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}

function handleVoteOver(element, vote) {
	if (vote==1) {
		element.style.height = '24px';
		element.style.margin = '0 4px 0 5px';
		element.style.width = '28px';
		element.style.background = 'url("/images/coupon_sprites2.png") no-repeat -47px -302px';
	} else if (vote==0) {
		element.style.height = '24px';
		element.style.margin = '0 6px';
		element.style.width = '24px';
		element.style.background = 'url("/images/coupon_sprites2.png") no-repeat -77px -302px';
	}
}

function handleVoteOut(element, vote) {
	if (vote==1) {
		element.style.height = '18px';
		element.style.margin = '2px 8px';
		element.style.width = '21px';
		element.style.background = 'url("/images/coupon_sprites2.png") no-repeat 0 -302px';
	} else if (vote==0) {
		element.style.height = '18px';
		element.style.margin = '2px 9px';
		element.style.width = '18px';
		element.style.background = 'url("/images/coupon_sprites2.png") no-repeat -23px -302px';
	}
}

function recordVote(coupon_id, vote, source) {
	// remove previous vote boxes
	closeVote();
	
	if (coupon_id == '') {
		coupon_id = currentCid;
	}
	
	// Pass the vote to xajax validate function
	xajax_record_did_it_work(coupon_id,vote,'',3,source);
	
	currentCid = coupon_id;
	if(!currentCid || !$('store-coupon-yesvote')){
		return false;
	}
	
	// First we need to make sure the comments div is closed
	$('comments_'+currentCid).style.display="none";
	
	// find X/Y position of coupon div
	var box = ZeroClipboard.getDOMObjectPosition($('coupon_inner_'+currentCid));
	
	if(vote==1){
		var div = $('store-coupon-yesvote');
	} else {
		div = $('store-coupon-novote');
	}
	
	var style = div.style;
	style.left = box.left + 'px';
	style.top = box.top + 'px';
	style.height = box.height + 'px';
}

function closeVote(){
	$('store-coupon-yesvote').style.display = 'none';
	$('store-coupon-novote').style.display = 'none';
	$('voting_box').style.display = 'none';
	$('how-much-middle').style.display = '';
	$('share-savings').style.display = 'none';
	
	// Add the clipboard back in this case (not working...revisit)
	/*if (currentCid != '') {
		var clips = ZeroClipboard.clients;
		
		for (i in clips) {
			if (clips[i].couponId == currentCid) {
				clips[i].show();
				return;
			}
		}
	}*/
	return false;
}

function submitVoteFeedback(vote,reason){
	
	var form = $('dollars-saved');
	var input = form['dollars_saved'];
	var how_much = $F(input);
	// Validate the $ input
	var regex = /^\$?\d{1,3}(\.(\d{1,2}))?$/g;
	if (!how_much.match(regex) && vote=='1') {
		alert('Please enter a reasonable $ amount saved, up to $999');
		return false;
	}
	how_much = how_much.replace('$','');
	xajax_record_vote_reason(currentCid, reason, how_much);
		
	// Reset the $ saved
	$('dollars_saved_value').value = '0.00';
	
	if (vote == 0) {
		// Remove the coupon
		$('store-coupon-novote').style.display = 'none';
		Effect.BlindUp('coupon_'+currentCid);
	} else if (vote == 1) {
		$('share-email-big').href = $('share-email-big').href.replace('blank', currentCid);
		var box = ZeroClipboard.getDOMObjectPosition($('how-much-middle'));
		$('how-much-middle').style.display = 'none';
		var div = $('share-savings');
		var style = div.style;
		style.left = box.left + 'px';
		style.top = box.top + 'px';
		style.height = box.height + 'px';
		div.style.display='';
	}
	
	return false;
}

function showCouponPulsePreview(){
	var pulse_button = $j('#'+this.id);
	var popup = pulse_button.children('.pulse-popup');
	
	if (popup.length==0){
		// create the popup if doesn't exist
		pulse_button.addClass('pulse-button-hover');
		var position = pulse_button.offset();
		pulse_button.append('<div class="pulse-popup"></div>');
		popup = pulse_button.children('.pulse-popup');
		popup.css("left", position.left + pulse_button.width()/2 - popup.width()/ 2 + "px");
		popup.css("top", position.top + pulse_button.height() + 2 + "px");
		popup.fadeIn([0.2]);
	} else { //div exists 
		pulse_button.addClass('pulse-button-hover');
		// reposition
		position = pulse_button.offset();
		popup.css("left", position.left + pulse_button.width()/2 - popup.width()/ 2 + "px");
		popup.css("top", position.top + pulse_button.height() + 2 + "px");
		popup.fadeIn([0.1]);
	}
}

function hideCouponPulsePreview(){
	pulse_button = $j('#'+this.id);
	popup = pulse_button.children('.pulse-popup');
	// hide the popup
	pulse_button.removeClass('pulse-button-hover');
	popup.fadeOut([0.1]);
}

function toggleCouponPulse(){
	// set the current currentCid
	coupon_id = this.id.replace('pulse-button-', '');
	
	// remove any open voting box
	$j('#store-coupon-novote').hide();
	$j('#store-coupon-yesvote').hide();
	$j('#voting_box').hide();
	
	// is the coupon pulse div already open?
	var cp_div = $j('#cp-'+coupon_id);
	var cp_data = $j('#cp-data-'+coupon_id);
	var cp_button = $j('#pulse-button-'+coupon_id);
	var cp_button_inner = $j('#coupon-pulse-bt-'+coupon_id);
	if (cp_div.css('display') == 'none') {
		// take care of the button
		cp_button.unbind('mouseenter', showCouponPulsePreview);
		cp_button.unbind('mouseleave', hideCouponPulsePreview);
		cp_button.children('.pulse-popup').fadeOut([0.1]);
		cp_button.addClass('pulse-button-hover');

		// remove comments if opened
		if ($j('#comments_'+coupon_id).css('display') == 'block') {
			$j('#comments_'+coupon_id).slideUp();
			// change the text in the comment intro div
			$j('#close_comments_'+coupon_id).hide();
			$j('#comments_count_'+coupon_id).show();
		}
			
		// grab the coupon pulse div from xajax query
		if (cp_data.length == 0) {
			cp_div.children('.cp-loading').css('display', '');
			cp_div.slideDown();
			var p = {};
			p['coupon_id'] = coupon_id;
			p['method'] = 'ajax';
			cp_div.load('/coupons/get_pulse_data',p,function(){
				cp_data = $j('#cp-data-'+coupon_id);
				cp_data.find('.inlinebar2').sparkline('html', {type: 'bar', height: 40, barColor: '#8ddd82', negBarColor: '#fc7d7d', zeroColor: '999999', zeroAxis: true, barSpacing: 4, barWidth: 3} );
				cp_button_inner.addClass('pulse-button-used');
				cp_data.slideDown();
				});
		} else { // the div already exists, just display it
			cp_button_inner.addClass('pulse-button-used');
			cp_div.slideDown();
		}
		_gaq.push(['_trackEvent', 'Coupon Pulse', 'Pulse Opened', coupon_id.toString()]);
	} else { // close it
		cp_div.slideUp();
		// Bind up the display coupon pulse again
		cp_button.bind('mouseenter', showCouponPulsePreview);
		cp_button.bind('mouseleave', hideCouponPulsePreview);
		cp_button.removeClass('pulse-button-hover');
		cp_button_inner.removeClass('pulse-button-used');
		_gaq.push(['_trackEvent', 'Coupon Pulse', 'Pulse Closed', coupon_id.toString()]);
	}
}

function showBigVote(source){
	// Close this coupons pulse if it's open
	var coupon_id = currentCid;
	var cp_div = $j('#cp-'+coupon_id);
	if (cp_div) {
		if (cp_div.css('display') == 'block') {
			var cp_button = $j('#pulse-button-'+coupon_id);
			var cp_button_inner = $j('#coupon-pulse-bt-'+coupon_id);
			cp_div.hide();
			// Bind up the display coupon pulse again
			cp_button.bind('mouseenter', showCouponPulsePreview);
			cp_button.bind('mouseleave', hideCouponPulsePreview);
			cp_button.removeClass('pulse-button-hover');
			cp_button_inner.removeClass('pulse-button-used');
			_gaq.push(['_trackEvent', 'Coupon Pulse', 'Pulse Closed - Coupon Click', coupon_id.toString()]);
		}
	}
	
	// Make sure the currentCid has been set, and that we're on a page that supports this feature
	if(!currentCid || !$('voting_box')){
		return false;
	}
	
	// find X/Y position of coupon div
	// First we need to make sure the comments div is closed
	$('comments_'+currentCid).style.display="none";
	
	var box = ZeroClipboard.getDOMObjectPosition($('coupon_inner_'+currentCid));
	var div = $('voting_box');
	var style = div.style;
	style.display = 'none';
	
	var arrow_width = Math.round(box.height/5)-1;
	style.left = '' + (box.left+box.width-259-arrow_width) + 'px';
	style.top = '' + box.top + 'px';
	style.height = '' + box.height + 'px';
	$('votearrow_div').style.width = arrow_width + 'px';
	
	// display the correct message depending on the coupon used
	if($('coupon-code-'+currentCid) && source=='Coupon Code' && flashOK){
		$('copy-code-worked').style.display = '';
		$('coupon-auto-applied').style.display = 'none';
		$('discount-auto-applied').style.display = 'none';
		$('nocopy-code-worked').style.display = 'none';
	} else if ($('coupon-code-'+currentCid)) {
		$('copy-code-worked').style.display = 'none';
		$('coupon-auto-applied').style.display = 'none';
		$('discount-auto-applied').style.display = 'none';
		$('nocopy-code-worked').style.display = '';
	} else if ($('coupon-no-code-'+currentCid)) {
		$('copy-code-worked').style.display = 'none';
		$('coupon-auto-applied').style.display = '';
		$('discount-auto-applied').style.display = 'none';
		$('nocopy-code-worked').style.display = 'none';
	} else {
		$('copy-code-worked').style.display = 'none';
		$('coupon-auto-applied').style.display = 'none';
		$('discount-auto-applied').style.display = '';
		$('nocopy-code-worked').style.display = 'none';
	}
	
	// center the did it work text
	var extra_height = 28;
	$('did-it-work-section').style.marginTop = '' + (box.height - extra_height- 84) / 2 + 'px';
		
	div.appear();
}

//###################################
// open up a centered pop-up window
//###################################
function PopAffiliateWin(coupon_id, store_id, source, tracking_code, just_blank)
{
	// Close any previous Vote box
	if ($('store-coupon-yesvote')) {closeVote()};
	
	// Track the event with Google Analytics
	_gaq.push(['_trackEvent', 'Coupon Used', source, coupon_id.toString()]);
	
	// Uncover the codes
	if($('coupon-code-tooltip2-'+coupon_id)){
		var scissors = $$('.coupon-code-sc');
		for (var i=0; i<scissors.length; i++){
			scissors[i].style.display = 'none';
		}
		var codes = $$('.coupon-code-container');
		for (var i=0; i<codes.length;i++){

			var changeDiv = codes[i].childElements();
			changeDiv[0].addClassName('coupon-code-full');
		}
	}
	
	// See if a tracking code was passed
	if (typeof tracking_code == 'undefined' ) tracking_code = 0;
	
	// See whether to just open a blank window, or to actually forward the visitor
	if (typeof tracking_code == 'undefined' ) just_blank = false;
	
	if(coupon_id){
		// If we're on a page that supports it, we want to popup the Big Voting box
		currentCid = coupon_id;
		showBigVote(source);
		
		$store_id = 0;

		// set/update the cookie which will represent the users' "Coupon History"
		var cookie_val = getCookieValue('coupon_history');
		if (!cookie_val)
		{
			writePersistentCookie("coupon_history", coupon_id, "years", 5);
		}
		else
		{
			deleteCookie("coupon_history");
		
			var coupons = "";
			var _coupons = new Array();
		
			// we're only storing a history of 4 coupons, so remove the first one in the list if we've reached #5
			_coupons = cookie_val.split('_');
			if( _coupons.length > 3 )
			{
				_coupons.remove(0);

				_coupons.each(function(item){
					coupons = coupons+item+"_";
				});
			}
			else
				coupons = cookie_val+"_";
		
			writePersistentCookie("coupon_history", coupons+coupon_id, "years", 5);
		}
		
		//alert(coupon_id +", "+ getCookieValue('coupon_history'));
		//return;
	}
	else if(store_id){
		coupon_id = 0;
	}
	else return;
	
	// pop the affiliate site
	var windowWidth = 990;
	var windowHeight = 600;

	var _windowLeft = (screen.width - windowWidth) / 2;
	var _windowTop = (screen.height - windowHeight) / 2;
	var windowProperties = 'height=' + windowHeight + ',width=' + windowWidth + ',top=' + _windowTop + ',left=' + _windowLeft + ',scrollbars=1,resizable=1,menubar=1,toolbar=1,location=1,fullscreen=0';

	if(just_blank){
		// Just open a blank window with the correct size the link's href will set the destination, and maintain the referrer property
		var url = '/coupons/use_it/'+coupon_id+'/'+store_id+'/'+tracking_code;
		var obj_window = window.open('', 'Store', windowProperties);
		if(!obj_window){
			// popup didn't open,
			// Just forward the user to the new url instead
			if (coupon_id == 0) {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Forward Only - Store', coupon_id.toString()]);
			} else {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Forward Only - Coupon', coupon_id.toString()]);
			}
			window.location = url;
			return;
		} else {
			if (coupon_id == 0) {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Popup Successful - Store', coupon_id.toString()]);
			} else {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Popup Successful - Coupon', coupon_id.toString()]);
			}
		}
	} else {
		var url = '/coupons/use_it/'+coupon_id+'/'+store_id+'/'+tracking_code;
		var obj_window = window.open(url, 'Store', windowProperties);
		if(!obj_window){
			// popup didn't open,
			// Just forward the user to the new url instead
			if (coupon_id == 0) {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Forward Only - Store NR', coupon_id.toString()]);
			} else {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Forward Only - Coupon NR', coupon_id.toString()]);
			}
			window.location = url;
			return;
		} else {
			if (coupon_id == 0) {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Popup Successful - Store NR', coupon_id.toString()]);
			} else {
				_gaq.push(['_trackEvent', 'Coupon Debug', 'Popup Successful - Coupon NR', coupon_id.toString()]);
			}
		}
	}
	// if possible, focus the window
	if (parseInt(navigator.appVersion) >= 4)
	{
		try { obj_window.window.focus(); } catch(e) {};
	}
	
	// Make this coupon have simpler listeners.
	var home_coupons = $$('.home-coupon');
	// hoops for ie array handling errors
	if (home_coupons) {
		if (home_coupons.length == 0) {
			var remove_flag = true;
		} else {
			remove_flag = false;
		}
	} else {
		remove_flag = true;
	}

	if (remove_flag) {
		if (flashOK) {
			removeClipboardClient(coupon_id);
		} else {
			// add in a minimum version of mouseover if not on the hompage
			code = $('coupon-code-'+coupon_id);
			Event.stopObserving(code, 'mouseover', showCopyTipNF);
			Event.stopObserving(code, 'mouseout', hideCopyTipNF);
			Event.observe(code, 'mouseover', highlightCodeMin);
			Event.observe(code, 'mouseout', unHighlightCodeMin);
		}
	}

}

// method used by PopAffiliateWin to remove coupon_id's from the coupon history cookie
Array.prototype.remove = function(from, to)
{
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

// cookie methods used by "PopAffiliateWin"
function getCookieValue(cookieName)
{
	var exp = new RegExp (escape(cookieName) + "=([^;]+)");
	if (exp.test (document.cookie + ";"))
	{
		exp.exec (document.cookie + ";");
		return unescape(RegExp.$1);
	}
	else 
		return false;
}

function writePersistentCookie(CookieName, CookieValue, periodType, offset)
{
	var expireDate = new Date ();
	offset = offset / 1;

	var myPeriodType = periodType;
	switch (myPeriodType.toLowerCase())
	{
		case "years": 
			var year = expireDate.getYear();     
			// Note some browsers give only the years since 1900, and some since 0.
			if (year < 1000) year = year + 1900;     
			expireDate.setYear(year + offset);
			break;
		case "months":
			expireDate.setMonth(expireDate.getMonth() + offset);
			break;
		case "days":
			expireDate.setDate(expireDate.getDate() + offset);
			break;
		case "hours":
			expireDate.setHours(expireDate.getHours() + offset);
			break;
		case "minutes":
			expireDate.setMinutes(expireDate.getMinutes() + offset);
			break;
		default:
			alert ("Invalid periodType parameter for writePersistentCookie()");
			break;
	} 

	document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

function deleteCookie(cookieName)
{
	if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);
	return true;     
}

//################################
// IMAGE POP-UP
//################################

// Set the horizontal and vertical position for the popup
PositionX = (screen.width) ? (screen.width-150)/2 : 0;
PositionY = (screen.height) ? (screen.height-150)/2 : 0;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)
defaultWidth = 500;
defaultHeight = 500;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows
var autoClose = true;

// Do not edit below this line...
// ================================
if (parseInt(navigator.appVersion.charAt(0))>=4)
{
	var isNN=(navigator.appName=="Netscape")?1:0;
	var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;
}
var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;

function popImage(imageURL)
{
	var imgWin;

	if (isIE)
	{
        if( imageURL.indexOf(".zip") != -1 )
		    imgWin=window.open(imageURL,'',optIE);

		imgWin=window.open('about:blank','',optIE);
	}
	else
	{
        if( imageURL.indexOf(".zip") != -1 )
		    imgWin=window.open(imageURL,'',optNN);

		imgWin=window.open('about:blank','',optNN);
	}

    if( imageURL.indexOf(".zip") == -1 )
    {
	    with (imgWin.document)
	    {
		    writeln('<html><head><title>Burton QA</title><style>body{margin:0;}</style>');
		    writeln('<sc'+'ript>');
		    writeln('var isNN,isIE;');
		    writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
		    writeln('isNN=(navigator.appName=="Netscape")?1:0;');
		    writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
		    writeln('function resizeToimage(){');
		    writeln('if (isIE){');
		    writeln('window.resizeTo(100,100);');
		    writeln('width = 100-(document.body.clientWidth-document.images[0].width);');
		    writeln('height = 100-(document.body.clientHeight-document.images[0].height);');
		    writeln('window.resizeTo(width,height);}');
		    writeln('if (isNN){');
		    writeln('window.innerWidth = document.images["smf"].width;');
		    writeln('window.innerHeight = document.images["smf"].height;}');

		    writeln('}');
		    writeln('</sc'+'ript>');
		    if (!autoClose) writeln('</head><body bgcolor=FFFFFF scroll="no" onload="resizeToimage();self.focus()">')
		    else writeln('</head><body bgcolor=FFFFFF scroll="no" onload="resizeToimage();self.focus()" onblur="self.close()">');
		    writeln('<a href="javascript:self.close()"><img id="smf" name="smf" src="'+imageURL+'" style="display:block" border="0"/></a></body></html>');
		    close();
	    }
    }
} 

/*
//################################
// AFTER A USER CLICKS "Did it work", update the percentage based on the dots
//################################
function didItWork(coupon_id)
{
	var yes_votes = $$("#success_dots_"+coupon_id+" span.dot-green").length;
	var total_votes = $$("#success_dots_"+coupon_id+" span.dot-red").length + yes_votes;

	var percent = 0;
	if( yes_votes > 0 && total_votes > 0 )
		percent = Math.round((yes_votes/total_votes)*100);
	
	//alert( coupon_id +", "+ yes_votes +", "+ total_votes +", "+ percent +", "+ $('success_percent_'+coupon_id));
	
	$('success_percent_'+coupon_id).innerHTML = percent +"% successful";
}
*/

// Manage the display of coupon comments 
function displayComments(commentId, source)
{
	if (commentId == 'currentCid') {
		commentId = 'comments_'+currentCid;
	}
	
	// Remove the voting box if it's displayed on another coupon since it's absolutely positioned
	$('voting_box').style.display = 'none';
	
	// First Display or Remove the comments div
	var div = $(commentId);
	
	if(div.style.display == 'none'){
		Effect.BlindDown(div);
		_gaq.push(['_trackEvent', 'Coupon Comment', source, currentCid.toString()]);
	} else {
		Effect.BlindUp(div);
		_gaq.push(['_trackEvent', 'Coupon Comment', source, currentCid.toString()]);
	}
	
	// change the text in the comment intro div
	
	var introDiv = $('comments_count_'+div.id.replace('comments_',''));
	var closeDiv = $('close_comments_'+div.id.replace('comments_',''));
	if(introDiv.style.display == 'none'){
		closeDiv.style.display = 'none';
		introDiv.style.display = '';
	} else {
		introDiv.style.display = 'none';
		closeDiv.style.display = '';
	}

}

function displayAddComments(comment_id)
{
	$('post_'+comment_id).toggle();
}

// sanitize user input
function stripHTML(val)
{
	var regex = /<\S[^><]*>/g;
	var ret = val.replace(regex, "");
		
	return ret;
}

function showCopyTip(client){
	// Is the hidden coupon div tooltip active or have the user already clicked through?
	if($('coupon-code-tooltip2-'+client.couponId) && !$('coupon-code-'+client.couponId).className.match('coupon-code-full')){
		var div = $('coupon-code-tooltip2-'+client.couponId);
	} else {
		div = $('coupon-code-tooltip-'+client.couponId);
	}
	var box = ZeroClipboard.getDOMObjectPosition($('coupon-code-'+client.couponId));
	div.style.left = (box.left+box.width+10) + 'px';
	//Subtract off 1px for IE extra sprite width
	div.style.top = (box.top-1) + 'px';
	
	div.appear({duration:0.3});
	
	var code = $('coupon-code-'+client.couponId);
	code.style.background = '#dcdcdc';
	code.style.border = '2px dashed #aaaaaa';
}

function showCopyTipNF(){
	var cid = this.id.replace('coupon-code-', '');

	if($('coupon-code-tooltip2-'+cid) && !this.className.match('coupon-code-full')){
		var div = $('coupon-code-tooltip2-'+cid);
	} else {
		div = $('coupon-code-tooltip3-'+cid);
	}
	var box = ZeroClipboard.getDOMObjectPosition(this);
	div.style.left = (box.left+box.width+10) + 'px';
	//Subtract off 1px for IE extra sprite width
	div.style.top = (box.top-1) + 'px';
	
	div.appear({duration:0.3});
	
	this.style.background = '#dcdcdc';
	this.style.border = '2px dashed #aaaaaa';
}

function hideCopyTip(client){
	// Is the hidden coupon div tooltip active or have the user already clicked through?
	if($('coupon-code-tooltip2-'+client.couponId) && !$('coupon-code-'+client.couponId).className.match('coupon-code-full')){
		$('coupon-code-tooltip2-'+client.couponId).fade({duration:0.3});
	} else {
		$('coupon-code-tooltip-'+client.couponId).fade({duration:0.3});
	}

	var code = $('coupon-code-'+client.couponId);
	code.style.background = '#eaeaea';
	code.style.border = '2px dashed #bebebe';
}

function hideCopyTipNF(){

	cid = this.id.replace('coupon-code-', '');

	if($('coupon-code-tooltip2-'+cid) && !this.className.match('coupon-code-full')){
		$('coupon-code-tooltip2-'+cid).fade({duration:0.3});
	} else {
		$('coupon-code-tooltip3-'+cid).fade({duration:0.3});
	}
	
	this.style.background = '#eaeaea';
	this.style.border = '2px dashed #bebebe';
}

function highlightCodeMin(e) {
	var code = e.target;
	code.style.border = '2px dashed #aaaaaa';
	code.style.background = '#dcdcdc';
	code.style.color = '#666';
}

function unHighlightCodeMin(e) {
	var code = e.target;
	code.style.border = '2px dashed #bebebe';
	code.style.background = '#eaeaea';
	code.style.color = '#666';
}
//Flash Player Version Detection - Rev 1.6
//Detect Client Browser type
//Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

//JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
			//alert("flashVer="+flashVer);
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

//When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

     	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
if (src.indexOf('?') != -1)
 return src.replace(/\?/, ext+'?'); 
else
 return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
 var str = '';
 if (isIE && isWin && !isOpera)
 {
		str += '<object ';
		for (var i in objAttrs)
			str += i + '="' + objAttrs[i] + '" ';
		for (var i in params)
			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
		str += '></object>';
 } else {
		str += '<embed ';
		for (var i in embedAttrs)
			str += i + '="' + embedAttrs[i] + '" ';
		str += '> </embed>';
 }

 document.write(str);
}

function AC_FL_RunContent(){
var ret = 
 AC_GetArgs
 (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
  , "application/x-shockwave-flash"
 );
AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i=0; i < args.length; i=i+2){
 var currArg = args[i].toLowerCase();    

 switch (currArg){	
   case "classid":
     break;
   case "pluginspage":
     ret.embedAttrs[args[i]] = args[i+1];
     break;
   case "src":
   case "movie":	
     args[i+1] = AC_AddExtension(args[i+1], ext);
     ret.embedAttrs["src"] = args[i+1];
     ret.params[srcParamName] = args[i+1];
     break;
   case "onafterupdate":
   case "onbeforeupdate":
   case "onblur":
   case "oncellchange":
   case "onclick":
   case "ondblClick":
   case "ondrag":
   case "ondragend":
   case "ondragenter":
   case "ondragleave":
   case "ondragover":
   case "ondrop":
   case "onfinish":
   case "onfocus":
   case "onhelp":
   case "onmousedown":
   case "onmouseup":
   case "onmouseover":
   case "onmousemove":
   case "onmouseout":
   case "onkeypress":
   case "onkeydown":
   case "onkeyup":
   case "onload":
   case "onlosecapture":
   case "onpropertychange":
   case "onreadystatechange":
   case "onrowsdelete":
   case "onrowenter":
   case "onrowexit":
   case "onrowsinserted":
   case "onstart":
   case "onscroll":
   case "onbeforeeditfocus":
   case "onactivate":
   case "onbeforedeactivate":
   case "ondeactivate":
   case "type":
   case "codebase":
     ret.objAttrs[args[i]] = args[i+1];
     break;
   case "id":
   case "width":
   case "height":
   case "align":
   case "vspace": 
   case "hspace":
   case "class":
   case "title":
   case "accesskey":
   case "name":
   case "tabindex":
     ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
     break;
   default:
     ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
 }
}
ret.objAttrs["classid"] = classid;
if (mimeType) ret.embedAttrs["type"] = mimeType;
return ret;
}

function copyCode(client)
{
	// remove the clipboard object from this coupon
	hideCopyTip(client);

	// remove the forced styling (use child's b/c of IE JS/Flash compatibilty bug)
	var codes = $('cc-container-'+client.couponId).childElements();

	codes[0].style.background = '';
	codes[0].style.border = '2px dashed #bebebe';
	
	PopAffiliateWin(client.couponId, 0, 'Coupon Code', 0, false);
}

function useCodeNF(){
	cid = this.id.replace('coupon-code-', '');
	
	// hide the copytip before removing the event listeners
	if($('coupon-code-tooltip2-'+cid) && !this.className.match('coupon-code-full')){
		$('coupon-code-tooltip2-'+cid).fade({duration:0.3});
	} else {
		$('coupon-code-tooltip3-'+cid).fade({duration:0.3});
	}
	this.style.background = '#eaeaea';
	this.style.border = '2px dashed #bebebe';
	
	PopAffiliateWin(cid, 0, 'Coupon Code', 0, true);
}

function setupFlashCopy(){

	flashOK = DetectFlashVer(9,0,0);
	if(!flashOK){
		// If they don't have flash version 9 or 10, don't do anything
		// Also safari doesn't handle popups from the flash vid, so don't do this for safari
		var code_tips = $$('.coupon-code');
		for (var i=0;i<code_tips.length;i++) {
			Event.observe(code_tips[i], 'mouseover', showCopyTipNF);
			Event.observe(code_tips[i], 'mouseout', hideCopyTipNF);
			// remove the inline onclick event now that the js is loaded
			code_tips[i].onclick = '';
			Event.observe(code_tips[i], 'click', useCodeNF);
		}
		return;
	}

	code_tips = $$('.coupon-code');
	var codeText = '';
	var clips = new Array();
	i = 0;
	
	for (i = 0; i < code_tips.length; i++)
	{
		// remove the previous event in the html
		code_tips[i].onclick = '';
		
		// set up the clip
		var clip = new ZeroClipboard.Client();
		var cid = code_tips[i].id.replace('coupon-code-','');
		clip.couponId = cid;
		// FireFox does not support innerText
		if($('coupon-code-'+cid).innerText != undefined) {
			var codeText = $('coupon-code-'+cid).innerText.replace(/\s/gi,'');
		} else {
			codeText = $('coupon-code-'+cid).textContent;
			codeText = codeText.replace(/\s/gi,'');
		}
		clip.setText(codeText);
		
		clip.glue('coupon-code-'+cid,'cc-container-'+cid);
		
		clip.addEventListener( 'onMouseOver', showCopyTip );
		clip.addEventListener( 'onMouseOut', hideCopyTip );
		 
		//Add a complete event to let the user know the text was copied
        clip.addEventListener('onComplete', copyCode);
        
        clips.push(clip);
 	}
}

function removeClipboardClient(cid){
	if (!cid) {
		if (!currentCid) {
			return false;
		} else { 
			cid = currentCid;
		}
	}
	
	var clips = ZeroClipboard.clients;
	
	for (var i in clips) {
		if (clips.hasOwnProperty(i)) {
			var clip = clips[i];
			
			if (clip.couponId == cid) {
				// Remove the clipboard client, already been used for this coupon and it messes with feedback
				try { clip.destroy() } catch(e) {};
				
				// Add back in regular event listeners to these post client divs
				var code = $('coupon-code-'+cid);
				code.onclick = '';
				Event.observe(code, 'mouseover', highlightCodeMin);
				Event.observe(code, 'mouseout', unHighlightCodeMin);
				Event.observe(code, 'click', useCodeNF);			
				return false;
			}
		}
	}

}
//################################
// Coupon Code Tooltips
//################################
function setupToolTips()
{
	//var startTime = new Date().getTime();
	setupFlashCopy();
	//var endTime = new Date().getTime();
	//alert('Flash copy setup took '+((endTime-startTime)/1000)+' seconds.');
	// Set up the graphs
	$j('.inlinebar').sparkline('html',{type: 'bar', height:14, barColor: '#8ddd82', negBarColor: '#fc7d7d', zeroColor: '999999', zeroAxis: true, barSpacing: 2, barWidth: 1} );
	$j('.inlinebar2').sparkline('html', {type: 'bar', height: 40, barColor: '#8ddd82', negBarColor: '#fc7d7d', zeroColor: '999999', zeroAxis: true, barSpacing: 4, barWidth: 3} );
	//return false;
	//var currentDate = new Date();
	//var start=currentDate.getTime();
	
	//var code_tips = $$('strong.tooltip', 'a.tooltip');
	//var activate_tips = $$('a.activate', 'a.tooltip_activate');
	//var facebook_tips = $$('a.fb_tooltip');
	//var friend_tips = $$('a.friend_tooltip');
	var user_tips = $$('a.user_tooltip','a.contributor_tooltip');
	var help_tips = $$('a.help_tooltip');
	var unverified_tips = $$('a.unverified_tooltip');
	
	var i = 0;
	
	/*for (i = 0; i < code_tips.length; i++)
	{
		new Tip(code_tips[i], '<div class="tip-content copy-tip"><p>click to copy this code and visit the store.</p></div>', {delay: 0, offset:{x:5, y:-75}});
	}
	/*
	for (i = 0; i < activate_tips.length; i++)
	{
		new Tip(activate_tips[i], '<div class="tip-content copy-tip"><p>click to go to the store and use this coupon.</p></div>', {delay: 0, offset:{x:5, y:-75}});
	}
	
	for (i = 0; i < facebook_tips.length; i++)
	{
		new Tip(facebook_tips[i], '<div class="tip-content"><p class="first">send to your</p><p>Facebook Friends</p></div>', {effect: "appear", hook: { target: "topRight", tip: "bottomLeft"}});
	}

	for (i = 0; i < friend_tips.length; i++)
	{
		new Tip(friend_tips[i], '<div class="tip-content-sendtofriend"><p>Email to your friends</p></div>', {effect: "appear", hook: { target: "topRight", tip: "bottomLeft"}});
	}
	*/
	for (i = 0; i < user_tips.length; i++)
	{
		new Tip(user_tips[i], $(user_tips[i].id+'_content').innerHTML, {effect: false, hook: { target: "topRight", tip: "bottomLeft"}});
	}
	
	// p2s tip
	/*
	$$('.p2s').each(function(e){
			new Tip(e, '<div class="tip-content-dispute"><div class="tip-content"><p>Store is enrolled in pays-2-share program.</p></div></div>', {
				effect: "appear",
				hook: { target: "bottomRight", tip: "topLeft"}
		});
	});*/
	
	// Myprofile tips
	for (i = 0; i < help_tips.length; i++)
	{
		new Tip(help_tips[i], '<div class="tip-content-help"><div class="tip-content"><p>click for help</p></div></div>', {effect: false, hook: { target: "bottomLeft", tip: "topRight"}});
	}

	for (i = 0; i < unverified_tips.length; i++)
	{
		new Tip(unverified_tips[i], '<div class="tip-content-help"><div class="tip-content"><p>you must verify your store<BR>before you can access this area.</p></div></div>', {effect: false, hook: { target: "topMiddle", tip: "bottomMiddle"}});
	}
	
	if($('norequestcash')){
		new Tip('norequestcash', '<div class="tip-content-help"><div class="tip-content"><p>Minimum payment threshold of $25<BR>is required before payment can be requested.</p></div></div>', {
			effect: "appear",
			hook: { target: "bottomRight", tip: "topLeft"}
		});
	}
	if($('last_payment_processed')){
		var el=$('last_payment_processed');
		new Tip('last_payment_processed', '<div class="tip-content-lastpayment"><div class="tip-content"><p>date of last payment:</p><p class="short">'+el.readAttribute('date_processed')+'</p><p>last payment processed:</p><p class="short">$'+el.readAttribute('amount_processed')+'</p><p>method of payment:</p><p class="short">'+el.readAttribute('method_processed')+'</p></div></div>', {
			effect:false,
			hook: { target: "topRight", tip: "bottomLeft"}
		});
	}

	if($('payment_status')){
		new Tip('payment_status', '<div class="tip-content-payment-status"><div class="tip-content"><p>payment being processed by '+$('payment_status').readAttribute('payment_method')+'</p></div></div>', {
			effect: false,
			hook: { target: "bottomRight", tip: "topLeft"}
		});
	}
	
	if($('dispute')){
		new Tip('dispute', '<div class="tip-content-dispute"><div class="tip-content"><p>click to dispute a transaction</p></div></div>', {
		effect: false,
		hook: { target: "bottomLeft", tip: "topRight"}
		});
	}
	
	$$('.top-coupon').each(function(el){
		//alert( el.id +", "+ el.innerHTML +", "+ el.readAttribute('coupon_code') );
		new Tip(el.id, '<div class="tip-content-pays2share-coupon"><div class="tip-store"><div class="tip-store-name">'+ el.innerHTML +'</div></div><div class="tip-content"><p>coupon code:</p><p class="code">'+ el.readAttribute('coupon_code') +'</p><p># of uses:</p><p class="num">'+ el.readAttribute('num_uses') +'</p><p>earnings:</p><p class="num">$'+ el.readAttribute('earnings') +'</p></div></div>', {
			effect: false,
			hook: { target: "topRight", tip: "bottomLeft"}
		});
	});


	//currentDate = new Date();
	//alert(currentDate.getTime()-start);
}

function handleVoteHighlight(coupon_id){
	var vote_box_id = 'coupon_vote_'+coupon_id;
	$(vote_box_id).hide();
	Effect.Grow(vote_box_id);
	return false;
}

//################################
// Attach the JS Event Handlers for the Main Comment Div
//################################
function attachCommentHandlers(){
	
	var commentDivs = $$('.coupon-comments');
	
	for (i = 0; i < commentDivs.length; i++)
	{
		commentDivs[i].id.addEventListener('onclick', displayComments(this));
 	}
}

function addPulseListeners(){
	
}

function changeExclusiveHeight()
{
	var exclusive = $$('.exclusive-coupon');
	for (i=0; i<exclusive.length; i++) {
		var height = exclusive[i].parentNode.clientHeight;
		exclusive[i].style.height = height+'px';
	}
}

//Attach event handlers here
document.observe('dom:loaded',function(){
	//attachCommentHandlers();
	changeExclusiveHeight();
	// Coupon Pulse
	var cp_button = $j('.coupon-pulse-bt-container');
	cp_button.bind('mouseenter', showCouponPulsePreview);
	cp_button.bind('mouseleave', hideCouponPulsePreview);
	cp_button.bind('click', toggleCouponPulse);
});

document.observe('dom:loaded', setupToolTips);

var currentCid = 0; // Coupon id, of latest coupon which has been clicked
var flashOK = false;



