if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

function for_page(anchor)
{
	var regex = new RegExp("\#"+anchor);
	return regex.exec(window.location.href);
}

// == DEBUG SETUP =========================================
if(window['debug'] === undefined) {
  window.debug = function(q,w,e,r){  
    try { if (typeof console != 'undefined') console.log.apply(console,arguments); } 
    catch(err){ if (typeof console != 'undefined')  console.log(q,w,e,r); }
  }
}

// catch all document.write() calls
// document._write = document.write;
// document.write = function(q){ 
//   if (q.match(/docwriteregextopassthrough/)) document._write(q);  
//   debug('document.write(): ',q); 
// }

// ===============
// = OBJECT: SAFETYFLAG =
// ===============
window.SAFETYFLAG = {
	
	// common domready code that runs on all pages
	common:{
		
		// code effecting visual look of the page (reason why it fires first / inits)
		init:function()
		{
			
			fc_tb_WIDTH = 650;
			fc_tb_HEIGHT = 400;

			// add the required class to phone number if we're on checkout
			jQuery("#customer_phone").addClass("fc_required");
			// add an asterisk to the label
			jQuery("li.fc_customer_phone label.fc_pre").append("<span class=\"fc_ast\">*</span>");
			// Now add the onblur error checking events
			jQuery("#customer_phone").blur(function() {
				if (this.value == "") {
					FC.checkout.updateErrorDisplay(this.name,true);
				} else {
					FC.checkout.updateErrorDisplay(this.name,false);
				}
			});

			jQuery('a.print').click(function(){
			  window.print();
			  return false;
			});

			jQuery('#q').click(function(){
			  if(this.value == "Product Search")
			    this.value="" 
			}).blur(function(){
			  if(this.value == "")
			    this.value="Product Search"
			});

			// set the ie6 variable to true if they're using ie7
			jQuery.browser.ie7 = (jQuery.browser.msie && jQuery.browser.version == 7);
			jQuery.browser.ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);
			if (jQuery.browser.ie6){ jQuery('body').addClass('ie6'); }; // SAFETYFLAG.common.pngfix('');
			if (jQuery.browser.ie7){ jQuery('body').addClass('ie7') };
			if (jQuery.browser.msie){ jQuery('body').addClass('ie') };
      
		  // add last-child class for IE
      if (jQuery.browser.msie)
      {
        jQuery('#header #nav li:last-child').addClass('last-child');
      }


			//fire bug lite - to activate firebug lite, add "?fbug=true" to URL as querystring
		  	if (!!document.location.search.match(/fbug=true/)){ jQuery.getScript('https://getfirebug.com/releases/lite/beta/firebug.jgz',function(){ firebug.init(); }); }
		
			// catch ajax errors
		  	jQuery(document).ajaxError(function(){ debug('ajax error:',arguments); });
		
			// remove promos if there's nothing in there
			if(jQuery('p#promos').html() && jQuery('p#promos').html().trim() == "")
			{
				jQuery('p#promos').remove();
			}
			
			// remove any empty UL tags in the sidebar
			jQuery('#sidebar li.category ul:empty').remove();
			
			// set the very top-most navigation item as current if we're in a sub-category
			topmost_category = jQuery('#sidebar li ul li a.current').closest('ul').parent().find('a:first');
			if (topmost_category && topmost_category[0])
			{
				top_href = topmost_category[0].href;
				top_href = "/products"+top_href.split('/products')[1];
				jQuery('#header #nav li a[href="'+top_href+'"]').addClass('current');
			}

      if(jQuery('a[href*="download/secure"]').length)
      {                                                                                                                                           
        jQuery('#footer').after('<div id="passprompt"><h2>Please enter password</h2><p>In order to view this file you must enter the password shared with you by Safetyflag. After entering the password in the following filed, press your enter key.</p><form method="GET" action=""><input type="hidden" name="targ" id="targ" value="" /><input type="text" value="" name="password" id="password" /></form></div>')
        jQuery('a[href*="download/secure"]').click(function(){
          jQuery('#targ').val(this.href);
          jQuery('#passprompt').show();
          jQuery('#passprompt form input').focus();
          return false;
        });
        jQuery('#passprompt form').submit(function(){
          distributer = jQuery('#targ').val().indexOf('price-list') > 0;
          govt = jQuery('#targ').val().indexOf('govt-list') > 0;
          if(govt && jQuery('#passprompt input#password').val()=="gsa"){ window.location.href="/download/secure/safetyflag-govt-price-list.pdf"; }
          else if(distributer && jQuery('#passprompt input#password').val()=="safetypays"){ window.location.href="/download/secure/safetyflag-price-list.pdf"; }
          else { alert('We are sorry - but the password you entered is incorrect. Please try again.'); }
          jQuery('#passprompt').hide();
          return false;
        });
      }
			
		},
		
		//code that doesn't effect the look of the page (hence, "finalize")
		finalize: function()
		{		
			// console.log("Fired: SAFETYFLAG.common.finalize()");
      jQuery('img[name="pphLoggerImage"]').hide();
		},
		
		// pngfix for legacy POS browsers
		// USE: SAFETYFLAG.common.pngfix('img.bigProdShot,a.thumb');
		pngfix: function(sel)
		{
			// ensure that conditional comments pull in the DD_belatedPNG js. Otherwise this will just return.
			if (typeof DD_belatedPNG == 'undefined'){  
				return; 
			} else {
				// delay pngfix until window onload
				jQuery(window).load(function(){ 
					jQuery(sel).each(function(){ 
						DD_belatedPNG.fixPng(arguments[1]); 
					});
				}); 
			}
		}, // SAFETYFLAG.common.pngfix

		// USE: SAFETYFLAG.common.show_tab('tab class');
		show_tab: function(to_view)
		{
			jQuery('#listings h2, #listings ul, #listings .container').removeClass('active');
			jQuery('#listings h2.'+to_view+', #listings ul.'+to_view+', #listings .container.'+to_view).addClass('active');
		},

		// USE: SAFETYFLAG.common.contains_colors();
		contains_colors: function()
		{
			has_colors = false;
			colors = jQuery("p.colors label span");
			skus_text = jQuery("p.skus").text().toLowerCase();
			colors.each(function(){
				if(skus_text.indexOf(jQuery(this).text().toLowerCase())>0){
					has_colors = true;
				}
			});
			return has_colors;
		}
	}, // end of SAFETYFLAG.common
	
	// ===========================================================================
	// = The following are for the pages. They're defined by the 'id' in <body>. =
	// = SAFETYFLAG.Util Looks to see what body id is and then fires off         =
	// = the page-specific methods.                                              =
	// ===========================================================================
	
	home:{
		
		init: function()
		{
			jQuery('#home #content h2').click(function(){
				
        if(this.id == "new_products" ){
          jQuery('#home #content').addClass('tall');        
        } else {
          jQuery('#home #content').removeClass('tall'); 
        }
				if(!jQuery(this).hasClass('active')){
					// alert('div#'+this.id);
					
					jQuery('h2.active').removeClass('active');
					jQuery('div.active').removeClass('active');
          

          //alert(jQuery('div#'+this.id));
          jQuery('h2#'+this.id).addClass('active');
          jQuery('div#'+this.id+'_div').addClass('active');
          
				}
			});
			
			//homepage specific PNGFIX ... same thing for the rest of the id's below, mgmt, news, etc	
			if (jQuery.browser.ie6){ /* SAFETYFLAG.common.pngfix('#'); */ }
			
      // background: #fff url(/images/home_01.jpg) right center no-repeat
      // jQuery('#home #content div').css('background', '#fff url(/images/home_0'+ (Math.floor(Math.random()*4)+1)  +'.jpg) right center no-repeat');
      jQuery('#home #content > div:first').css('background', '#fff url(/images/home_0'+ (Math.floor(Math.random()*4)+1)  +'.jpg) right center no-repeat');
      // jQuery('#home #content div').css('background', '#fff url(/images/home_02.jpg) right center no-repeat');

      jQuery('#distributers_div button').click(function() {
        jQuery(this).toggle();
        jQuery('.panel_container').animate({
          marginLeft: '-=876'
        }, 500, function() {
          // Animation complete.
        });
        return false;
      });
      
      jQuery('h2#distributers, p#return a').click(function() {
        if ($('.panel_container').css('margin-left') == "-876px")
        {
          jQuery('.panel_container').animate({
            marginLeft: '0'
          }, 500, function() {
            jQuery('#distributers_div button').toggle();
          });
        }
        return false;
      });
      
      jQuery("#mailer").validate();
      
      
		}	
		
	}, // end SAFETYFLAG.homepage()

  'product':{
    init: function()
    {
      jQuery('textarea#comments').click(function(){
        if(this.value == "Please add any additional comments here")
          this.value="" 
      }).blur(function(){
        if(this.value == "")
          this.value="Please add any additional comments here"
      });
			
      jQuery('p.submit input[type="submit"]').click(function(){
        if(jQuery('textarea#comments').val()=="Please add any additional comments here"){ jQuery('textarea#comments').val(''); }
        return true;
      });

      jQuery('input#customize').click(function(){
        product_url = Url.encode(window.location.href);    
        window.location.href = "/contact-safety-flag?product_url="+product_url;
      });
      

			var color_labels = jQuery('#product .product form p.colors label');
			color_labels.click(function(){
				// reset and animate
				jQuery('.skus > *').css('opacity', 1);
				jQuery('.skus input').removeAttr('disabled').attr('checked',false);
				jQuery('input[type="hidden"][name="price"]').val('');
				jQuery('span#price').html("$0.00");
				jQuery('span#price').animate({ backgroundColor: "yellow" }, 10).animate({ backgroundColor: "white" }, 700);
				
				color_labels.removeClass('active');
				jQuery(this).addClass('active');
				
				var color_filter = jQuery(this).attr('title');

        // force IE to click the radio button. too stupid to listen to the label that was clicked.
        jQuery('input#'+color_filter+':radio').click();

				if(SAFETYFLAG.common.contains_colors())
				{
					// let's filter out everything below if one of these is selected
					jQuery("p.skus label span.description").each(function(){
						description = this.innerHTML.toLowerCase();
						if(description.indexOf(color_filter) < 0)
						{
							jQuery(this).parent().animate({ opacity: 0.4 });
							jQuery(this).parent().prev().attr('disabled', true)
						}
					})
				}
				return
			});
			
			
			var size_labels = jQuery('#product .product form p.sizes label');
			size_labels.click(function(){
				size_labels.removeClass('active');
				jQuery(this).addClass('active');
				return
			});

      // if something's already checked then take care of everything in there already
      if(jQuery('p.skus input:radio:checked').length){
        jQuery('p.submit input.disabled').removeClass("disabled").removeAttr("disabled");
        jQuery('p.submit span').remove();
        pr = jQuery('p.skus input:radio:checked').attr('class');
        // set the price in the hidden field
        jQuery('input[type="hidden"][name="price"]').val(pr);
        calculated_price = parseFloat(pr) * parseInt(jQuery('input#quantity').val());
        jQuery('span#price').html("$"+calculated_price.toFixed(2));
        jQuery('span#price').animate({ backgroundColor: "yellow" }, 10).animate({ backgroundColor: "white" }, 700);
      }
			
			var sku_labels = jQuery('#product .product form p.skus label, #product .product form p.skus input');
			sku_labels.click(function(){

				pr = jQuery(this).attr('class');
				
				// set the price in the hidden field
				jQuery('input[type="hidden"][name="price"]').val(pr);
				
				// set the price on the page * the quantity
				calculated_price = parseFloat(pr) * parseInt(jQuery('input#quantity').val());
				jQuery('span#price').html("$"+calculated_price.toFixed(2));
				jQuery('span#price').animate({ backgroundColor: "yellow" }, 10).animate({ backgroundColor: "white" }, 700);

        // enable the add to cart button
        jQuery('p.submit input[type="submit"]:disabled').removeAttr("disabled").removeClass("disabled");
        jQuery('p.submit span').remove();

			});

			jQuery('input#quantity').change(function(){
				pr = jQuery('input[type="hidden"][name="price"]').val();
				calculated_price = parseFloat(pr) * parseInt(this.value);
				calculated_price = calculated_price.toFixed(2)
				if(isNaN(calculated_price))
				{
					calculated_price = '0.00';
				} 
				jQuery('span#price').html("$"+calculated_price);
				jQuery('span#price').animate({ backgroundColor: "yellow" }, 10).animate({ backgroundColor: "white" }, 700);
			});
			
 			$('a[rel*=facebox]').facebox({
			 	loadingImage:'/javascripts/plugins/facebox/loading.gif',
				closeImage :'/javascripts/plugins/facebox/closelabel.gif'
			})
    }
  },

  'default-content':{
    
    init: function(){
      if(jQuery('.contact-safety-flag').length)
      {
        product_url =  jQuery.query.get('product_url') 
        if (product_url.length > 0)
        {
          jQuery('textarea#message').val("I'd like more information or custom options for the following product:\n"+product_url);
        }
      }

      jQuery('#use_different_addresses').click(function(){
        if(jQuery('#fc_checkout_cart #fc_cart_container').hasClass('collapse'))
        {
          jQuery('#fc_checkout_cart .collapse').removeClass('collapse');
        } else {
          jQuery('#fc_checkout_cart #fc_cart_container').addClass('collapse');
        }
      });

      jQuery("#fc_shipping_methods_inner").ajaxComplete(function(event, request, settings){
        if (fc_json.total_weight > 150)
        {
          jQuery(this).html("<strong style='line-height:18px; font-size:13px; color:#CD2626'>Due to the size and/or weight of this order, it cannot be calculated by our shipping calculator.  This happens with some of our items.  Someone will contact you from Safety Flag for approval of freight charges shortly after you place your order.  You will not be charged until you approve the shipping amount.  You may also <a style='font-size:13px' href='http://safetyflag.com/contact-safety-flag' target='_blank'>contact us</a> for a quote if you would like.</strong>");
          // jQuery("#fc_complete_order_button_container").html("Please contact us to complete your order or limit the number of items in this order.");
        }
      });
     
    }

  },
	
	'product-listing':{
		
		init: function()
		{
			jQuery('#content li:contains("Flags, Markers, Misc.")').addClass('flags_markers_miscs');
			jQuery("#content a[href*='/products/29']").closest("li")[0].className = "flags__airport_runway_closed_miscs";
			jQuery("#content a[href*='/products/35']").closest("li")[0].className = "flags__bicycle_snow_tractor_pennant_s";

			// find the active one.
			$('#sidebar a.current').closest('li.category').addClass('current');
			$('ul:empty').remove();
			
			
			if($("#sidebar .current.category").children().size() == 1)
			{
				$("#sidebar .current.category").addClass('no-subcategories');
			}
		}
		
	}
	
} // END OF the SAFETYFLAG object literal

