if ($("#storeAC").length > 0) {
  if (jQuery.trim($('#storeAC')[0].value).length != 0) {
    $('#storeAC')[0].value = "";
  }
  $("#storeAC").focus(function() {
    $("#frmStoreAC label").addClass("hidden");
  });
  $("#storeAC").blur(function() {
    if (jQuery.trim(this.value).length == 0) {
      $("#frmStoreAC label").removeClass("hidden");
    }
  });
};


if ($("#searchQuery").length > 0) {
  $("#searchQuery").keypress(function() {
    $('#sitesearch label').addClass('hidden');
  });
  if (jQuery.trim($('#searchQuery')[0].value).length != 0) {
    $('#sitesearch label').addClass('hidden');
  }
  $("#searchQuery").focus(function() {
    $("#sitesearch label").addClass("hidden");
  });
  $("#searchQuery").blur(function() {
    if (jQuery.trim(this.value).length == 0) {
      $("#sitesearch label").removeClass("hidden");
    }
  });
};

if ($("#slideShow").length > 0) {
  $("#slideShow").tabs({
    fx: {
      opacity: 'toggle'
    }
  }).tabs('rotate', 3500, true);
  $("#slideShow").hover(
  	function() {
  		$(this).tabs('rotate',0, true);
  	},
  	function() {
  		$(this).tabs('rotate',3500, true);
  	}
  )
}
if ($("#slideNav").length > 0) {
  $("#slideNav").before('<div id="slideBL"></div><div id="slideBR">');
  $("#slideNav a:last").css({
    width: '114px'
  });
};
if ($("#favCoupTabs").length > 0) {
  $("#favCoupTabs").tabs();
};
if ($("#coupTabs").length > 0) {
  $("#coupTabs").tabs();
};
$('.min').toggleClass('max');
if ($("#emailSignUpForm").length > 0) {
  $("#emailSignUpForm").validate({
    errorLabelContainer: "#emailSignUpFormError"
  });
};
if ($("#alertSignUpForm").length > 0) {
  $("#alertSignUpForm").validate({
    errorLabelContainer: "#alertSignUpFormError"
  });
};
if ($("#CCLocalCoupForm").length > 0) {
  $("#CCLocalCoupForm").validate({
    errorLabelContainer: "#CCLocalCoupFormError"
  });
};
if ($("#emailSignUpFormBtm").length > 0) {
  $("#emailSignUpFormBtm").validate({
    errorLabelContainer: "#emailSignUpFormErrorBtm"
  });
};
var storeID;
var storeName;
var userCoup;
function formatStore(row) {
  $("#frmStoreACError").html('');
  return row[1];
}
$("#storeAC").autocomplete('/search/autocomplete-store', {
  formatItem: formatStore,
  delay: 10,
  selectFirst: true
});
$("#storeAC").result(function(event, data, formatted) {
  if (data) {
    storeID = data[0];
    storeName = data[1];
    userCoup = data[2];
    $("#storeAC").val(data[1]);
    $("#storeAC")[0].blur();
    if (data[2] == 1) {
      $("#frmStoreACError").html('<label generated="true" for="storeAC">We\'re sorry, but '+data[1]+'doesn\'t allow us to post user-submitted coupons on our site.</label>');
    } else {
      $.fancybox({'autoScale': false,
				'autoDimensions': false,
		    	'type': 'iframe',
		    	'href': '/stores/submit-coupon/store/' + data[0] + '?layout=false',
				'height': 500,
				'width': 500,
				'padding': 0
				
	  });
    }
  } else {
    alert("Oops");
  }
});
$("#frmStoreAC").submit(function() {
  if ($("#storeAC").val() != storeName) {
    $("#frmStoreACError").html('<label generated="true" for="storeAC">We\'re sorry but that doesn\'t match one of our stores. Please try again.</label>');
  } else if ($("#storeAC").val() == storeName && userCoup == 0) {
    $.fancybox({'autoScale': false,
		'autoDimensions': false,
    	'type': 'iframe',
    	'href': '/stores/submit-coupon/store/' + storeID + '?layout=false',
		'height': 500,
		'width': 500,
		'padding': 0
		
    });
  } else if ($("#storeAC").val() == storeName && userCoup == 1) {
    $("#frmStoreACError").html('<label generated="true" for="storeAC">We\'re sorry, but '+storeName+' doesn\'t allow us to post user-submitted coupons on our site.</label>');
  }
  return false;
});
$(".min h2 a").click(function() {
  $(this).parent().parent().toggleClass("max");
  return false;
});
$(".tabs a").click(function() {
  if (($(this).attr("id") == "tbBtn_print") || ($(this).attr("id") == "tbBtn_local")) {
    $(".min").addClass("none");
  } else if (($(this).attr("id") == "tbBtn_online")) {
    $(".min").removeClass("none");
  };
});
$("#bm a:not(.peel)").each(function() {
  $(this).attr("target", "_blank");
});
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}
function eraseCookie(name) {
  createCookie(name, "", -1);
}
var topAdCookie = readCookie("CC_topAdSpace");
if (($("#topAd iframe").length > 0) || ($("#topAd #google_ads_div_cc_800x20_sliver").length > 0) || ($("#topAd #google_ads_div_cc_800x20_sliver_ad_container").length > 0)) {
  var topAdLoaded = true;
} else {
  var topAdLoaded = false;
}
if ((topAdLoaded == true) && !topAdCookie){
  $("#topAd").append('<a id="topAdClose" href="#closeAd" title="Close this ad"><img src="http://d5ry64b8sxkjy.cloudfront.net/prd/www/120/res/img/base/btn_close.png" alt="Close" width="14" height="14" border="0" /></a>');
  setTimeout('$("#topAd").slideDown("slow")', 500);
  } else {
  $("#topAd").hide();
}
$("#topAdClose").click(function() {
  createCookie("CC_topAdSpace", "Closed", 1);
  $("#topAd").slideUp("slow");
  return false;
});

