//###################################
// 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 showBigVote(){
	// Make sure the currentCid has been set, and that we're on a page that supports this feature
	if(!currentCid || !$('voting_box') || !$('comments_'+currentCid)){
		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($('item_'+currentCid));
	var div = $('voting_box');
	var style = div.style;
	style.left = '' + (box.left+box.width-280) + 'px';
	style.top = '' + box.top + 'px';
	style.height = '' + box.height + 'px';
	$('votearrow_div').style.width = (Math.round(box.height/5)-1) + 'px';
	style.display = '';
}

//###################################
// open up a centered pop-up window
//###################################
function PopAffiliateWin(coupon_id, store_id, coupon_code, tracking_code)
{
	// See if a tracking code was passed
	if (typeof tracking_code == 'undefined' ) tracking_code = 0;
	
	s.pageName="Offer Click Attempt";
	s.events="event15";;
	var s_code=s.t();if(s_code)document.write(s_code);
	
	if(coupon_id){
		// If we're on a page that supports it, we want to popup the Big Voting box
		currentCid = coupon_id;
		showBigVote();
		
		$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';

	var url = '/coupons/use_it/'+coupon_id+'/'+store_id+'/'+tracking_code;
	var obj_window = window.open(url, 'Affiliate', windowProperties);
	if(!obj_window){
		// popup didn't open,
		//alert('You are unable to use this coupon, because your browser has pop-ups disabled.  Please adjust your browser settings and retry.');
		// Just forward the user to the new url instead
		window.location = url;
		return;
	}
	// if possible, focus the window
	if (parseInt(navigator.appVersion) >= 4)
	{
		obj_window.window.focus();
	}
}

// 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(comment_id)
{
	// should we hide the "add comment" fields?
	if( comment_id.indexOf('post_') == -1 )
	{
		// if we're hiding the 

		if( $('post_'+comment_id).style.display == '' )
			$('post_'+comment_id).style.display = 'none';
	}

	$(comment_id).toggle();
	$(comment_id+'_add').toggle();
}

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){
	// Only do something if this code hasn't already been copied
	if($('codeheader'+client.couponId).childNodes[2].style.display!==''){
		if (Prototype.Browser.IE && (parseFloat(navigator.appVersion.split 
				("MSIE")[1]) >= 1.0)){
			$('codeheader'+client.couponId).childNodes[1].style.display='';			
		}
		else{
			$('codeheader'+client.couponId).childNodes[1].appear({duration:0.5});
		}
		$('codespan'+client.couponId).style.color="#B9B9B9";
	}
}
function hideCopyTip(client){
	if($('codeheader'+client.couponId).childNodes[2].style.display!==''){
		if (Prototype.Browser.IE && (parseFloat(navigator.appVersion.split 
				("MSIE")[1]) >= 1.0)){
			$('codeheader'+client.couponId).childNodes[1].style.display='none';			
		}
		else{
			$('codeheader'+client.couponId).childNodes[1].fade({duration:0.5});
		}
		$('codespan'+client.couponId).style.color="#737373";
	}
}

//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, text)
{
	// Clear any existing highlighted codes on the page
	var copied = $$('div.copyconfirmation');
	
	var i = 0;
	
	for (i = 0; i < copied.length; i++)
	{
		copied[i].style.display="none";
	}
	
	var codes = $$('strong.codespan');
	var i = 0;
	
	for (i = 0; i < codes.length; i++)
	{
		codes[i].style.color="#737373";
	}
	
	

	$('codeheader'+client.couponId).childNodes[2].style.display='';
	$('codeheader'+client.couponId).childNodes[1].style.display='none'; // Turn off the hover tip
	$('codespan'+client.couponId).style.color="#DCDCDC";
	
	PopAffiliateWin(client.couponId, 0, text);
}



function setupFlashCopy(){
	//if(!DetectFlashVer(9,0,0) || (navigator.userAgent.toLowerCase().indexOf("safari") != -1) ){
	if(!DetectFlashVer(9,0,0)){
		// 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
		return;
	}
	//var code_tips = $$('strong.tooltip', 'a.tooltip');  // a.tooltip is the UseIt button
	var code_tips = $$('strong.tooltip');
	var clips = new Array();

	var i = 0;
	
	for (i = 0; i < code_tips.length; i++)
	{
		var clip = new ZeroClipboard.Client();
		var cid=code_tips[i].id.replace('codespan','').replace('tip','').replace('_useit','')
		clip.couponId = cid;
		clip.glue(code_tips[i]);
		clip.setText($('codespan'+cid).innerHTML);
		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);
 	}

	window.onresize = function(){
		for (j = 0; j < clips.length; j++)
		{
			clips[j].reposition();
		}
	}
}

//################################
// Coupon Code Tooltips
//################################
function setupToolTips()
{
	//setupFlashCopy();
	// Set up the graphs
	jQuery('.inlinebar').sparkline('html', {type: 'bar', height:10, barColor: '#7fcd85', negBarColor: '#f58588', barSpacing: 1, barWidth: 2} );

	//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);
}

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

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