function switchStyle(showHideDiv, displaystyle) {
	var ele = document.getElementById(showHideDiv);
    ele.style.display = displaystyle;
}

function tbShareClicked(elm) {
document.getElementById(elm.get_id() + '_pnlShare2').className='coupShowShare';}

var friendArray = new Array();
function createNewEmailRow(dvId, textboxClassName) {
    if (!textboxClassName) {
        textboxClassName = 'add-friend-textbox';
    }
  if(friendArray[dvId] == null)
  {
     friendArray[dvId] = 0;
  }
  
  // only allow 4 additional friends for emailing coupon
  if(friendArray[dvId]<4)
  {
    friendArray[dvId]++;
    var d = document.getElementById(dvId);
    var _nwTxt = document.createElement('input');
    var _nwBr = document.createElement('br');
    var _nwMsg = document.createElement('span');
    _nwTxt.type = 'text';
    _nwTxt.className = textboxClassName;
    _nwTxt.id = _nwTxt.name = 'friendEmail' + friendArray[dvId];
    _nwMsg.id = _nwMsg.name = 'friendMsg' + friendArray[dvId];
    _nwMsg.innerHTML = '&nbsp;*'
    _nwMsg.className='coupon-email-frnd';    
    d.appendChild(_nwBr); 
    d.appendChild(_nwTxt);
    d.appendChild(_nwMsg);
  }else
  {
    var lnkId = dvId.replace('dvFriendEmail','lnkNewFriend');
    document.getElementById(lnkId).innerHTML = 'All Friends Added';
  }
}

function showEmailFrame(elemid){
  document.getElementById(elemid).style.display = "inline";
}

function validEmail(email){      
	var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailReg.test(email); 
}

function showhide(copy_id, state){
  var tool = document.getElementById(copy_id);
  if(tool != null)
  {
  tool.style.visibility = state;
  }else{alert(copy_id + " not found");}
  return false;}

var divstate = "off";
var lastToolShown = null;
var lastButtonShown = null;
function showVoteOption(tooltipDiv){
  var tool = document.getElementById(tooltipDiv);
  var btnOp = document.getElementById(tooltipDiv.replace('dvToolTip', 'imgVoteDown'));
  var currentState = tool.style.visibility;     
             
  if(lastToolShown != null && lastToolShown != tool){
     lastToolShown.style.visibility = "hidden";
     lastButtonShown.src = "//i.bfrl.us/cancel.gif";
  }
  
  if(currentState == "" || currentState == "hidden"){
     tool.style.visibility = "visible";
     btnOp.src = "//i.bfrl.us/cancel-on.gif";
  }
  else if(currentState == "visible"){
     tool.style.visibility = "hidden";
     btnOp.src = "//i.bfrl.us/cancel.gif";
  }
 
  lastToolShown = tool;
  lastButtonShown = btnOp;  
  return true;
}

function InvalidAddFriend(lstControl){
   var cntrArr = lstControl.split(';');
   var elm;
   for(i=0;i<4;i++)
   {
     elm = document.getElementById('friendMsg'+i);
     if(elm !=null)
     {
       if(lstControl.indexOf('friendEmail'+i) == -1)
       {
         elm.className = 'coupon-email-frnd';
       }else{
         elm.className = 'coupon-email-frnd-invalid';
       }
     }
   }
}

function EmailSuccessfullySent(){
   Recaptcha.reload();
   //alert('Your email was successfully sent.');
   try{
   hideCouponDetail();}catch(e){}
}

function EmailFailSent(msg){
   Recaptcha.reload();
   alert(msg);
   try{
   hideCouponDetail();}catch(e){}
}

