$(document).ready(function(){

  $(".search-active").mousedown(function(){
    $(this).css("background-position","0 -58px");
  }).mouseup(function(){
    $(this).css("background-position","0 0");
  });
  
  $("#search-submit").mousedown(function(){
    var templateBase = $("#template-directory").attr("href");
    $(this).attr("src",''+templateBase+'/images/find-active.gif');
  }).mouseup(function(){
    $(this).attr("src",''+templateBase+'/images/find-spinner.gif');
  });

  
  $(".get-rss").mousedown(function(){
    $(this).css("background-position","0 -45px");
  }).mouseup(function(){
    $(this).css("background-position","0 0");
  });

// trigger lightbox on exit
//$('.click').livequeryquery('click', function(event) {
  
  $('.click').livequery('click', function() {
    $(this).parent().parent().parent().parent().parent().parent().find('.button.click').hide();
});


$('.activate').livequery('click', function() {

//var subscribe_html = $(".subscribe").html();
//$("#test-html").html('<div class="MailPress">' + subscribe_html + '</div>');

var bitlyUrl = $(this).parent().parent().parent().find(".bitly-url").attr("href");
var tweetUrl = $(this).parent().parent().parent().find(".tweet-this").attr("href");
var facebookUrl = $(this).parent().parent().parent().find(".fb-share").attr("href");
var couponTitle = $(this).parent().parent().parent().find(".coupon-title").html();
var couponCat = $(this).parent().parent().parent().find(".post-cat img").attr("title");
var templateBase = $("#template-directory").attr("href");
$("#share-html").html('<h2 style="text-align:right;float:left;width:70px;color:#999999;font-size:1em;font-weight:lighter;">Share This<br />Coupon:</h2><a id="show-link" rel="nofollow" href="#" onclick="javascript: pageTracker._trackPageview(\'/link/'+couponCat+'/lightbox\');" ><img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_link.gif" /></a><a onclick="javascript: pageTracker._trackPageview(\'/fbshare/'+couponCat+'/lightbox\');"rel="nofollow" target="_blank" href="'+facebookUrl+'"> <img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_facebook.gif" /></a><a onclick="javascript: pageTracker._trackPageview(\'/tweet/'+couponCat+'/lightbox\');" href="'+tweetUrl+'"rel="nofollow" target="_blank" ><img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_twitter.gif" /></a><a onclick="javascript: pageTracker._trackPageview(\'/emailshare/'+couponCat+'/lightbox\');" rel="nofollow" href="mailto:?subject='+couponTitle+' '+couponCat+' Coupon &body=Check out this coupon from SaveBrite.com '+bitlyUrl+'"><img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_email.gif" /></a>');
$.fx.speeds._default = 1000;

lightboxExit = $('#lightbox-exit').html();

var dialog = $('#lightbox-exit')
.load(lightboxExit)
.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
show: 'blind',
hide: 'explode'
});

//dialog.appendTo($("form:first"));

var vote = $(this).parent().parent().parent().find(".vote").html();
if(vote == undefined){//if we are on product page
var vote = $(this).parent().parent().find(".click span").attr("title");
}

$("#lightbox-exit .vote").html(vote);
$("#lightbox-exit .cat-title").html(couponCat); //update coupon cat in lightbox


var Code = $(this).parent().parent().find(".click span").attr('title');
if(Code != undefined){
var hiddenCode = 'Coupon Code:<br /><strong>'+Code+'</strong>';
$("#lightbox-exit .show-code").html(hiddenCode);
}


// end email lightbox

$(".post-cat").each(function(){
  var Code = $(this).parent().parent().find(".click span").attr('title');
  if(Code != undefined){
  $(this).html('Coupon Code:<br /><span>'+Code+'</span>');
  }
}
);

//$('#cat').bgiframe(); // fix ie selec from poping above dialog

//initiate modal dialog
dialog.dialog('open');

});


/* Old Facebook Fan Lightbox
//trigger facebook dialog 20% of the time
var rand_no = Math.ceil(100*Math.random());

if(rand_no > 80){
var template_base = $("#template-directory").attr("href");
var dialog = $('#facebook-lightbox')
.html('<div class="facebook-module"><script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script><script type="text/javascript">FB.init("6d912ef1a774f6e709cfa18f077d77f7");</script><fb:fan profile_id="112130948829116" stream="" connections="10" width="300" height"250"></fb:fan></div><a href="http://www.facebook.com/pages/SaveBrite/112130948829116"><img align="left" src="'+template_base+'/images/iPad.gif" /></a>')
.dialog({
autoOpen: false,
height: 320,
width: 650,
modal: true,
show: 'blind',
hide: 'explode'
});

dialog.dialog('open');
}
*/

$('.submit-coupon').livequery('click', function() {
  submitHtml = $('#coupon-submit').html();
  var dialog = $('#coupon-submit')
  .load(submitHtml)
  .dialog({
    autoOpen: false,
    height: 720,
    width: 650,
    modal: true,
    show: 'blind',
    hide: 'explode'
  });

  dialog.dialog('open');
});