// ==========================================================================================
// = Here's the magic that triggers the dom ready code based on page id.                    =
// = Based on Paul Irish's exceptional code:                                                =
// = http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/  =
// ==========================================================================================

// ... don't touch!  Tsk tsk.

UTIL = {

	fire: function(func,funcname, args)
	{
		var namespace = SAFETYFLAG;  // indicate your obj literal namespace here
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function')
		{
  			namespace[func][funcname](args);
		} 
	}, // end of SAFETYFLAG.util.fire

	loadEvents: function()
	{

		var bodyId = document.body.id;

		// hit up common first.
		UTIL.fire('common');

		//hit page specific via  body ID
		UTIL.fire(bodyId);
		UTIL.fire('common','finalize');

	},

	// utility method w/a bunch of regex's
	validate_for: function(type, string)
	{
		var re;
		if(type=='url') { re = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/; }
		else if(type=='email') { re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/ }
		else if(type=='phone') { re = /^\(\d{3}\) ?\d{3}( |-)?\d{4}|^\d{3}( |-)?\d{3}( |-)?\d{4}/ }
		else if(type=='zip') { re = /^((\d{5}-\d{4})|(\d{5})|([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]\s?\d[A-Za-z]\d))$/ }
		else if(type=='money') { re = /^\$?(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})?|\d{1,3}(\.\d{0,2})?|\.\d{1,2}?)$/ }
		else if(type=='cc') { re = /^((4\d{3})|(5[1-5]\d{2}))(-?|\040?)(\d{4}(-?|\040?)){3}|^(3[4,7]\d{2})(-?|\040?)\d{6}(-?|\040?)\d{5}/ }
		return (re.test(string));
	}

} // end of UTIL

// LET 'ER RIP! ===================
$(document).ready(UTIL.loadEvents);
// ================================

var Url = {
   
  encode : function (string) {
    return escape(this._utf8_encode(string));
  },

  decode : function (string) {
    return this._utf8_decode(unescape(string));
  },

  _utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },

  _utf8_decode : function (utftext) {

    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }

    }

    return string;
  }
}