var clip = null;
var clip2 = null;
var couponTextId = null;
var bf_coupon_title_link = null;
var lastPopupShown = null;
function init() {
    try{
    document.body.addEventListener('DOMMouseScroll', body_scrolled_hndl, false);
    }catch(err){}

	// setup single ZeroClipboard object for all our elements
	ZeroClipboard.setMoviePath('/Style/ZeroClipboard.swf');
	clip = new ZeroClipboard.Client();
	clip.setHandCursor( true );			
    clip.addEventListener('complete', coupon_click );
    
	clip2 = new ZeroClipboard.Client();
	clip2.setHandCursor( true );			
    clip2.addEventListener('complete', coupon_click );       
    
	// assign a common mouseover function for all elements using jQuery
	$('div.coupon-code-wrap').mouseover( function() {
		// set the clip text to our innerHTML		
		couponTextId = document.getElementById(this.id.replace("dvCouponCode", "dvCouponId")).innerHTML;
		var cdElem = document.getElementById(this.id.replace("dvCouponCode", "dvCode"));	
		
		if(cdElem == null) return;
		clip.setText( cdElem.innerHTML );

		bf_coupon_title_link = this.id.replace("dvCouponCode", "couponTitle");

		// reposition the movie over our element
		// or create it if this is the first time
		if (clip.div) {
			clip.receiveEvent('mouseout', null);
			clip.reposition(this);
		}
		else clip.glue(this);
		
		// gotta force these events due to the Flash movie
		// moving all around.  This insures the CSS effects
		// are properly updated.
		clip.receiveEvent('mouseover', null);
	} );

	$('div.coupon-related-copy').mouseover(function () {
	    // set the clip text to our innerHTML	    
	    couponTextId = document.getElementById(this.id.replace("dvCouponCode", "dvCouponId")).innerHTML;
	    var cdElem = document.getElementById(this.id.replace("dvCouponCode", "dvCode"));
	    clip2.setText(cdElem.innerHTML);

	    bf_coupon_title_link = this.id.replace("dvCouponCode", "couponTitle");

	    // reposition the movie over our element
	    // or create it if this is the first time
	    if (clip2.div) {
	        clip2.receiveEvent('mouseout', null);
	        clip2.reposition(this);
	    }
	    else clip2.glue(this);

	    // gotta force these events due to the Flash movie
	    // moving all around.  This insures the CSS effects
	    // are properly updated.
	    clip2.receiveEvent('mouseover', null);
	});}

function coupon_click(){
    // flash assume yes
    var bf_lnk = $get(bf_coupon_title_link);
    googleTrackOut(couponTextId, 'yes');
    eval(bf_lnk.getAttribute('onclick').replace('return ', '').replace('this', 'bf_lnk'));
}

function pageloadingtime(){
    // loads all flash objects
    init();

    //calculate the current time in afterload 
    afterload = (new Date()).getTime();
    // now use the beforeload and afterload to calculate the seconds
    secondes = (afterload-beforeload)/1000;
    // If necessary update in window.status
    window.status='Page loaded in ' + secondes + ' seconds.';
    // Place the seconds in the innerHTML to show the results
    document.getElementById("loadingtime").innerHTML = "<font color='white'>Page loaded in  " + secondes + " seconds.</font>";
       
    //popDD();
    flashload = (new Date()).getTime();
    flSeconds = (flashload-afterload)/1000;
    document.getElementById("loadingtime").innerHTML += "<br/><font color='white'>Flash and cb  " + flSeconds + " seconds.</font>";
}

function offerClick(lnk,id, isP){
    googleTrackOut(id, isP);
    window.open(lnk.href, '_blank');
    return false;
}

function cbOfferClick(lnk, id, isP, dest) {
    var rnd = randomString();
    googleTrackOut(id, isP);
    document.location = lnk.href + '&rndLookup=' + rnd;
    window.open(dest + '&rndLookup=' + rnd, '_blank', 'directories=yes,height=510,width=640,location=yes,menubar=no,toolbar=no,scrollbars=yes');
    return false;
}

function cbpopOpenLnkClose(lnk) {
    window.open(lnk.href);
    window.close();
}