/*  Old EmailCapture
// on succesfull rating
$('.post-ratings img').click(function(){

var bitlyUrl = $(this).parent().parent().parent().find(".bitly-url").attr("href");
var tweetUrl = $(this).parent().parent().parent().find(".tweet-this").attr("href");
var facebookUrl = $(this).parent().parent().parent().find(".fb-share").attr("href");
var couponTitle = $(this).parent().parent().parent().find(".coupon-title").html();
var couponCat = $(this).parent().parent().parent().find(".post-cat img").attr("title");
var templateBase = $("#template-directory").attr("href");
$("#share-html").html('<h2 style="text-align:right;float:left;width:70px;color:#999999;font-size:1em;font-weight:lighter;">Share This<br />Coupon:</h2><a id="show-link" rel="nofollow" href="#" onclick="javascript: pageTracker._trackPageview(\'/link/'+couponCat+'/lightbox\');" ><img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_link.gif" /></a><a onclick="javascript: pageTracker._trackPageview(\'/fbshare/'+couponCat+'/lightbox\');"rel="nofollow" target="_blank" href="'+facebookUrl+'"> <img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_facebook.gif" /></a><a onclick="javascript: pageTracker._trackPageview(\'/tweet/'+couponCat+'/lightbox\');" href="'+tweetUrl+'"rel="nofollow" target="_blank" ><img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_twitter.gif" /></a><a onclick="javascript: pageTracker._trackPageview(\'/emailshare/'+couponCat+'/lightbox\');" rel="nofollow" href="mailto:?subject='+couponTitle+' '+couponCat+' Coupon &body=Check out this coupon from SaveBrite.com '+bitlyUrl+'"><img align="right" width="96" class="share-block" src="'+templateBase+'/images/button_email.gif" /></a>');
$.fx.speeds._default = 1000;
$("#pop-email").html('');
$("#lightbox-headline").html('');

lightboxExit = $('#test-html').html('<img align="right" style="margin:0 50px 10px 10px;" width="100" src="'+templateBase+'/images/ninja.png" /><h2>Want an even sweeter deal? Get an extra <strong>5% Cash-Back</strong> on you\'re purchase for each friend you refer to SaveBrite.com*</h2><br /><p>*In order to qualify for you\'re cash back, your friend must use a coupon on a purchase through SaveBrite.com. You can share this coupon with the following services:</p>');

var dialog = $('#lightbox-exit')
.load(lightboxExit)
.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
show: 'blind',
hide: 'explode'
});

dialog.dialog('open');

$("#lightbox-exit .vote").html('');
});
*/

//Larger thumbnail preview

$(".shopping_offerimage").hover(function(){
  $(this).css({'z-index' : '100'});
  $(this).addClass("hover");
  $(this).find('img').addClass("hover").stop()
  .animate({
    marginTop: '-110px',
    marginLeft: '-110px',
    top: '50%',
    left: '50%',
    width: '200px',
    padding: '20px'
    }, 200);

  } , function() {
    $(this).css({'z-index' : '0'});
    $(this).removeClass("hover");
    $(this).find('img').removeClass("hover").stop()
    .animate({
      marginTop: '0',
      marginLeft: '0',
      top: '0',
      left: '0',
      width: '110px',
      padding: '5px'
      }, 400);
    });



    // load howto video into a lightbox
    $('#howto-trigger').livequery('click', function() {
      submitHtml = $('#howto-video').html();
      var dialog = $('#howto-video')
      .load(submitHtml)
      .dialog({
        autoOpen: false,
        height: 450,
        width: 675,
        modal: true,
        show: 'blind',
        hide: 'explode'
      });

      dialog.dialog('open');
    });


    // $('#rating_' + post_id).click(function(){
      // $(this).parent().parent().parent().hide();
      // });

      // initialize scrollable together with the circular plugin
      //$("#infinite").scrollable();


      // initialize vertical scrollable
      /*$("div.scrollable.vertical").scrollable({
      vertical:true,
      size: 3
      }).circular().autoscroll({autopause:true,autoplay: true,interval:3000});
      */

      // trigger hidden link that submits outbout url
      $('.click').livequery('click', function() {
        //$(this).nextAll("form:first").submit();

        if ($('body').is('.products')) {
          var href = $(this).closest(".shopping_offer").find(".code").attr('href');
          window.open(href,'NewWin','status=yes,scrollbars=yes');
          window.blur(); // popup window on products pages
        }else{
          var href = $(this).closest(".coupon").find(".code").attr('href');
          window.open(href,'NewWin','status=yes,scrollbars=yes');
          window.focus(); // hide window on coupons
        }

      });

/* Old Popup Window
// trigger popup window to show coupon
$('.click').popupWindow({
  height:500,
  width:540,
  top:50,
  left:50,
  scrollbars:1
});
*/

// show popup window w/featured coupons
$(".click").livequery(function(){
  $(this).popupwindow();
});


// show more sidebar categories
$('.show-more').livequery('click', function() {
  $(this).parent().find("ul.wp-tag-cloud").addClass('expanded');
  $(this).text('Show Less');
  $(this).addClass('show-less').removeClass('show-more');

  // show less sidebar categories
  $('.show-less').livequery('click', function() {
    $(this).parent().find("ul.wp-tag-cloud").removeClass('expanded');
    $(this).text('Show More');
    $(this).removeClass('show-less').addClass('show-more');
  });
});