//Flash detection
//http://www.featureblend.com/license.txt
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";

// Clipboard stuff
if(FlashDetect.versionAtLeast(9)){
	var hovered;
	var clip = null;
	var linktag = null;
	var gotolink = null;
	var pos;
	var x;
	var y;
	var mouseY = null;
	ZeroClipboard.setMoviePath('http://d5ry64b8sxkjy.cloudfront.net/prd/www/70/res/swf/ZeroClipboard.swf');
	clip = new ZeroClipboard.Client();
	clip.setHandCursor(true);
	$("body").mousemove(function(e) {
	  x = e.pageX;
	  y = e.pageY;
	  if (y >= (mouseY + 20) || y <= (mouseY - 20)) {
	    $("#codeTip").fadeOut(200);
	  };
	});
	$(function() {
	  $('body').append('<div id="codeTip">Click to copy code and open site</div>');
	});
	$('a.cc-code').live('mouseover', function() {
		hovered = $(this).parents("li.offer");
		var linkWidth = $(this).width();
	
		$(".exclusive").removeClass("hov");
	
	    gotolink = $(this).attr("href");
	    mouseY = y;
	    clip.setText(this.innerHTML);
	    linktag = $(this).Attributes;
	    if (clip.div) {
	    	clip.div.style.width = linkWidth+"px";
	    	$("#ZeroClipboardMovie_1").css("width",linkWidth);
	
			clip.receiveEvent('mouseout', null);
			clip.reposition(this);
	    } else clip.glue(this);
	    clip.receiveEvent('mouseover', null);
	});
	function my_mouse_over_handler(client) {
	  $(hovered).addClass("hov");
	  $("#codeTip").css({
	    "left": x + "px",
	    "top": y + 20 + "px"
	  }).fadeIn(200);
	}
	function my_mouse_out_handler(client) {
	  $("#codeTip").fadeOut(200);
	  clip.hide();
	}
	function my_mouse_up_handler(client) {
	  var storeWin = window.open(gotolink);
	  if (storeWin) {
	    return false;
	  } else {
	    document.location = gotolink;
	  }
	}
	clip.addEventListener('onMouseOver', my_mouse_over_handler);
	clip.addEventListener('onMouseOut', my_mouse_out_handler);
	clip.addEventListener('onMouseUp', my_mouse_up_handler);
}
$("div.catpod a").attr("href", "#");
$("div.catpod a").click(function() {
  if ($(this).parent().next('div.podContent').children().size() == 0) {
    var cat_id = $(this).parents('div.catpod').attr("id");
    var url = '/categories/homepage/niceurl/' + cat_id;
    $(this).parent().next('div.podContent').load(url);
  }
});
$("a.fb").each(function() {
  $(this).click(function() {
    u = $(this).attr("href");
    window.open(u, 'sharer', 'toolbar=0,status=0,width=626,height=436');
    return false;
  });
});