var myToday = new Date();
var curr_date = myToday.getDate();
var curr_month = myToday.getMonth() + 1;
var curr_year = myToday.getFullYear();
var myTodayFormatted = curr_month + "-" + curr_date + "-" + curr_year;
var myTomorrow = new Date();
myTomorrow.setDate(myTomorrow.getDate()+1);
var next_date = myTomorrow.getDate();
var next_month = myTomorrow.getMonth() + 1;
var next_year = myTomorrow.getFullYear();
var myTomorrowFormatted = next_month + "-" + next_date + "-" + next_year;
function CheckExp(passedDate){
if (myTodayFormatted == passedDate) document.write("<span style='color: #DF4C03;'>&nbsp;Today!</span>");
else if (myTomorrowFormatted == passedDate) document.write("<span style='color: #DF4C03;'>&nbsp;Tomorrow!</span>");
else document.write(passedDate);}

function body_scrolled_hndl() { // firefox issue, mouseover code and scroll
  if(clip != null){clip.hide();}
  if(clip2 != null){clip2.hide();}
}

function userSelectedMerchDD(dd){document.location = '/coupons/store/'+dd.value;}

function MoveRecaptchaTable(elemId){
    $get(elemId).appendChild($get('recaptcha_table'));
}
function userVoted(sw,wrp,elT,elB){ try{
  $get(sw+wrp).style.display='inline';
  $get(sw+elT).innerHTML = 'Thanks for your vote!';
  $get(sw+elB).style.display='none';}catch(e){}return true;}
  
function AdvancedItemDisplay(behaviour,args) {
    var template=behaviour.get_element().getAttribute('_template');
    for (var i=0; i<behaviour._completionListElement.childNodes.length; i++) {
        var item=behaviour._completionListElement.childNodes[i];
        //var vals = item._value;
        var vals = Sys.Serialization.JavaScriptSerializer.deserialize(behaviour._completionListElement.childNodes[i]._value);
        var html=template;
        for (var c = 0; c < vals.length; c++)
            html = html.replace(new RegExp('##' + c + '##', 'g'), vals[c].replace(/\$/g, "$$$$"));
        item.innerHTML=html;
    }
}
function AdvancedSetText(behaviour,args) {
    var attrib = null;
    if (args._value == null)
    {
        var item = args._item;
        while(item && !item.getAttribute("TACSearchValue"))
        {
            item = item.parentNode;
        }
        attrib = item.getAttribute("TACSearchValue");
    } else
    {
        var vals = Sys.Serialization.JavaScriptSerializer.deserialize(args._value);
        attrib = vals[0];
    }
    var element=behaviour.get_element();
    var control = element.control;
    if (control && control.set_text)
        control.set_text(attrib);
    else
        element.value = attrib;}
        
 function bf_AutoRedirectAutoItemSelected(behaviour, args){
    var attrib = null;
    if (args._value == null)
    {
        var item = args._item;
        while(item && !item.getAttribute("TACAutoValue"))
        {
            item = item.parentNode;
        }
        attrib = item.getAttribute("TACAutoValue");
    } else
    {
        var vals = Sys.Serialization.JavaScriptSerializer.deserialize(args._value);
        attrib = vals[1];
    }
    var element=behaviour.get_element();
    var control = element.control;
    if (control && control.set_text)
        control.set_text(attrib);
    else
        element.value = attrib;
    window.location = '/coupons/store/' + attrib;
}

function bf_lgnGetUrl(elm) {
    $get(elm).value = document.location.pathname + document.location.search;
    return true;
}
function cb_CloseReload() {
    document.location = document.location.href.replace('https://', 'http://');
}
function bf_blReload() {
    window.location.reload(true);
}
function GoToBeFrugal(lnk) {
    try {
        if (window.opener != null && !window.opener.closed) {
            try {
                window.opener.open(lnk.href, '_blank');
                window.close();
            } catch (e2) {
                window.open(lnk.href, '_blank');
                window.close();
            }
        } else {
            window.open(lnk.href, '_blank');
            window.close();
        }
    } catch (e) { }
    return false;
}