// Zero Clipboard Copy 2 Click
var clip = null;
var linktag = null;
var gotolink = null;
var pos;
var x;
var y;
var mouseY = null;
var templateBase = $("#template-directory").attr("href");
ZeroClipboard.setMoviePath(templateBase+'/js/zeroclipboard/ZeroClipboard.swf');
clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
$().mousemove(function(e) {
  x = e.pageX;
  y = e.pageY;
  if (y >= (mouseY + 20) || y <= (mouseY - 20)) {
    $("#code_tip").fadeOut(200);
  };
});

$('a.code').livequery('mouseover', function() {
  $('body').append('<div id="code_tip">Click to copy code and open site</div>');
  //alert(this.innerHTML);
  gotolink = $(this).attr("href");
  mouseY = y;
  clip.setText(this.innerHTML);
  linktag = $(this).Attributes;
  if (clip.div) {
    clip.receiveEvent('mouseout', null);
    clip.reposition(this);
    } else clip.glue(this);
    clip.receiveEvent('mouseover', null);
  });

  function mouse_over_handler(client) {
    $("#code_tip").css({
      "left": x + "px",
      "top": y + 20 + "px"
      }).fadeIn(200);
    }
    function mouse_out_handler(client) {
      $("#code_tip").fadeOut(200);
      clip.hide();
    }
    function mouse_up_handler(client) {
      var storeWin = window.open(gotolink);
      if (storeWin) {
        return false;
      } else {
        document.location = gotolink;
      }
    }
    clip.addEventListener('onMouseOver', mouse_over_handler);
    clip.addEventListener('onMouseOut', mouse_out_handler);
    clip.addEventListener('onMouseUp', mouse_up_handler);


    //sign in popup
    /* $(".signin").click(function(e) {
    e.preventDefault();
    $("fieldset#signin_menu").toggle();
    $(".signin").toggleClass("menu-open");
    });*/

    $("fieldset#signin_menu").livequery('mouseup', function() {
      return false
    });

    $(document).livequery('mouseup', function(e) {
      if($(e.target).parent("a.signin").length==0) {
        $(".signin").removeClass("menu-open");
        $("fieldset#signin_menu").hide();
      }
    });

    // tooltip
    $('.q_mark').tipsy({gravity: 's'}); // nw | n | ne | w | e | sw | s | se
    /*$('.tooltip').livequery('mouseover', function(){
    $(this).tipsy({gravity: 's'});
    });
    */

    //toggle
    $('#t2').livequery('click', function() {
      $("#query").removeClass("multi");
    });

    $('#t1').livequery('click', function() {
      $("#query").addClass("multi");
    });


    // Check the radio button associated with the label
    $('span.reason').click(function(e){
      $(this).prev('input:first').attr('checked',true);
    });

    // Bind function to the click events of the navigation links
    /* $('#menu li a').click(function(e) {
    // Prevent the browser from loading the page the user tried to visit
    e.preventDefault();

// Save the URL of where the user wanted to go
destination = $(this).attr('href');

// Show the exit survey
showExitSurvey();
});

*/

function PopIt() {
  showExitSurvey();
  window.onbeforeunload = UnPopIt;
  // Save the URL of where the user wanted to go
  return "Before you go...Would you mind taking a brief survey?";
}

function UnPopIt() { /* nothing to return */ }

//window.onbeforeunload = PopIt;

// prevent interal/external links from triggering exit poll
// $("a[id!=trigger]").click(function(){ window.onbeforeunload = UnPopIt; });
// $("form").submit(function(){ window.onbeforeunload = UnPopIt; });

function showExitSurvey()
{
  $('#survey').dialog({
    width: 500,
    bgiframe: true,
    modal: true,
    close: function() { $('#survey').dialog('destroy'); }, // Destroy the dialog. Allows it to appear again if closed.
    buttons: {"Continue" : log_answer } // Add a continue button that logs the answer when clicked
  });
}

function log_answer() {
  var templateBase = $("#template-directory").attr("href");
  //var destination = window.location.href;
  $.ajax({
    type : "GET",
    cache : false,
    url: ""+templateBase+"/survey-ajax",
    data: $("#survey-form").serialize(),
    dataType: "text",
    beforeSend: function() { $('#survey').dialog('destroy'); },
    complete: function() { /*window.location.replace(destination);*/ }
});
return;
}

function mail_rating(maildata) {
  var templateBase = $("#template-directory").attr("href");
  //var destination = window.location.href;
  $.ajax({
    type : "GET",
    cache : false,
    url: ""+templateBase+"/downvote",
    data: maildata,
    dataType: "text"
});
return;
}

// 
$('.post-ratings').find('img:first').click(function(){
  maildata = new Object();
  maildata.id = $(this).parent().attr('id');
  mail_rating(maildata);
  return;
});

// track email subscriptions
$('.MailPressFormSubmit').click(function(){
  pageTracker._trackPageview('/subscription/');
});

});
