// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(function() { 

	// Header Message Handlers
	$("#read_header_message a").click(function () {
		$("#read_header_message a").toggle();
	});	          
	// Expand Panel
	$("#read_more").click(function(){
		$("div#top_bar_header_message").slideDown("slow");	
	});	
	// Collapse Panel
	$("#read_less").click(function(){
		$("div#top_bar_header_message").slideUp("slow");	
	});		
 
	
  // Search Handlers
  $("#search_keyword, #search_keyword_error").focus(function(){
    if ( $(this).val() == 'Search Keyword')
      $(this).val('');
  });
  $("#search_keyword, #search_keyword_error").blur(function(){
    if ( $(this).val() == '')
      $(this).val('Search Keyword');
  });


  // Email Signup Handlers
  $("#email_signup_email_address").focus(function(){
    if ( $(this).val() == 'Email Address')
      $(this).val('');
  });
  $("#email_signup_email_address").blur(function(){
    if ( $(this).val() == '')
      $(this).val('Email Address');
  });


  // Navigation Menu Handlers
  var timeout;
  $(".menuDrop").hover(function() {
      var element = this;
      var show_function = function() {show_menuDrop(element);};
      timeout = setTimeout(show_function, 300);
    }, function() {
      var element = this;
      hide_menuDrop(element);
      clearTimeout(timeout);  
  });


  // Feedback Handlers
  $('#feedback_container').tabSlideOut({
    speed: 300,                               //speed of animation
    action: 'click',                          //options: 'click' or 'hover', action to trigger animation
    topPos: '172px',                          //position from left/ use if tabLocation is bottom or top
    imageWidth: '38px',                       //width of tab image            //Optionally can be set using css
    imageHeight: '186px',                     //height of tab image           //Optionally can be set using css
    tabHandle: '.handle',                     //class of the element that will become your tab
    tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
    pathToTabImage: '/images/feedback_right.png', //path to the image for the tab //Optionally can be set using css
    fixedPosition: true                      //options: true makes it stick(fixed position) on scroll
  });

  $('.handle').click(function() { $('#feedback_response').html(''); });

  $('#feedback_button').click(function() {
    if ($('#feedback_message').val() === '') {
      $('#feedback_response').html('Please enter some feedback!');
    } else {
      $.ajax({
        type: "POST",
        url: '/feedback',
        beforeSend : function (xhr) { 
          $('#feedback_response').html('');
          xhr.setRequestHeader('Accept-Encoding', 'identity'); 
        },
        dataType: "json",
        data: $('#feedback_message').serialize() + '&page=' + encodeURIComponent(window.location.href),
        success: function(resp_json) { 
          $('#feedback_message').val('');
          $('#feedback_response').html(resp_json);
          setTimeout(function() { $('.feedback_container').animate({right: '-' + parseInt($('.feedback_container').outerWidth(),10)}, 300).removeClass('open'); }, 2000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) { return false; }
      });
    }
  });

  // LivePerson handlers
  $("a._lpChatBtn").click(function() {
    lpButtonCTTUrl = 'http://server.iad.liveperson.net/hc/79835155/?cmd=file&amp;file=visitorWantsToChat&amp;site=79835155&amp;SESSIONVAR!skill=jewlr&amp;imageUrl=http://<%=request.host%>/images/jewlr/liveperson&amp;referrer='+escape(document.location);
    lpButtonCTTUrl = (typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl);
    lpButtonCTTUrl = ((typeof(lpMTag)!='undefined' && typeof(lpMTag.addFirstPartyCookies)!='undefined')?lpMTag.addFirstPartyCookies(lpButtonCTTUrl):lpButtonCTTUrl);
    window.open(lpButtonCTTUrl,'chat79835155','width=475,height=400,resizable=yes');
    return false;
  });  
  
  // BIFF Social Media Share Links
  $("a.biff_facebook_share").click(function() {
    var share_message = "I recently shopped at jewlr.com. My friends get 15% off all jewelry. If you recommend jewlr.com to your friends you can get your jewelry for Free";    
    open_facebook_share2($('#promo_link').val(), share_message);
    submit_ga_event_click('biff_facebook_share');
    return false;
  });

  $("a.biff_twitter_share").click(function() {
    var share_message = "I just shopped at jewlr.com. Get 15% off all jewelry today.";    
    open_twitter_share($('#promo_link').val(), share_message);
    submit_ga_event_click('biff_twitter_share');
    return false;
  });
  
  // Enable pretty popin links
  $("a[rel^='prettyPopin']").prettyPopin();

  // Set popup message to appear (if any);  
  setTimeout("$('#popupMessage').click();", 3000);

});

function show_menuDrop(element) {
  $(".subMenuContainer", element).slideDown("fast");
}

function hide_menuDrop(element) {
  $(".subMenuContainer", element).fadeOut("fast");
}

function number_to_currency(number, options) {
	try {
 		var options   = options || {};
		var precision = options["precision"] || 2;
 		var unit      = options["unit"] || "$";
 		var separator = precision > 0 ? options["separator"] || "." : "";
		var delimiter = options["delimiter"] || ",";
   
 		var parts = parseFloat(number).toFixed(precision).split('.');
		return unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString();
	} catch(e) {
		return number
	}
 }

function number_with_delimiter(number, delimiter, separator) {
	try {
		var delimiter = delimiter || ",";
 		var separator = separator || ".";

		var parts = number.toString().split('.');
		parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter);
		return parts.join(separator);
	} catch(e) {
		return number
	}
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.titleCase = function () {
	var str = "";
	var wrds = this.replace('_', ' ').split(" ");
	for(keyvar in wrds)
	{
	str += ' ' + wrds[keyvar].substr(0,1).toUpperCase()
	 + wrds[keyvar].substr(1,wrds[keyvar].length).toLowerCase();
	}
   return str.ltrim();
}

function swapImages() {
  var $active = $('#myGallery .active');
  var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery div:first');
  $active.fadeOut(function(){
  $active.removeClass('active');
  $next.fadeIn().addClass('active');});
}


function submit_ga_tracker(tracking_path) {
	if (!(typeof pageTracker === "undefined")) {		
		pageTracker._trackPageview(tracking_path);	
	}	
}

function submit_ga_event_click(click_type) {
	if (!(typeof pageTracker === "undefined")) {		
		pageTracker._trackEvent('Link', click_type);	
	}	
}

function submit_email_signup() {
	submit_ga_event_click("email-signup")
	return true;
}

function open_facebook_share(url, message) {
  var share_url  = 'http://facebook.com/sharer.php?'
                    + 'u=' + encodeURIComponent(url)
                    + '&t=' + encodeURIComponent(message);
  submit_ga_event_click("facebook-share");
  window.open(get_redirect_url(share_url),"share_window","status=1");
}

function open_facebook_share2(url, message) {
  var share_url  = 'http://facebook.com/sharer.php?s=100'
                    + '&p[title]='
                    + '&p[url]=' + encodeURIComponent(url)
                    + '&p[summary]=' + encodeURIComponent(message)
                    + '&p[images][0]=' + encodeURIComponent( $('.biff_item_thumbnail').val() );

  submit_ga_event_click("facebook-share");
  window.open(get_redirect_url(share_url),"share_window","status=1");
}

function open_twitter_share(url, message) {
  var share_url  = 'http://twitter.com/home?'
                  + 'status=' + encodeURIComponent(message + " | " + url);
  submit_ga_event_click("twitter-share");
  window.open(get_redirect_url(share_url),"share_window","status=1");
}

function get_redirect_url(url) {
  return( '/redirector?u=' + encodeURIComponent(url) );
}