function removeCountdown() {
	$('#couponClub #signUpNow').remove();
}

var dontgo_shown = false;
var dontgo_timeout;
$(function() {
  if (readCookie('new') == null) {
    createCookie('new', location.href, 365);
  } else if (readCookie('new') != location.href) {
    createCookie('new', 'no', 365);
    dontgo_shown = true;
  }
  if (readCookie('rec') != null) {
	  dontgo_shown = true;
  }

  $().mousemove(function(e) {
    if (!dontgo_shown) {
      clearTimeout(dontgo_timeout);
      if (e.pageX > 0 && (e.pageY - $(window).scrollTop()) < 10) {
        dontgo_timeout = setTimeout('dontgo()', 700);
      }
    }
  });
});

function dontgo() {
  if ($('#dontgo').size() > 0) {
    $.fancybox({'autoScale': false,
				'autoDimensions': false,
		    	'content': $('#dontgo').html(),
    			'height': 368,
    			'width': 740,
    			'padding': 0
    			
    });
    $("#emailSignUpForm-dontgo").validate({
      errorLabelContainer: "#emailSignUpFormError-dontgo"
    });
    $("#emailSignUpForm-dontgo input.email").focus();
    dontgo_shown = true;
  }
}

$(function() {
  if ($('#visitUKOuter').size() > 0) {
    $.fancybox({'autoScale': false,
				'autoDimensions': false,
		    	'content': $('#visitUKOuter').html(),
				'height': 275,
				'width': 650,
				'padding': 0
    });
    _gaq.push(['_trackEvent', 'UK Popup', 'UK Popup Shown'])
  }

  $('#go2US a').click(function() {
	$.fancybox.close();
    document.cookie = 'ukpester=no; expires=Fri, 3 Aug 2042 20:47:11 UTC; path=/';
    _gaq.push(['_trackEvent', 'UK Popup', 'Stayed on CC'])
  });

  $('#dontShowUK').click(function() {
    document.cookie = 'ukpester=no; expires=Fri, 3 Aug 2042 20:47:11 UTC; path=/';
    $.fancybox.close();
  });

  $('#go2UK a').click(function() {
    _gaq.push(['_trackEvent', 'UK Popup', 'Went to UK'])
  });
});

