/* http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/ */


(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);
      
    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title

      $input.addClass(blurClass);
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

/**
  based on http://allinthehead.com/retro/338/supersleight-jquery-plugin
  modified to handle individual elements rather than children elements
  
  preferred usage:
    add class="r" to all elements with transparent pngs as background-image,
    set visibility: hidden for these elements for ie5/ie6 (conditional comments)
    $('.r').supersleight();
  **/

jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: 'x.gif',
		apply_positioning: false
    }, settings);
	
  if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4) {
    this.each(function(){
      var self = jQuery(this);
      
      // background pngs
      if (settings.backgrounds && self.css('background-image').match(/\-trans.png/i) !== null) {
        var bg = self.css('background-image');
        var src = bg.substring(5,bg.length-2);
        var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
        var styles = {
          'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
          'background-image': 'url('+settings.shim+')',
          'visibility': 'visible'
        };
        self.css(styles);
      };
      
      // image elements
      if (settings.imgs && self.is('img[src$=png]')){
        var styles = {
          'width': self.width() + 'px',
          'height': self.height() + 'px',
          'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')",
          'visibility': 'visible'
        };
        self.css(styles).attr('src', settings.shim);
      };
      
      // apply position to 'active' elements
      if (settings.applyPositioning && self.is('a, input') && self.css('position') === ''){
        self.css('position', 'relative');
      };
    });
  }
};

$(function() {
  $('.r').supersleight();
  
  // ie5, ie6 have problems with png transparency + input fields
  //if (!(jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4))
  $('input').hint();
});


// notification messages
$(document).ready(function() {
  /* handle dismiss message functionality */
  $('<a title="Dismiss message." href="#">Dismiss message.</a>').appendTo('#message-dismiss-link');
  
  $('#message-dismiss-link a').click(function() {
    $('#message').slideUp('normal');
    
    return false;
  });
});

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};

jQuery.round = function(val, decimals) {
  return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals);
}

jQuery.json = function(s) {
  return window["eval"]("(" + s + ")");
}

// coupon rating
function rateCoupon(link, url) {
  $.getJSON(url + '/json/true', function(json) {
    var span = $(link).parent('dd').children('span').get(0);

    if (json.error) {
      $(span).text(json.error);
    }
    else {
      json.votes = parseFloat(json.votes);
      var percent   = $.round(100.00 * json.rating / json.votes, 2);
      var className = (percent >= 60 ? 'success' : 'failure');

      $(span).text(percent + '% success rate');
      $(span).attr('class', className);
    }
    
    return true;
  });
}

$(document).ready(function() {
  /* ajax-ify coupon ratings */
  $('a.rater').click(function() {
    rateCoupon(this, this.href);
    return false;
  });
});


// stores autocomplete
$(document).ready(function() {
	$("#searchbox_store, #search_store").autocomplete("/misc/autocomplete-store.php", {
		width: 245,
		selectFirst: false,
		scroll: true,
		minChars: 1,
		scrollHeight: 300,
		cacheLength: 10,
		matchSubset: true,
		formatItem: function(row, i, n, value) {
		      row = $.json(row);
		      return row.name + '<br />';
		     
		    },
		formatResult: function(row) {
		      row = $.json(row);
		      return row.name;
		}
	}).result(function(event, data, formatted) {
    store = $.json(data);
	
	if(document.getElementById('restaurantid'))
	document.getElementById('restaurantid').value=store.id;
  
  });
});




// search autocomplete
$(document).ready(function() {

	$("#searchbox_query, #search_query").autocomplete("/misc/autocomplete-ajax.php", {
		width: 320,
		selectFirst: false,
		scroll: true,
		minChars: 2,
		scrollHeight: 300,
		cacheLength: 10,
		matchSubset: true,
		formatItem: function(row, i, n, value) {
		      row = $.json(row);
		      return row.name + '<br /><span>' + row.url + '</span>';
		      return row.url;
		    },
		formatResult: function(row) {
		      row = $.json(row);
		      return row.name;
		}
	}).result(function(event, data, formatted) {
    store = $.json(data);
	
	//location.href = 'coupons/' + store.url; // KIPL
	
	if(store.type=='restaurant')
    	location.href = 'http://www.dealtherapy.com/restaurants/' + store.name;
	if(store.type=='printables')
    	location.href = 'http://www.dealtherapy.com/printables/' + store.name;
	if(store.type=='store')
    	location.href = 'http://www.dealtherapy.com/coupons/' + store.url;
  
  });
});
//disable the curve corner issue fix
//$.fn.curvycorners = function(classname) {
 // var settings = {
 //   tl: {radius: 5},
 //   tr: {radius: 5},
  //  bl: {radius: 5},
  //  br: {radius: 5},
  //  antiAlias: true,
   // autoPad: false
  //}

  //var obj = new curvyCorners(settings, classname);
  //obj.applyCornersToAll();
//};


//$(function() {
 // $().curvycorners('corners');
//});

//$(function() {
  //$('#slider').flash({
   // src:    '/images/slider.swf',
   // width:   980,
   // height:  238
   // , wmode: 'opaque'
 // });
//});

})(jQuery);

function showRecaptcha(element, placeholder, buttonButton, submitButton, textId) {
  Recaptcha.create("6LckbgYAAAAAAGbEybsiIs-tScdtZQfGbKJynFq8", placeholder, {
        tabindex: 0,
        callback: Recaptcha.focus_response_field
  });
  document.getElementById(element).style.zIndex = 1;
  document.getElementById(buttonButton).style.display = 'none';
  document.getElementById(submitButton).style.visibility = 'visible';
  document.getElementById(submitButton).className = 'visible';

  document.getElementById(element).style.backgroundColor = 'white';
  document.getElementById(element).style.border = '1px solid #eeeeee';

  document.getElementById(textId).innerHTML = 'Please confirm the security code below.';
  document.getElementById(textId).style.display = 'block';
  document.getElementById(textId).style.textAlign = 'center';
}