$(function() {
	$('a.fancybox, a.fancybox-iframe').each(function() {
		var href = $(this).attr('href');
		var hrefQueryString = $.deparam.querystring(href);
		var opts = {'autoScale': false,
					'autoDimensions': false,
					'titleShow': false,
					'padding': 20,
					'width': parseInt(hrefQueryString['width']),
					'height': parseInt(hrefQueryString['height'])
					}
		if (typeof(hrefQueryString['inlineId']) != 'undefined') {
			opts['content'] = $('#' + hrefQueryString['inlineId']).html();
		} else if ($(this).hasClass('fancybox-iframe')) {
			opts['type'] = 'iframe';
			opts['padding'] = 0;
		}
		hrefQueryString['layout'] = 'false';
		opts['href'] = $.param.querystring(href, hrefQueryString);
		$(this).fancybox(opts);
	});

  $('a.modal').live('mouseover', function(){
  	$(this).fancybox({
      'scrolling' : 'no'
    })
  });

  if (($("#curlSlot a").length > 0)) {
    $("#pageCurl").show();
    var curlTimer = null;
    var tug = true;
    function curlTug() {
      if (tug == true) {
        $("#pageCurl").animate({width:"55px",height:"55px"},750).animate({width:"45px",height:"45px"},750);
        setTimeout(curlTug,4000);
      }
    }
  
    //Take the anchor tag from the msg_block and apply it to the curl
    var curlLink = $("#curlSlot a").attr("href");
    //alert(curlLink)
    $("#pageCurl a.curl").attr("href",curlLink);
  
    //Page Flip opening animation
    setTimeout('$("#pageCurl").animate({width:"95px",height:"95px"},750).delay(750).animate({width:"45px",height:"45px"},500)',500);
    
    //Start the "tugging" animation
    setTimeout(curlTug,6000);
  
    //Page Flip on hover
    $("#pageCurl").hover(
      function () {
        if (curlTimer) {
          clearTimeout(curlTimer);
          curlTimer = null;
        } else {
          tug = false;
          $("#pageCurl").stop().animate({width:"350px",height:"350px"},500).animate({width:"340px",height:"340px"},150).animate({width:"350px",height:"350px"},150);
        }
      },
      function () {
        curlTimer = setTimeout(function(){
          $("#pageCurl").stop().animate({width:"45px",height:"45px"},250);
          curlTimer = null;
          tug = true;
          setTimeout(curlTug,4000);
        }, 500);
      }
    );
  }
});

function assembleChartUrl(clicks, min, max) {
    // Adjust so we have a little flesh in our chart
    var renderMin = Math.round(min * .8);
    var renderMax = Math.round(max * 1.2);
    
    var chartServer = Math.floor(Math.random() * 10);
    
    var base = 'http://' + chartServer + '.chart.apis.google.com/chart';
    var args = {
        'cht': 'lc',  // linechart
        'chd': 't:' + clicks.join(','),  // values
        'chs': '180x76',  // size
        'chco': '0077cc',  // series colors
        'chls': '2.0,2.0,0.0',  // line styles
        'chf': 'bg,s,fff',  // solid fill
        'chm': 'B,e6f2fa,0,0.0,0.0',  // shape markers
        'chxt': 'x,y',  // turn on y axis labels
        'chxr': '1,' + renderMin + "," + renderMax,  // scale
        'chds': renderMin + ',' + renderMax, // give it min and max
        'chxs': '0,000000,0,0,_|1,000000,0,0,_', // HACK: this turns off the axis labels
        'chxl': '0:||1:|' // HACK: This is part two of the above, we want our values arbitrary
    };
    var url = base + '?';
    for (var prop in args) {
        url += prop + '=' + args[prop] + '&';
    }
    // Chomp off last &
    url = url.substring(0, url.length-1);
    return url;
}

/**
 * Parses a date string as passed from the server into a JS Date
 * object
 */
function parseDate(dateStr) {
    if (dateStr.indexOf(' ') == -1) {
        return new Date();
    }
    var dateChunks = dateStr.split(' ');
    var justDate = dateChunks[0];
    
    if (justDate.indexOf('-') == -1) {
        return new Date();
    }
    dateChunks = justDate.split('-');
    
    if (dateChunks.length == 3) {
        // Remember, JS dates are always off by one on month (starts counting at 0)
        return new Date(parseInt(dateChunks[0], 10), parseInt(dateChunks[1], 10)-1, parseInt(dateChunks[2], 10));
    }
    
    return new Date();
}

